天天看點

python subprocess popen輸入密碼_使用subprocess.Popen通過SSH或SCP發送密碼

下面是一個使用pexpect密碼的ssh函數:def ssh(host, cmd, user, password, timeout=30, bg_run=False):

"""SSH'es to a host using the supplied credentials and executes a command.

Throws an exception if the command doesn't return 0.

bgrun: run command in the background"""

fname = tempfile.mktemp()

fout = open(fname, 'w')

options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'

if bg_run:

options += ' -f'

ssh_cmd = 'ssh %s@%s %s "%s"' % (user, host, options, cmd)

child = pexpect.spawn(ssh_cmd, timeout=timeout)

child.expect(['password: '])

child.sendline(password)

child.logfile = fout

child.expect(pexpect.EOF)

child.close()

fout.close()

fin = open(fname, 'r')

stdout = fin.read()

fin.close()

if 0 != child.exitstatus:

raise Exception(stdout)

return stdout

使用scp應該可以實作類似的功能。