2016-10-07 65 views
1

这里是有问题的代码:为什么这个正则表达式不起作用?

import subprocess 
import re 
import os 
p = subprocess.Popen(["nc -zv 8.8.8.8 53"], stdout=subprocess.PIPE, shell = True) 
out, err = p.communicate() 

regex = re.search("succeeded", out) 
if not regex: 
    print ("test") 

我希望它做的是打印出来的测试,如果正则表达式不匹配的netcat命令。现在我只是匹配“成功”,但是这就是我需要的,因为netcat的命令打印出:

Connection to 8.8.8.8 53 port [tcp/domain] succeeded! 

的代码运行正常,但它时,它不应该相匹配?

回答

3

输出走出标准错误不是标准输出:

stderr=subprocess.PIPE 

可以简化为用,你不需要壳=真:

p = subprocess.Popen(["nc", "-zv", "8.8.8.8", "53"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
out, err = p.communicate() 

if "succeeded" not in err: 
    print ("test") 

您也可以重定向标准错误STDOUT并假设您使用python> = 2.7使用check_output:

out = subprocess.check_output(["nc", "-zv", "8.8.8.8", "53"],stderr=subprocess.STDOUT) 

if "succeeded" not in out: 
    print ("test") 
+0

工作很好,谢谢Padraic! – nillenilsson

相关问题