6

コマンドを実行するためのpythonスクリプトを作成しています。これらのコマンドの中には、ユーザーがパスワードを入力する必要があるものがあります。標準入力にデータを入力しようとしましたが、機能しません。問題を表す 2 つの単純な python プログラムを次に示します。

入力.py

import getpass

print raw_input('text1:')
print getpass.getpass('pass1:')
print getpass.getpass('pass2:')

put_data.py

import subprocess
import getpass

def run(cmd, input=None):
    stdin=None
    if input:
        stdin=subprocess.PIPE
    p = subprocess.Popen(cmd, shell=True, stdin=stdin)
    p.communicate(input)
    if p.returncode:
        raise Exception('Failed to run command %r' % cmd)

input ="""text1
password1
password2
"""
run('python test.py', input)

そして、ここに出力があります

[guest@host01 ~]# python put_data.py 
text1:text1
pass1:

pass1 フィールドで停止します。ここに問題があります。パスワード フィールドにデータをフィードするためにデータを stdin に入れることができないのはなぜですか? パスワード フィールドにデータを書き込むにはどうすればよいですか?

4

2 に答える 2

2

そのような場合にはpexpectモジュールが必要です。

Pexpect は、子アプリケーションを生成して自動的に制御するための Python モジュールです。Pexpect は、ssh、ftp、passwd、telnet などの対話型アプリケーションの自動化に使用できます。

于 2011-01-28T10:31:00.910 に答える
0

このようなものを作成するために 2 つのクラスが必要になることは絶対にありません。put_data.py で init_() という別のメソッドを作成し次の行に沿って何かを行うだけです。

x = raw_input('text1:')
y = getpass.getpass('pass1:')
z = getpass.getpass('pass2:')

その後、 pexpect を使用して残りを実行できます。

child = pexpect.spawn(x, timeout=180)
while True:
   x = child.expect(["(current)", "new", "changed", pexpect.EOF, pexpect.TIMEOUT])
   if x is 0:
      child.sendline(y)
      time.sleep(1)
   if x is 1:
      child.sendline(z)
      time.sleep(1)
   if x is 2:
      print "success!"
      break

多田!おそらく、そのようなコードでは大量のエラーが発生するでしょう。Linux を使用している場合は、os.system("passwd") を実行し、シェルに残りを処理させる方が簡単な場合があります。また、getpass の使用をできる限り避けてください。

于 2011-09-19T16:23:29.613 に答える