【问题标题】:scp to a remote server using pexpect使用 pexpect scp 到远程服务器
【发布时间】:2014-04-09 20:33:06
【问题描述】:

我正在尝试学习一点关于 pexpect 的知识:特别是我正在尝试将文件从我的笔记本电脑复制到远程服务器。 我遇到了一种奇怪的行为:如果我逐行编写,或多或少相同的代码可以工作,但如果我将它作为脚本运行则不会。 这是我一行一行写的:

child = pexpect.spawn('scp pathdir/file.ext username@hostname:pathdir')
r=child.expect ('assword:')
r

它返回 0,我用密码完成工作

child.sendline ('password')

当我对服务器执行 ssh 时,我在那里找到了我的文件。所以我把所有的步骤都收集在一个脚本中;它没有错误地退出,但它没有被复制的文件......为什么?但更重要的是,我该如何解决这个问题?

这是脚本:

child = pexpect.spawn('scp pathdir/file.ext username@hostname:pathdir')
r=child.expect ('assword:')
print r
if r==0:
    child.sendline ('password')
child.close()

我不确定 pexpect 是如何工作的,所以我打印 r 以确保它是 0。确实如此。

【问题讨论】:

  • 你是从file.ext所在的文件夹启动脚本吗?
  • 是的:脚本和file.ext在同一个目录下。但是问题需要编辑:file.ext 给出了它的完整路径。
  • 遇到了同样的问题。你现在解决了吗?
  • 没有。尚未找到任何解决方案。

标签: python scp pexpect


【解决方案1】:

我最近遇到了“同样”的问题。这就是我的做法。我希望这肯定会对你有所帮助。

您的问题: I'm not sure how pexpect works so I print r to be sure it is 0. And it is.

是的,它是零。

试试下面的代码:

    try:
        var_password  = "<YOUR PASSWORD>" Give your password here
        var_command = "scp pathdir/file.ext username@hostname:pathdir"
        #make sure in the above command that username and hostname are according to your server
        var_child = pexpect.spawn(var_command)
        i = var_child.expect(["password:", pexpect.EOF])

        if i==0: # send password                
                var_child.sendline(var_password)
                var_child.expect(pexpect.EOF)
        elif i==1: 
                print "Got the key or connection timeout"
                pass

    except Exception as e:
        print "Oops Something went wrong buddy"
        print e

child.expect 可以接受多个参数。在这种情况下,您必须以列表的形式发送这些参数。在上述情况下,如果 pexpect.spawn 的输出是“密码:”,那么 i 将得到 0 作为输出,如果遇到 EOF 而不是“密码”,那么 i 的值将是 1。

我希望这可以消除您的疑问。如果没有,请告诉我。我会尽力为你加强解释。

【讨论】:

    【解决方案2】:

    发送密码后,即

    child.sendline('password') 
    

    写:

    child.expect(pexpect.EOF)
    

    这会等到文件复制完成

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题。当我将客户端的主目录 (~/) 指定为目标时,就会发生这种情况。这在手动输入 scp 命令时效果很好,但由于某种原因在使用 pexpect 时效果不佳。只需使用相对或绝对目标目录路径就可以解决我的问题。

      【讨论】:

        【解决方案4】:

        您必须使用child.interact() 完成您的代码,然后它将运行您之前编写的所有命令。

        看起来像这样:

        child = pexpect.spawn('scp pathdir/file.ext username@hostname:pathdir')
        r=child.expect ('assword:')
        print r
        if r==0:
            child.sendline ('password')
        child.interact()
        child.close()
        

        【讨论】:

          猜你喜欢
          • 2014-11-18
          • 2014-07-10
          • 1970-01-01
          • 1970-01-01
          • 2013-10-04
          • 2015-12-02
          • 2019-11-07
          • 2019-07-21
          • 2020-02-25
          相关资源
          最近更新 更多