我试图使用scp (安全副本)命令运行subprocess.Popen。登录要求我发送密码:
from subprocess import Popen, PIPE
proc = Popen(['scp', "user@10.0.1.12:/foo/bar/somefile.txt", "."], stdin = PIPE)
proc.stdin.write(b'mypassword')
proc.stdin.flush()这将立即返回一个错误:
user@10.0.1.12's password:
Permission denied, please try again.我确定密码是正确的。我很容易通过手动调用shell上的scp来验证它。那为什么这个不起作用?
注意,有许多类似的问题,询问subprocess.Popen并发送密码用于自动SSH或FTP登录:
这些问题的答案不起作用和/或不适用,因为我使用的是Python 3。
发布于 2013-03-01 21:28:39
链接的第二个答案建议您使用普雷普 (这通常是与期望输入的命令行程序交互的正确方式)。
发布于 2013-03-01 22:05:24
下面是一个使用ssh密码使用pexpect的函数
import pexpect
import tempfile
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) #spawnu for Python 3
child.expect(['[pP]assword: '])
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。
发布于 2017-10-05 22:14:47
OpenSSH scp实用程序调用ssh程序使SSH连接到远程主机,ssh进程处理身份验证。ssh实用程序不接受命令行或其标准输入中的密码。我认为这是OpenSSH开发人员故意做出的决定,因为他们认为人们应该使用更安全的机制,比如基于密钥的身份验证。调用ssh的任何解决方案都将遵循以下方法之一:
ssh的密码。ssh版本,该版本以您希望的方式工作。在这种情况下,考虑到您已经在从python脚本调用scp,似乎其中之一是最合理的方法:
https://stackoverflow.com/questions/15166973
复制相似问题