最后迭代产生“无”输出

时间:2019-03-13 12:45:49

标签: python pexpect

我正在编写一个脚本,以使用Pexpect和regex测试输出开关和公共IP之间的延迟。

以下是示例:

# Connect to a cisco system just before and going enable
for key in nodes:
    ipaddr_node = nodes[key]["IP Address"]
    print ('[|] Ping de %s en cours ...' % ipaddr_node)
    p.sendline("ping %s repeat 20" % ipaddr_node) #ping of the ip 20 times on cisco
    p.expect('#')
    ping = p.before #get the output before '#'
    print ('[+] Ping de %s reussi' % ipaddr_node)
    place = ping.find('min') #get the position of 'min' in output
    regex = ping.replace(ping[:place],"")
    output = re.search(r'\s=\s(?P<min>\d{1,4}.\d{0,3})\/(?P<avg>\d{1,4}.\d{0,3})\/(?P<max>\d{1,4}.\d{0,3})', regex) #regex to get min, avg and max
    print(output) #Print regex object
    avg = output.group('avg') #get value of group "avg" in regex
    print('[+] Average time : ' + avg) #print it

以下是输出示例:

('min/avg/max = 33/44/51 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(<_sre.SRE_Match object at 0x7f2d68ea11f8>, '<= Regex object')
[+] Temps moyen : 44
('min/avg/max = 41/46/59 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(<_sre.SRE_Match object at 0x7f2d68ea1290>, '<= Regex object')
[+] Temps moyen : 46
('min/avg/max = 41/41/42 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(<_sre.SRE_Match object at 0x7f2d68ea11f8>, '<= Regex object')
[+] Temps moyen : 41
('min/avg/max = 1/3/9 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(None, '<= Regex object')
Traceback (most recent call last):
  File "EssaiPexpect.py", line 95, in <module>
    avg = output.group('avg')
AttributeError: 'NoneType' object has no attribute 'group'

包含要测试的IP的字典包含4个IP。

我的node是包含IP和其他信息的字典,但这可以肯定地工作。

我的regex变量每次也是如此(即使在上一次迭代中):min/avg/max = 1/3/9 ms

我确信这是一件简单的事情,但我无法理解。

1 个答案:

答案 0 :(得分:0)

找到解决方案!

这是我的正则表达式搜索中的一个简单错误。 这是旧的:Output of Regex101 of old regex

这是新的:Ouput of Regex 101 of new regex

为简化起见,我的第一个请求找不到最后一行,因为我的absolute没有正确转义。 我只是在这两种可能性之间添加了一个很好的转义符以及一个.

谢谢您的帮助。

相关问题