There are 4 ways to execute a shell command through Python, which is described here as a common use.
Os.system, Os.popen, commands, subprocess
Next introduce the use of subprocess
Through the Python log analysis, get to the attack source IP address, collect writes to the MySQL database
MySQL is as follows:
650) this.width=650; "Src=" https://s1.51cto.com/wyfs02/M01/9A/74/wKioL1lV_KuRc5I3AAAi_QJDHS4141.png-wh_500x0-wm_ 3-wmp_4-s_2635175523.png "title=" ch}awt8xa@) 9$k6%8@6]ns7.png "alt=" wkiol1lv_kurc5i3aaai_qjdhs4141.png-wh_50 "/ >
iptables.py Script
#!/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 ' successfully inserted IP blacklist:%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
650) this.width=650; "Src=" https://s5.51cto.com/wyfs02/M02/9A/74/wKioL1lV_V6AxEtvAAA9omI0C5I755.png-wh_500x0-wm_ 3-wmp_4-s_100985829.png "title=" r2vli% ' [5@9d]edk]}~61jj.png ' alt= ' wkiol1lv_v6axetvaaa9omi0c5i755.png-wh_50 '/>
This article is from the "My_soul" blog, make sure to keep this source http://soul455879510.blog.51cto.com/6180012/1943514
Python executes shell command, automates adding attack IP address to iptables