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

通过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:

原文:http://soul455879510.blog.51cto.com/6180012/1943514

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值