python---socket模块---监控端口

import socket,re
#.*?叫做非贪婪匹配,尽可能的少匹配
#.*叫做贪婪匹配,尽可能的多匹配
# a = 'fenif1212nfi129f21f'
# res = re.compile('(\d+)').findall(a)
# print(res)
hosts = ['1.1.1.1:90','2.2.2.2:8080','127.0.0.1:80','3.3.3.3:50','192.168.1.1:9090']
for host in hosts:
    ip = re.compile('(.*?):(.*)').search(host).group(1)
    port = re.compile('(.*?):(.*)').search(host).group(2)
    server = socket.socket()#tcp协议
    server.settimeout(1)#设置超时时间
    res = server.connect_ex((ip,int(port)))
    # print(res)#res == 0代表端口号启用|res != 0代表端口号没启用
    if res == 0:
        print('%s---%s:ok' % (ip,port))
    else:
        print('%s---%s:不通' % (ip, port))

你可能感兴趣的:(python基础)