本文共 2734 字,大约阅读时间需要 9 分钟。
服务器安全问题,对于我们运维人员来说都是不可忽视的,虽然我们没有安全工程师那么牛掰,但是我们也要尽量的避免被黑,即使我们被黑了,上面跑了别的应用,我们要立刻马上收到报警信息,尽量减少损失。好了说重点,今天我写了python端口扫描的脚本,如果开启了异常的端口,管理员会立马收到邮件信息,看代码!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | #!/usr/bin/python #coding=utf8 #Author zhaodong #www.tshare365.com 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 = [ 'zhaodong@tshare365.tv' ] mail_host = "smtp.163.com" #设置服务器 mail_user = "tshare365@163.com" #用户名 mail_pass = "www.tshare365.com" #密码 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, "zhaodong" ,infor) os.system( "rm -rf /tmp/Problem_info.txt" ) |
注释: 如果代码是放在/root/目录下 ,需要在/root/ 目录下建立一个IP.txt 的文件,在里面写上你需要扫描的IP。