简体   繁体   English

Pexpect正则表达式不起作用

[英]pexpect regex not working

I am having a script which uses pexpect to telnet to a switch and copy its running config to a tftp server. 我有一个脚本,该脚本使用pexpect远程登录到交换机并将其运行配置复制到tftp服务器。 If I give the hostname, then the script works fine but while using regex in pexect, timeout occurs. 如果提供主机名,则脚本可以正常工作,但是在pexect中使用正则表达式时,会发生超时。 The code is as follows: 代码如下:

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)

I am giving the above regex as the hostname for my current switch is Force10-60. 我给上面的正则表达式作为我当前的交换机的主机名是Force10-60。 Thanks. 谢谢。

child.expect(r'.+\-.+#')

You can try this by providing raw string . 您可以通过提供raw string来尝试此操作。

Or use 或使用

child.expect('#')

To match any hostname 匹配任何主机名

I know this question already has accepted answer but I would like to add an explanation on how to handle matched regular expression. 我知道这个问题已经接受了答案,但是我想对如何处理匹配的正则表达式添加一个解释。

So, my problem was that I needed to get a string that appeared between two specific strings. 因此,我的问题是我需要获取出现在两个特定字符串之间的字符串。 This is how I solved my problem: 这是我解决问题的方式:

import pexpect

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

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

Hope this would help someone! 希望这会对某人有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM