Script function to check if IP is whitelisted
I have a Python script which blocks some IPs if they perform some actions. This script contains a function to check if the IP is already bloc开发者_Python百科ked. In addition to this, I'd like the function to also check if the IP is stored in a database table and if it is, do not block it ( whitelist )
The function looks like this :
def check_ip(ip_address):
cmd = "/sbin/iptables -L INPUT -n|grep " + ip_address
signal,output = commands.getstatusoutput(cmd)
if signal is 0:
return True
else:
return False
I'm not that versed in Python so I'm not sure on how to go with this but I imagine it's pretty simple. I'm thankful for any suggestions you might have. Thank you !
Later Edit : I want to use a MySQL database as I'll be writing a PHP interface to manually add IPs. How would I search for that ? The table only has 2 fields : id and whitelist_ip, the latter storing the IP which needs to be whitelisted.
If you're planning on editing this whitelist manually, you could just use a file with your list of IP addresses. (one per line) You could then use code something like this to check it:
def check_ip(ip_address):
cmd = "/sbin/iptables -L INPUT -n|grep " + ip_address
signal,output = commands.getstatusoutput(cmd)
if signal is 0:
return True
whitelist = open('<filename>')
for ip in whitelist.readlines():
if ip_address == ip:
return True
return False
This will first check using the check you've made, and if that fails, it will check the ip whitelist. Because the function returns from the if-clause, the else clause is not needed.
If you want to use an sql database to store the whitelist data, I'd recommend using mysql or sqlite. Both of these have python wrappers available.
精彩评论