我正在尝试使用 pexpect 模块通过 SFTP 传输文件。
sftp_opts = ['-o', 'Port=%s' % port,
'-o', 'UserKnownHostsFile=%s' % known_hosts_file,
'-o', 'PasswordAuthentication=yes',
'%s@%s' % (user, host)]
p = pexpect.spawn('sftp', sftp_opts)
try:
p.expect('(?i)password:')
x = p.sendline(password)
x = p.expect('sftp>')
x = p.sendline('cd ' + remote_dir)
x = p.expect('sftp>')
x = p.sendline('put ' + filename)
x = p.expect('sftp>')
x = p.isalive()
x = p.close()
retval = p.exitstatus
except pexpect.EOF:
print('SFTP file transfer failed due to premature end of file.')
return False
except pexpect.TIMEOUT:
print('SFTP file transfer failed due to timeout.')
return False
看起来我能够通过 SSH 连接并获得身份验证,但 retval 始终为 1(退出状态)并且文件未通过 sftp 进行传输。
我在这里遗漏了什么吗?
如果我尝试等待 p (p.wait() 而不是 p.close()) - 它永远不会返回。
最佳答案
总结为答案:
打开调试日志记录以更好地了解出了什么问题;来自大卫·K·赫斯
使用 pexpect 但自动化 scp 而不是 sftp;最好使用 ssh key ;来自约南
使用 paramiko ssh lib 中的 sftp 功能;来自 ephemient
关于python - 使用 pexpect python 模块的 SFTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8389721/