Why doesnt this regex work?

2019-07-26 23:44发布

问题:

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. Right now im only matching on "succeeded" but that's all i need because the netcat command prints out :

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

The code runs fine but it matches when it shouldn't ?

回答1:

The output is coming out stderr not stdout:

stderr=subprocess.PIPE

You can simplify to using in and you don't need 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:

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

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