Read txt file, add to iptables not working on new host
Chris Angelico
rosuav at gmail.com
Fri May 24 09:54:05 EDT 2013
On Fri, May 24, 2013 at 12:44 PM, JackM <notreal at earthlink.net> wrote:
> outPut = os.popen( '/sbin/iptables -A INPUT -s' + ' ' + IP + ' ' +
> '-j REJECT' )
There's so much about this script that's less than Pythonic, but the
one thing I'd really like to see is a log of the exact command being
executed. Replace the above line with this:
command = '/sbin/iptables -A INPUT -s' + ' ' + IP + ' ' + '-j REJECT'
outPut = os.popen(command)
logFile.write(command+"\n")
That will show, in your log, exactly what's being executed. You should
then be able to execute that command in the shell and see the exact
same result. That might also show you the problem - it might be
obvious from the commands logged.
If that doesn't work, here's a rewrite of your code for cleanliness,
which still does what I think your original code does. See if they act
differently...
-- cut --
#!/usr/bin/python
import os
import time
# Input, Output, and TimeStamp
inFile = open('/var/www/html/mydomain.com/banlist.txt','r')
logFile = open('/var/log/banList.log','w')
stamp = time.asctime(time.localtime())
# Daily Flush of blockList rules before re-applying Blocks
os.popen('/sbin/iptables -F INPUT')
logFile.write(stamp+'\nFlushing Rules..\n')
# Loop to read in file and Apply rules to IPtables
for line in inFile: # TODO: Use 'with' for a bit of protection
ip = line.split(';')[0]
output = os.popen( '/sbin/iptables -A INPUT -s ' + ip + ' -j REJECT' )
logFile.write(IP+' - Has been blocked\n')
-- cut --
Since the timestamp doesn't change across a run anyway, there's not
much point printing it out every time, and I'm also putting newlines
in the logfile. Beyond that, it should function the same way as the
original.
ChrisA
More information about the Python-list
mailing list