use*_*577 5 python scp pexpect
我正在尝试了解一些有关 pexpect 的知识:特别是我正在尝试将文件从我的笔记本电脑复制到远程服务器。我遇到了一种奇怪的行为:如果我逐行编写,或多或少相同的代码可以工作,但如果我将其作为脚本运行,则不会。这是我逐行写的:
child = pexpect.spawn('scp pathdir/file.ext username@hostname:pathdir')
r=child.expect ('assword:')
r
Run Code Online (Sandbox Code Playgroud)
它返回 0,我用密码完成工作
child.sendline ('password')
Run Code Online (Sandbox Code Playgroud)
当我通过 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()
Run Code Online (Sandbox Code Playgroud)
我不确定 pexpect 是如何工作的,所以我打印 r 以确保它是 0。确实如此。
我最近遇到了“同样”的问题。我是这样做的。我希望这一定会对您有所帮助。
你的问题 :
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
Run Code Online (Sandbox Code Playgroud)
child.expect 可以接受多个参数。在这种情况下,您必须以列表的形式发送这些参数。在上面的场景中,如果 pexpect.spawn 的输出是“password:”,那么i将得到 0 作为输出,如果EOF遇到而不是“password”,那么 的值i将为 1。
我希望这能消除您的疑虑。如果没有,请告诉我。我会尽力为您加强解释。
| 归档时间: |
|
| 查看次数: |
16093 次 |
| 最近记录: |