call IPtables command within python script -
i trying call following command in python script. trying insert rule ip tables. using sub process call , inserting variables needed, getting large error. suggestions?
iptables = subprocess.call('iptables -i forward -eth 0 -m '+protocol+' -t'+protocol+'--dport '+port+'-j dnat --to-destination'+ipaddress)
error:
traceback (most recent call last): file "./port_forward.py", line 42, in <module> iptables = subprocess.call('iptables -i forward -i eth0 -m '+protocol+' -t'+protocol+'--dport '+port+'-j dnat --to-destination'+ipaddress) file "/usr/lib/python2.7/subprocess.py", line 493, in call return popen(*popenargs, **kwargs).wait() file "/usr/lib/python2.7/subprocess.py", line 679, in __init__ errread, errwrite) file "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child raise child_exception oserror: [errno 2] no such file or directory
your problem common python beginners. instead of formatting string command, trying build complex string concatenating many strings , variables. instead, use string format, allow test command , make code more readable , flexible.
your original string lacks spaces between options , arguments, e.g. --to-destination1.2.3.4
.
hence, you should format string (this works python 2.7):
opts = {'iptables': '/sbin/iptables', 'protocol': 'tcp', 'port': 80, 'ipaddress': '0.0.0.0'} ipcmd = '{iptables} -i forward -eth 0 -m {protocol} -t {protocol} \ --dport {port} -j dnat --to-destination {ipaddress}'.format(**opts) if debug: print ipcmd iptables = subprocess.call(ipcmd)
this easier modify later, , also, when more python programming, see more readable.
also, call iptables, should root, stated in comments: in beginning of script add:
import sys import os if not os.getuid() == 0: print "you must root change iptables." sys.exit(2)
update after seeing error trace:
you trying call command iptables
not in path. should call full path of iptables , e.g. /sbin/iptables
Comments
Post a Comment