pexpect:期待各种线条

时间:2014-02-08 11:40:42

标签: python edit pexpect

我正在尝试将pexpect用于来自服务器的scp文件,但它似乎什么都不做(甚至不是错误消息)。这是我的代码:

import pexpect
child=pexpect.spawn('scp -r user@host:route/file .')
child.expect("user@host's password:")
child.sendline('password')

我认为问题出在child.expect命令中,因为“user @ host的密码:”是包含特殊字符的30行欢迎消息的最后一行。有没有办法告诉pexpect期望不止一条线或只是什么?或者只是等待X秒然后输入密码?

编辑:它与child.wait()命令一起使用,但它在第9个文件处停止。碰巧第10个非常大(大约250Mb),我不知道它是否与它有关...谢谢!!

编辑:我把行

child.logfile=sys.stdout

child=pexpect.spawn('scp -r user@host:route/file .')

我在屏幕上得到的,不是在文件中,是“user @ host的密码:”结束的欢迎信息,然后我在同一行看到了密码,但我仍然没有得到文件

任何人都知道如何修复它?

谢谢大家!

2 个答案:

答案 0 :(得分:0)

您可以查看pexpect的属性缓冲区: - pexpect.before在匹配pexpect.expect中指定的正则表达式之前解析#tring - 目前在缓冲区中的pexpect.buffer#字符串 - pexpect.after#string解析后匹配pexpect.expect

中指定的正则表达式

请记住,child.expect()是一个阻塞调用,在它与正则表达式匹配或者遇到EOF / TIMEOUT异常之前不会返回。

答案 1 :(得分:0)

根据pexpect documentation

  

赋予Expect()的模式可以是正则表达式,也可以是正则表达式列表。这使您可以匹配多个可选响应。 Expect()方法返回匹配的模式的索引。例如,假设您要登录到服务器。输入密码后,您可以从服务器获得各种响应–您的密码可能会被拒绝;或者可以允许您进入并询问您的终端类型;否则您可以直接进入并给出命令提示符。

以及文档中的示例:

child.expect('password:')
child.sendline(my_secret_password)
# We expect any of these three patterns...
i = child.expect (['Permission denied', 'Terminal type', '[#\$] '])
if i==0:
    print('Permission denied on host. Can\'t login')
    child.kill(0)
elif i==1:
    print('Login OK... need to send terminal type.')
    child.sendline('vt100')
    child.expect('[#\$] ')
elif i==2:
    print('Login OK.')
    print('Shell command prompt', child.after)
相关问题