scp到使用pexpect的远程服务器

问题描述 投票:4回答:3

我正在尝试学习一些关于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.它确实是。

python scp pexpect
3个回答
3
投票

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

你的问题: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的输出是“password:”,那么i将得到0作为输出,如果遇到EOF而不是“password”,那么i的值将为1。

我希望这会清除你的怀疑。如果没有,请告诉我。我会尽力为你加强解释。


1
投票

发送密码后即

child.sendline('password') 

写:

child.expect(pexpect.EOF)

这等待文件复制完成


0
投票

我遇到了同样的问题。当我指定客户端的主目录(〜/)作为目标时,就发生了这种情况。这在手动输入scp命令时工作正常,但出于某种原因,在使用pexpect时却没有。简单地使用相对或绝对目标目录路径解决了我的问题。


0
投票

你必须用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()
© www.soinside.com 2019 - 2024. All rights reserved.