13
13

More than 5 years have passed since last update.

Python で sudo を呼び出しパスワードを自動入力

Last updated at Posted at 2016-01-25

システム設定はいじらずに Python で完結するやり方。
Python3.5(3.4)~

sudo で端末以外からパスワードを入力するには -S オプションをつけて標準入力から渡す必要がある。改行文字も必要。

subprocess.run() (Python3.4 なら subprocess.check_output) の引数 input に「パスワード + 改行文字」をバイト列で渡す (引数 input が追加されたのは Python3.4 から)。

複数の ISO ファイルを順次マウントしてごにょごにょしてアンマウントする例。

import os
import subprocess
import getpass
import tempfile


# 一時的なマウントポイントの作成
mp = tempfile.mkdtemp()

# パスワードの入力
passwd = (getpass.getpass() + '\n').encode()

while True:

    path = input('Input file path (".quit" to quit) : ')

    if path == '.quit':
        os.rmdir(mp)
        raise SystemExit

    subprocess.run(('sudo', '-S',
                    'mount', '-t', 'iso9660', '-o', 'loop', path, mp),
                   input=passwd, check=True)

    """ごにょごにょ"""

    subprocess.run(('sudo', '-S', 'umount', mp), input=passwd, check=True)

13
13
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
13
13