使用 pexpect python 模块的 SFTP
我正在尝试使用 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()) - 它永远不会返回。
I am trying to SFTP a file using the pexpect module.
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
It looks like I am able to connect & get authenticated thru SSH, but the retval is always 1 (exit status) and the file doesnt get sftp'ed.
Am I missing something here?
If I try to wait on p (p.wait() instead of p.close()) - it never returns.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
总结一下答案:
打开调试日志记录以更好地了解出了什么问题;来自 David K. Hess
使用 pexpect 但自动化 scp 而不是 sftp;更好的是使用 ssh 密钥;来自 jornam
使用 paramiko ssh lib 中的 sftp 函数;来自ephemient
To summarize as an answer:
turn on debug logging to get a better idea of what is going wrong; from David K. Hess
Use pexpect but automate scp instead of sftp; even better use ssh keys; from jornam
use sftp function from paramiko ssh lib; from ephemient