端口检测

Zss 发表于:

时常需要查看端口情况,有时候信息过多,所以筛选一下

#coding:gbk
from subprocess import Popen,PIPE
import os,re

if __name__ == '__main__':
    while 1:
        port4_1 = []
        port4_2 = []
        port6_1 = []
        port6_2 = []
        if os.name == 'nt':
            cmd = 'netstat -nat'
            result = Popen(cmd,shell=True,stdout=PIPE)
            text = result.stdout.read().decode('gbk')
            ipv4_port = list(set(re.findall('(?:TCP\s*)(.*:\d{1,5})(?:\s*\d{1,3}\.)',text)))
            ipv6_port = list(set(re.findall('(?:TCP\s*)(\[.*\]:\d{1,5})(?:\s*?\[.*\])',text)))
            for i in ipv4_port:
                if '127.0.0.1' in i:
                    port4_1.append(int(i.split(':')[1]))
                if '0.0.0.0' in i:
                    port4_2.append(int(i.split(':')[1]))
            for i in ipv6_port:
                if '[::1]' in i:
                    port6_1.append(int(i.split(':')[3]))
                if '[::]' in i:
                    port6_2.append(int(i.split(':')[3]))
            print '-' * 30
            print '    只显示回路地址和全零地址'
            if len(port4_1)!=0 or len(port4_2)!=0:
                print '-'*30
                print 'IPV4_Port:'
                if len(port4_1)!=0:
                    port4_1 = sorted(port4_1)
                    for i in port4_1:
                        print 'IP: 127.0.0.1     PORT: %d'%i
                if len(port4_2)!=0:
                    port4_2 = sorted(port4_2)
                    for i in port4_2:
                        print 'IP: 0.0.0.0       PORT: %d'%i
            if len(port6_1) != 0 or len(port6_2) != 0:
                print '-' * 30
                print 'IPV6_Port:'
                if len(port6_1)!=0:
                    port6_1 = sorted(port6_1)
                    for i in port6_1:
                        print 'IP: [::1]         PORT: %d'%i
                if len(port6_2)!=0:
                    port6_2 = sorted(port6_2)
                    for i in port6_2:
                        print 'IP: [::]          PORT: %d'%i
                print '-' * 30
        if os.name == 'posix':
            cmd = "netstat -nat|awk '{print $4}'"
            result = Popen(cmd, shell=True, stdout=PIPE)
            text = result.stdout.read()
            result_list = text.split('\n')[2:-1]
            print '-' * 30
            print 'Port:'
            for i in result_list:
                print i
            print '-' * 30
        raw_input('回车继续查看!')