質問

I am new to python and have done several searches on SO and google regarding this question.

How can I pass a variable pw, which is the user's password, to the input for popen.communicate?

Here is the code involved:

pw = getpass.getpass()
from subprocess import Popen, PIPE, STDOUT
            ssh_conn = Popen(["ssh", "-t", server, "sudo -S cp /etc/"+map, "/etc/"+map + "." +fulltime], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
            ssh_conn.communicate(input='pw\n')[0]

The code above appears to send the string 'pw' to standard input, instead I would like the value of the variable pw to be sent.

I realize that this approach is less than ideal and that there are other python modules that could do the job more simply, but I am not in a position to install any additional modules.

役に立ちましたか?

解決

Use str.format to insert the password into the string:

pw = getpass.getpass()
from subprocess import Popen, PIPE, STDOUT
ssh_conn = Popen(["ssh", "-t", server, "sudo -S cp /etc/"+map, "/etc/"+map + "." +fulltime], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
ssh_conn.communicate(input='{0}\n'.format(pw))[0]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top