1.使用Python的nmap进行特定的端口扫描,包括各种常用的数据库端口,web端口,一些自定义的端口,使用nmap之前需要确定本机已经安装了nmap包
2.其中ret()函数是获取ip列表
3.最后print出来的是一个json的结果,方便使用zabbix进行监控
4.因为ip较多,需要进行多线程获取结果,时间比较久,建议先把结果写到本地,然后再用zabbix进行自动发现并监控
5.Python语法不够精通,欢迎批评指导
#!/usr/bin/python
#-*-coding:utf-8-*-
import json
import sys
import nmap
import multiprocessing
import commands
import urllib2
import time
reload(sys)
sys.setdefaultencoding(‘utf8‘)
def ret():
url=commands.getoutput(‘/bin/bash /cron/md5_ops_exist_InZabbix_monitor.sh‘)
#ip列表
url_data=urllib2.urlopen(url,timeout=50)
ipList = json.loads(url_data.readline())
url_data.close()
allip=ipList["data"]["all"]
# opsip = [i.strip(‘u‘) for i in allip]
return allip
def checkPythonVersionGt():
#python version great then 2.4?
pythonVersion = sys.version_info
if pythonVersion[0] == 2 and pythonVersion[1] > 5:
return True
else:
return False
if checkPythonVersionGt():
import subprocess
import json
else:
try:
import simplejson
except ImportError:
os.system(‘yum -y install python-simplejson ‘)
def resoutput(ipList):
#output result
if checkPythonVersionGt():
printt= (json.dumps(ipList,indent=4,separators=(‘,‘,‘:‘)))
else:
try:
import simplejson
printt= (simplejson.dumps(ipList,indent=4,separators=(‘,‘,‘:‘)))
except ImportError:
printt= (str(ipList))
return printt
def scan_defaults_ports(ip,default_ports):
nm=nmap.PortScanner()
sd={}
productname={}
nm.scan(ip,default_ports)
alll={}
po=[]
for host in nm.all_hosts():
if nm[host].has_key(‘tcp‘):
for port in nm[host][‘tcp‘].keys():
name = nm[host][‘tcp‘][port][‘name‘]
state = nm[host][‘tcp‘][port][‘state‘]
if state == ‘open‘:
po.append(port)
if len(po)>0:
po=‘,‘.join(str(s) for s in po)
sd[host]=po
return sd
else:
return
def default_ports():
p1="21 22 677 873 80 8080"
p2=" ".join(map(str,[k for k in range(3306,3321)]))
p3=" ".join(map(str,[k for k in range(3690,3692)]))
p4=" ".join(map(str,[k for k in range(6379,6400)]))
p5=" ".join(map(str,[k for k in range(11200,11201)]))
p6=" ".join(map(str,[k for k in range(27000,27101)]))
p7=" ".join(map(str,[k for k in range(20000,20101)]))
p8=" ".join(map(str,[k for k in range(22000,22101)]))
default_ports=reduce(lambda x,y: x+‘ ‘+y,[p1,p2,p3,p4,p5,p6,p7,p8]).replace(" ",",")
return default_ports
if __name__==‘__main__‘:
pool = multiprocessing.Pool(processes = 3)
result=[]
default_ports=default_ports()
opsip=ret()
for x in opsip:
try:
x=x.encode(‘utf-8‘)
result.append(pool.apply_async(scan_defaults_ports, (x,default_ports)))
except Exception as e:
print e
pass
pool.close()
pool.join()
ip=[]
for res in result:
ip.append(res.get())
ip=filter(None,ip)
iplist=[]
outip={}
for i in ip:
k=i.keys()
v=i.values()
k=‘,‘.join(str(s) for s in k)
v=‘,‘.join(str(s) for s in v)
iplist.append({‘{#NEWSACNPORT}‘:v,‘{#NEWSCANHOSTIP}‘:k})
outip={‘data‘:iplist}
outip= resoutput({‘data‘:iplist})
print outip
原文地址:http://blog.51cto.com/9393764/2177121
时间: 2024-11-09 06:16:37