您的位置:首页 > 运维架构 > Shell

python 执行shell 命令,自动化添加攻击IP地址到iptables

2017-06-30 15:28 471 查看
通过python执行shell命令的方法有4种,在这里介绍一种常用的。
os.system、 os.popen、 commands、 subprocess

接下来介绍subprocess的使用
通过python 日志分析,获取到攻击源IP地址,收集写入到mysql数据库中
mysql如下:





iptables.py 脚本

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import MySQLdb
import subprocess
try:

connection =
MySQLdb.connect(user='soul',passwd='soul',host='127.0.0.1',db='iptable',port=3306,use_unicode=1,charset="utf8")
cursor = connection.cursor()
cursor.execute('select * from iptables')
data = cursor.fetchall()
cursor.close()
connection.close()

except MySQLdb.Error,err_msg:
print 'MySQLdb error msg:' ,err_msg

def insert():
for info in data:
ipaddress = info[1]
print '成功插入IP黑名单:%s' %ipaddress
subprocess.call(['/sbin/iptables -I INPUT -s %s -p tcp --dport 8000 -j ACCEPT' % ipaddress],  shell=True)

def save():
subprocess.call(['service iptables save'], shell=True)

if __name__ == '__main__':
insert()
save()


python iptables.py
result:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell python