pexpect正则表达式无法正常工作

问题描述 投票:0回答:2

我有一个脚本使用pexpect telnet到交换机并将其运行配置复制到tftp服务器。如果我给出主机名,那么脚本工作正常,但在pexect中使用正则表达式时,会发生超时。代码如下:

child = pexpect.spawn('telnet ' +ip)
child.expect ('Login: ')
child.sendline (username)
child.expect ('Password: ')
child.sendline (password)
child.sendline ('enable')
child.expect('Password: ')
child.sendline(password)
child.expect('.*\-.*#')
child.sendline ('copy running-config tftp://10.0.37.111/'+filename+'.txt')
time.sleep(5)

我给出了上面的正则表达式,因为我当前开关的主机名是Force10-60。谢谢。

python regex pexpect
2个回答
1
投票
child.expect(r'.+\-.+#')

您可以通过提供raw string来尝试这一点。

或者使用

child.expect('#')

匹配任何主机名


0
投票

我知道这个问题已经接受了答案,但我想补充说明如何处理匹配的正则表达式。

所以,我的问题是我需要得到一个出现在两个特定字符串之间的字符串。这就是我解决问题的方法:

import pexpect

child = pexpect.spawn(...)
child.sendline(...)
child.expect(r'firstString(.*?)secondString')

regex_obj = child.match
print(regex_obj.group(1).decode('utf-8'))

希望这会对某人有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.