import sys,os,nmap
import multiprocessing
import httplib,smtplib
from email.MIMEText import MIMEText
from email.Header import Header
reload(sys)
sys.setdefaultencoding('utf8')
#设置收件人邮箱改成你自己的
mailto_list=['admin@163.com']
mail_host="smtp.163.com" #设置服务器
mail_user="user@163.com" #用户名
mail_pass="password" #密码
mail_postfix="163.com" #发件箱的后缀
def send_mail(to_list,sub,content):
me="服务器端口异常报警"+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_subtype='plain',_charset='utf_8')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server.login(mail_user,mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
def HostCheck(ipaddr):
nm = nmap.PortScanner()
call = nm.scan(ipaddr, '22-65535') # scan host 127.0.0.1, ports from 22 to 443
nm.command_line() # get command line used for the scan : nmap -oX - -p 22-443 127.0.0.1
nm.scaninfo() # get nmap scan informations {'tcp': {'services': '22-443', 'method': 'connect'}}
nm.all_hosts() # get all hosts that were scanned
for host in nm.all_hosts():
for proto in nm[host].all_protocols():
pass
lport = nm[host][proto].keys()
lport.sort()
for port in lport:
if port in White_PORT:
print line
else:
line = "HOST: %s\tTCP/UDP: %s\tPORT : %s\t 异常端口" % (host, proto, port)
f =file('/tmp/Problem_info.txt','a')
f.write("\r\n")
f.write(line)
f.close()
if __name__ == "__main__":
INPUT_IP = os.path.join(os.getcwd(),"IP.txt")
INPUT_IP_LINES = sum(1 for line in open(INPUT_IP))
OPEN_INPUT_IP = open(INPUT_IP)
if INPUT_IP_LINES > 30:
process_number = 30
else:
process_number = INPUT_IP_LINES
#设置白名单端口
White_PORT=[22,80,3306]
pool = multiprocessing.Pool(processes=process_number)
for IP in OPEN_INPUT_IP.readlines():
IP = IP.strip('\n')
pool.apply_async(HostCheck,(IP,))
pool.close()
pool.join()
#判断Problem_info文件是否存在
if os.path.exists("/tmp/Problem_info.txt"):
infor=os.popen("cat /tmp/Problem_info.txt").read()
#发送邮件报警
send_mail(mailto_list,"admin",infor)
os.system("rm -rf /tmp/Problem_info.txt")