[英]Why doesnt this regex work?
Here is the code in question: 这是有问题的代码:
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")
What i want it to do is to print out test if the regex does not match the netcat command. 我想要它做的是打印出测试,如果正则表达式与netcat命令不匹配。 Right now im only matching on "succeeded" but that's all i need because the netcat command prints out :
现在我只匹配“成功”但这就是我需要的全部因为netcat命令打印出来:
Connection to 8.8.8.8 53 port [tcp/domain] succeeded!
The code runs fine but it matches when it shouldn't ? 代码运行正常,但它不应该匹配?
The output is coming out stderr not stdout: 输出是stderr而不是标准输出:
stderr=subprocess.PIPE
You can simplify to using in and you don't need shell=True: 你可以简化使用in,你不需要shell = True:
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")
You can also redirect stderr to STDOUT and use check_output presuming you are using python >= 2.7: 您还可以将stderr重定向到STDOUT并使用check_output,假设您使用的是python> = 2.7:
out = subprocess.check_output(["nc", "-zv", "8.8.8.8", "53"],stderr=subprocess.STDOUT)
if "succeeded" not in out:
print ("test")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.