码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-06-30 17:08:41      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:python shell

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


技术分享






本文出自 “my_soul” 博客,请务必保留此出处http://soul455879510.blog.51cto.com/6180012/1943514

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

标签:python shell

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!