You can use os.system()
, like this:
import os
os.system('ls')
Or in your case:
os.system('echo 1 > /proc/sys/net/ipv4/ip_forward')
os.system('iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080')
Better yet, you can use subprocess's call, it is safer, more powerful and likely faster:
from subprocess import call
call('echo "I like potatos"', shell=True)
Or, without invoking shell:
call(['echo', 'I like potatos'])
If you want to capture the output, one way of doing it is like this:
import subprocess
cmd = ['echo', 'I like potatos']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
o, e = proc.communicate()
print('Output: ' + o.decode('ascii'))
print('Error: ' + e.decode('ascii'))
print('code: ' + str(proc.returncode))
I highly recommend setting a timeout
in communicate
, and also to capture the exceptions you can get when calling it. This is a very error-prone code, so you should expect errors to happen and handle them accordingly.
https://docs.python.org/3/library/subprocess.html
bash
was a bloated shell...os.system
recommend using thesubprocess
module.