Search code examples
pythonawksubprocesspopen

using awk in python in ping sweep


I'm trying to make a ping sweep in python using subprocess but I have a problem with getting awk in Popen , I want to run this command:

ping 192.168.1.1 -c1 | grep from | awk '{print $4 "is alive"}'

output should be "assume we can receive reply form it": 192.168.1.1:is alive

here is my code "problem is in var p3"

import subprocess
# Ask the user for input for example we will enter 192.168.1.1
host = input("Enter a host to ping: ") 
p1 = subprocess.Popen(['ping', '-c 1', host], stdout=subprocess.PIPE)
p2=subprocess.Popen(["grep","from"],stdin=p1.stdout,stdout=subprocess.PIPE)
p3 = subprocess.Popen(["awk","\'{print $4 \"is alive\"}\'"], stdin=p2.stdout,stdout=subprocess.PIPE)

# Run the command
output = p3.communicate()[0]
print (output)

Solution

  • Remove the single quotation marks. They are necessary to delineate shell command line parameters, but not needed when there is no command line.

    p3 = subprocess.Popen(["awk", "{print $4 \"is alive\"}"], ...)