python批量检测防火墙ip端口连通性

需求场景:工作地点迁移,办公电脑IP变了,批量开通防火墙后需要测试,手工一个个输入telnet太慢了,cmd脚本好像也很难满足需求,所以自己写了个python脚本,发布成exe,可双击直接执行。

环境:windows 7/10

使用方式: 将要检测的ip端口事先保存在iplist.csv里,然后执行python脚本,将自动输出检测结果到iplist_out.csv。

import socket
import csv
import time
socket.setdefaulttimeout(9)

def socketTest(ip, port):
    res = ''
    port = int(port)
    timestr = time.strftime('%Y-%m-%d %H:%M:%S %p')
    print('%s - CONNECTING %s:%i' % (timestr, ip, port), end='\t')
    if port > 65536:
        print('--Error: Port should less than 65535')
        res = 'Error'
    else:
        s = socket.socket()
        result = s.connect_ex((ip, port))

        if result == 0:
            print('--OK')
            res = 'OK'
        else:
            print('--FAIL')
            res = 'FAIL'
        s.close()
    return res

if __name__ == '__main__':
    infile = 'iplist.csv'
    csvfile = csv.reader(open(infile,'r')) 
    ipInput = []
    ipOut = []
    # READ FROM INPUT CSV FILE
    for row in csvfile:
        if row[0].lower() =='ip':
            continue
        else:
            ipInput.append((row[0], row[1]))

    # TEST CONNECTION
    for ip, port in ipInput:
        res = socketTest(ip, port)
        timestr = time.strftime('%Y-%m-%d %H:%M:%S %p')
        ipOut.append([ip, port, res, timestr])

    # WRITE TO OUTPUT CSV FILE
    outfile = 'iplist_out.csv'
    out = open(outfile, 'w', newline='')
    csv_write = csv.writer(out, dialect='excel')
    csv_write.writerow(['ip','port','result', 'time'])
    for item in ipOut:
        csv_write.writerow(item)
    out.close()

    print("OUTPUT FILE: %s" % outfile)

 

你可能感兴趣的:(其他)