0
0

More than 3 years have passed since last update.

[05] subprocessの代替パッケージ「sh」を使ってみる ... sudo をパスワード自動入力で使う

Posted at
本シリーズのトップページ
https://qiita.com/robozushi10/items/fabde36bb9a312347bc7

はじめに

一般的に Python で Linux コマンドを使う場合は subprocess を使うこと多い.
が、標準パッケージでは無いものの subprocess の代替である「sh」(amoffat/sh) も便利である.1

個人的な考えではあるが、「sh2」は標準パッケージでは無いので、職場などで使い込むと
他者の迷惑になり兼ねない。しかし、適度に使う分には subprocess よりも速く実装できて
好都合なので書き残しておく.

前項では sh.contrib.sudo を使ったが、パスワード入力が毎回発生してしまう.
そこで、本項では「「sh」で sudo を使いつつパスワードを自動入力する方法」を記す.

この実装方法であれば シェルスクリプトに近い感覚で実装できるので、
subprocess よりも速く実装できるのではないかと思う.

セットアップ

pip 等で sh をインストールする.
詳細は本項末尾の「参考情報」に記した.

使用例

005.py ... パスワードを自動入力する

公式ドキュメントsh.sudo.bake による実装方法にする.

なお、bake焼き固める の意味のようである.

コード

ここではパスワード🈲が「PASSWORD」であるものとする.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys; sys.dont_write_bytecode = True
import os
import traceback
import sh

if __name__ == '__main__':
  # password must end in a newline
  my_password = "PASSWORD\n" ##🈲

  # -S says "get the password from stdin"
  my_sudo = sh.sudo.bake("-S", _in=my_password)

  T = '{0}/work/'.format(os.environ['HOME'])
  for d in my_sudo.find(T, '-maxdepth', '4', '-type', 'd', '-name', '.git'):
    try:
      absp = os.path.abspath(d).rstrip()
      print(absp)
    except:
      traceback.print_exc(file=sys.stdout)

 

実行結果

/home/foo/work/wiki/02_software/xx/.git
/home/foo/work/wiki/02_software/git-lfs/.git
/home/foo/work/wiki/02_software/git-lfs2/.git
/home/foo/work/wiki/02_software/xx2/.git
/home/foo/work/LOCAL_GITLAB/fluentd/.git
/home/foo/work/fluentd/.git

参考情報

項目 URL 一言
Pypi sh https://pypi.org/project/sh/
公式ドキュメント - トップページ https://amoffat.github.io/sh/
公式ドキュメント - API逆引き https://amoffat.github.io/sh/reference.html
チュートリアル https://amoffat.github.io/sh/tutorials ここで実現したい機能を検索しながら使うことが多い
もた日記 https://wonderwall.hatenablog.com/entry/2017/07/30/083000

検討環境

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=18.04
DISTRIB_CODENAME=bionic
DISTRIB_DESCRIPTION="Ubuntu 18.04.4 LTS"

 

以上


  1. 私は職場で別の方が使用していて知った 

  2. パッケージ名が「sh」だと検索し辛い.. 

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0