python使用masscan扫描端口
简介:使用masscan扫描互联网端口,最终将变更和高危端口输出到mysql。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import pymysql
from pymysql import connect
import os
import xmltodict
import datetime
class SCAN():
def __init__(self):
self.conn = connect(host='localhost',port=3306,user='root',password='password=',database='risk_detection')
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
def __del__(self):
self.cursor.close()
self.conn.close()
###masscan扫描端口
def masscan(self):
global starttime, endtime
starttime = datetime.datetime.now()
print("扫描开始时间:%s" % (starttime))
os.system("/data/masscan/bin/masscan -iL /data/scan/ip_list3 --rate 1000 -p1-65535 -oX /data/scan/testscan.xml")
endtime = datetime.datetime.now()
print("扫描结束时间:%s" % (endtime))
##
def NMAP(self):
####打开masscan的扫描结果文件
with open('/data/scan/testscan.xml') as f:
xml_obj = xmltodict.parse(f.read())
host = xml_obj['nmaprun']['host']
for line in host:
ip = line['address']['@addr']
port = line['ports']['port']['@portid']
if ip in scan_dict.keys():
scan_dict[ip] = scan_dict[ip] + ',' + port
else:
scan_dict[ip] = port
def num_ip(self):
f = open("/data/scan/ip_list3")
n = 0
for line in f:
n += 1
return n
###上次task_record——id查询
def search_sql_record(self):
sql = "SELECT id FROM task_record ORDER BY id DESC LIMIT 1;"
try:
self.cursor.execute(sql)
self.conn.commit()
except:
self.conn.rollback()
dict_data = self.cursor.fetchall()
return dict_data[0]['id']
###查询任务id
def record(self):
print(self.search_sql_record())
try:
sql = "INSERT INTO task_record(start_date, end_date, num_ip,last_time_id) VALUES ('%s', '%s', '%s','%s')" % (
starttime, endtime, self.num_ip(), self.search_sql_record())
self.cursor.execute(sql)
self.conn.commit()
self.cursor.fetchall()
except:
sql = "INSERT INTO task_record(start_date, end_date,num_ip) VALUES ('%s', '%s', '%s')" % (
starttime, endtime, self.num_ip())
self.cursor.execute(sql)
self.conn.commit()
self.cursor.fetchall()
###查询任务上一次id
def search_sql_record_id(self):
sql = "SELECT id,last_time_id FROM task_record ORDER BY id DESC LIMIT 1"
try:
self.cursor.execute(sql)
except:
self.conn.rollback()
try:
return self.cursor.fetchall()
except:
return 0
###存储扫描结果
def result(self):
####打开masscan的扫描结果文件
high_port = ['20', '21', '22', '23', '69', '111', '2049', '137', '139', '445', '161', '389', '512', '513', '514',
'873', '1352', '1433', '1521', '1500', '2082', '2083',
'2181', '2601', '2604', '3128', '3306', '3389', '3690', '4848', '5000', '5432', '5632', '5900', '5901',
'5902', '5984', '6379', '7001', '7002', '7778',
'8000', '8443', '8069', '9080', '9081', '9090', '9200', '9300', '11211', '27017', '27018', '50030',
'50070']
with open('/data/scan/scan.xml',encoding='utf-8') as f:
xml_obj = xmltodict.parse(f.read())
host = xml_obj['nmaprun']['host']
for line in host:
ip = line['address']['@addr']
port = line['ports']['port']['@portid']
protocol = line['ports']['port']['@protocol']
print(self.search_sql_record_id()[0]['last_time_id'])
if port in high_port:
# print("高危端口:%s"%(port))
sql = "INSERT INTO task_result(id_task,ip,port,protocol,high_risk_port) VALUES ('%s', '%s', '%s','%s','1')" % (
self.search_sql_record_id()[0]['id'], ip, port, protocol)
try:
self.cursor.execute(sql)
self.conn.commit()
except:
self.conn.rollback
else:
sql = "INSERT INTO task_result(id_task,ip,port,protocol) VALUES ('%s', '%s', '%s','%s')" % (
self.search_sql_record_id()[0]['id'], ip, port, protocol)
try:
self.cursor.execute(sql)
self.conn.commit()
except:
self.conn.rollback
###获取变更信息
def port_change(self):
sql = "INSERT INTO port_change(id_task, ip, `port`, protocol, `status`) SELECT %s AS id_task, ip, \
`port`, protocol, (CASE WHEN id_task=%s THEN '1' ELSE '0' END)AS 'status' FROM( \
SELECT `id_task`, `ip`, `port`, `protocol` FROM task_result WHERE id_task=%s \
UNION ALL \
SELECT `id_task`, `ip`, `port`, `protocol` FROM task_result WHERE id_task=%s) t3 \
GROUP BY ip, `port`, protocol \
HAVING COUNT(*)=1" % (
self.search_sql_record_id()[0]['id'], self.search_sql_record_id()[0]['id'], self.search_sql_record_id()[0]['id'],
self.search_sql_record_id()[0]['last_time_id'])
sql_1 = "SET sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';"
self.cursor.execute(sql_1)
self.cursor.execute(sql)
self.conn.commit()
if __name__ == '__main__':
mes = SCAN()
mes.masscan()
mes.record()
mes.result()
print("扫描结果写入成功!")
try:
mes.port_change()
print("本次变更数据已更新!")
except:
print("本次无对比数据")