2014-03-06 80 views
3

我想学习一点关于pexpect:特别是我试图从我的笔记本电脑复制文件到远程服务器。 我遇到一个奇怪的行为:或多或少相同的代码工作,如果我一行一行写,但它不会如果我作为脚本运行它。 这是我写的行由行:scp到远程服务器使用pexpect

child = pexpect.spawn('scp pathdir/file.ext [email protected]:pathdir') 
r=child.expect ('assword:') 
r 

返回0,我完成这项工作与密码

child.sendline ('password') 

当我做ssh来,我发现我的文件中有服务器。所以我收集了一个脚本中的所有步骤;它退出没有错误,但它没有被复制的文件...为什么?但更重要的是,我该如何解决这个问题?

下面是脚本:

child = pexpect.spawn('scp pathdir/file.ext [email protected]:pathdir') 
r=child.expect ('assword:') 
print r 
if r==0: 
    child.sendline ('password') 
child.close() 

我不知道Pexpect的是如何工作的,所以我印记R,以确保它是0。它是。

+0

你是否从'file.ext'所在的文件夹开始脚本? – njzk2

+0

是:脚本和file.ext位于同一目录中。然而,这个问题需要编辑:file.ext以其完整路径给出。 – user2988577

+0

遇到同样的问题。你现在解决了吗? – laike9m

回答

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 [email protected]: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

我希望这将清除你的疑问。如果没有,然后让我知道。我会尽力为你解释。

0

child.sendline('password') 

写入发送密码后:

child.expect(pexpect.EOF) 

此等待,直到文件复制完成后

0

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

相关问题