Why doesnt this regex work?
<p>Here is the code in question:</p>

<pre><code>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")
</code></pre>

<p>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 :</p>

<pre><code>Connection to 8.8.8.8 53 port [tcp/domain] succeeded!
</code></pre>

<p>The code runs fine but it matches when it shouldn't ?  </p>

<p>The output is coming out stderr not stdout:</p>

<pre><code>stderr=subprocess.PIPE
</code></pre>

<p>You can simplify to using in and you don't need shell=True:</p>

<pre><code>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")
</code></pre>

<p>You can also redirect <em>stderr</em> to <em>STDOUT</em>  and use check_output presuming you are using python >= 2.7:</p>

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

if "succeeded" not in out:
    print ("test")
</code></pre>

python regex netcat