使用 pexpect python 模块的 SFTP

发布于 2024-12-19 18:19:36 字数 987 浏览 3 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆梦 2024-12-26 18:19:36

总结一下答案:

  • 打开调试日志记录以更好地了解出了什么问题;来自 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文