Created
May 24, 2016 08:04
-
-
Save BroHui/f1498810689062bd0f0cf94bc20a42f2 to your computer and use it in GitHub Desktop.
ipset python 包装
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python | |
import subprocess | |
import logging | |
fmt = "%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s" | |
datefmt = "%a %d %b %Y %H:%M:%S" | |
logging.basicConfig(format=fmt, datefmt=datefmt, level=logging.INFO) | |
def ipset_basic_struct(action, ipset_name, ip): | |
cmd = ['ipset', action] | |
if not ipset_name: | |
logging.error('no ipset name') | |
cmd.append(ipset_name) | |
if not ip: | |
logging.error('no ip address') | |
cmd.append(ip) | |
process = subprocess.Popen(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
returncode = process.poll() | |
if returncode == 0: | |
method = 'to' if action == 'add' else 'from' | |
logging.info('%s %s %s ipset %s success' % (action, ip, method, ipset_name)) | |
return 0 | |
else: | |
logging.error(process.stderr.read()) | |
return 1 | |
def ipset_add_ip(ipset_name, ip): | |
return ipset_basic_struct('add', ipset_name, ip) | |
def ipset_del_ip(ipset_name, ip): | |
return ipset_basic_struct('del', ipset_name, ip) | |
if __name__ == '__main__': | |
ipset_add_ip('gfw', '8.8.8.8') | |
ipset_del_ip('gfw', '8.8.8.8') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment