Why doesnt this regex work?

独自空忆成欢 提交于 2019-12-11 04:13:12

问题


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")


来源:https://stackoverflow.com/questions/39917569/why-doesnt-this-regex-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!