python - 使用 pexpect python 模块的 SFTP

标签 python ssh sftp file-transfer pexpect

我正在尝试使用 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/

相关文章:

linux - 通过无密码的 ssh 连接(rpm 安装)

cocoa - 使用 NSTask ssh 到另一台计算机

linux - shell sftp 下载远程文件

python - 'dropwhile' 是静态的吗?我可以让它动态吗?

python - 迭代 `OrderedDict` 并删除它的一些键?

batch-file - 一种在 cmd.txt 文件中使用 PuTTY 批处理对 Cisco 键入多个命令的方法

go - SFTP 进入错误 : User does not have appropriate read permission

python - 按对象将 pandas 组转换为多索引 Dataframe

python - 为 API 调用创建基本响应

mysql - 在 Wordpress MySQL 数据库中使用凭据进行 SFTP 身份验证?