Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to run shell commands from python [duplicate]

I'm creating a python 3 tool that requires the access of many other preexisting networking tools, and some don't have python libraries. I've tried subprocess.check_output, which works, however, this data is not easy to work with, and I don't believe it supports piping commands like grep or awk if both commands require arguments. I want to be able to, on separate threads, run each command and store the output, as well as stop the output of the command, as I'll be using tools like SSLStrip, ArpSpoof, nmap, and others. that run until terminated.

What's the best way to do this?

like image 476
Tessa Painter Avatar asked May 16 '26 08:05

Tessa Painter


1 Answers

I propose to use subprocess to build proper pipes as you are used to in shell syntax. It just gets a little more "syntaxish". Here's an example of how to call ls | tr e E in Python:

from subprocess import Popen, PIPE

ls = Popen([ 'ls' ], stdout=PIPE)
tr = Popen([ 'tr', 'e', 'E' ], stdin=ls.stdout, stdout=PIPE)
out, err = tr.communicate()

After this, out will contain the output of ls with all the e translated to E.

Of course, more complex stuff can be done using this method.

like image 118
Alfe Avatar answered May 17 '26 22:05

Alfe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!