Jan-25-2021, 11:19 AM
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!