hey all ..
i am trying to run this command on my machine by using python subprocess module ...
command :
ping -c 1 -t 1 -w 1 192.168.1.81 | grep "ttl=" | awk {'print $4'} | sed 's/.$//'
code
import subprocess
q= subprocess.run(['ping', '-c' ,'1' ,'192.168.1.81' , '| grep ttl' , ' awk {"print $4"}' , " sed 's/.$//'"], capture_output=True)
print(q.stdout.decode())
i dont get an error i just get an empty result !!
try
import subprocess
q= subprocess.check_output("ping -c 1 -t 1 -w 1 192.168.1.81 | grep 'ttl=' | awk {'print $4'} | sed 's/.$//'", shell=True)
print(q.decode())
import shlex
from subprocess import PIPE, Popen
def run_pipes(cmds):
"""
Run commands in PIPE, return the last process in chain
"""
cmds = map(shlex.split, cmds)
first_cmd, *rest_cmds = cmds
procs = [Popen(first_cmd, stdout=PIPE)]
for cmd in rest_cmds:
last_stdout = procs[-1].stdout
proc = Popen(cmd, stdin=last_stdout, stdout=PIPE)
procs.append(proc)
return procs[-1]
cmds = [
"ping -c1 5.9.16.40",
"grep ttl",
"awk '{print $4}'",
"sed 's/.$//'",
]
last_proc = run_pipes(cmds)
stdout = last_proc.stdout
for line in stdout:
line = line.decode()
print(line, end="")
The function shlex.split splits a string like the shell is doing it.
This is useful to split the command. Using shell=True is not so good because it makes vulnerabilities possible.
This part here, can be done with Python instead of rely on os dependend tools.
For example,
grep
,
awk
and
sed
are not installed on Windows.
grep 'ttl=' | awk {'print $4'} | sed 's/.$//'"
The ping command itself could still be used because it's almost everywhere available.
Some options differs from implementation to implementation. So Windows-Ping has for example some different options.