13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python で sudo を呌び出しパスワヌドを自動入力

13
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?