Reputation: 3
The substring 'Failed to connect to host' is not being found in the 'text' variable. I am fairly new to python and I would appreciate any help.
import subprocess
import re
host = 'XXXXXXX'
output = subprocess.Popen(['/usr/bin/ssh', '-q', host, 'ifconfig|', 'grep', 'Mask'], stdout=subprocess.PIPE)
text = output.communicate()[0].decode('utf-8')
pattern = 'Failed to connect to host'
if re.search(pattern, text, re.IGNORECASE):
print('found')
else:
print('not found')
The expected result should be "found" since the text str contains the pattern but for some reason, the result is "not found".
Actual Output:
Failed to connect to host XXXXXXX port 22: No route to host
not found
Upvotes: 0
Views: 104
Reputation: 176
It's because the error message is printed to stderr, but you're only matching against the text printed on stdout. If you try print(repr(text))
you'll see it prints ''
.
Try adding stderr=subprocess.STDOUT
to your Popen
call, like this:
output = subprocess.Popen([...], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# ^-- this
What it does is it redirects stderr to stdout. See the docs here: https://docs.python.org/3.7/library/subprocess.html#subprocess.STDOUT
Upvotes: 1