python:端口扫描邮件推送

#!/usr/bin/env python
import pickle
import smtplib
from email.mime.text import MIMEText
import nmap
from multiprocessing import Pool
import time
import os

now = time.strftime("%Y%m%d")
os.system('touch /tmp/%s'%now)
def run(ip):
	f = open('/tmp/%s'%now,'a')
	nm = nmap.PortScanner()
	nm.scan(ip)
	for proto in nm[ip].all_protocols():
		ports = nm[ip][proto].keys()
		ports.sort()
		port_length = len(ports)
		i = 0
		while i < port_length:
			in_port = ports[i]
			if nm[ip][proto][in_port]['state'] == 'open':
				name = nm[ip][proto][in_port]['name']
				f.write('%s %s-%d open => %s\n' %(ip,proto,in_port,name))	
				f.flush()
			i += 1
	f.close()

def sendmail():
	mail_host = 'smtp.intellicredit.cn'
	mail_user = '[email protected]'
	mail_pass = 'yourpassword'
	sender = '[email protected]'
	receivers = ['[email protected]']
	context = os.popen('cat /tmp/%s'%now).read()
	message = MIMEText(context,'plain','utf-8')
	message['Subject'] = 'boxing-Intranet-port-scan'
	message['From'] = sender
	message['To'] = receivers[0]
	
	try:
	        smtpObj = smtplib.SMTP()
	        smtpObj.connect(mail_host,25)
	        smtpObj.login(mail_user,mail_pass)
	        smtpObj.sendmail(sender,receivers,message.as_string())
	        smtpObj.quit()
	        print('success')
	except:
	        print('failed')

if __name__ == '__main__':
	iplist = pickle.load(open('/root/host.ini','rb'))
#	iplist = ['10.0.17.20']
	for ip in iplist:run(ip)
	sendmail()

猜你喜欢

转载自www.cnblogs.com/ywxbbbbb/p/10101123.html