Python 端口扫描邮件推送

Posted by ZhangShun Blog on December 11, 2018
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
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
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 = 'security@intellicredit.cn'
    mail_pass = 'yourpassword'
    sender = 'security@intellicredit.cn'
    receivers = ['zhangshun@intellicredit.cn']
    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()