python源码

#/usr/bin/env python
#coding:utf-8

'''
@author:fojo
Email:puzzle@92linux.cn
'''

import socket
import configparser
import logging
import time
import os

proDir = os.path.split(os.path.realpath(__file__))[0]
file_path = os.path.join(proDir,'conf.txt')

'''日志配置'''
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)   #总日志级别
logfile = 'info.log'
fh = logging.FileHandler(logfile,mode='w')  #日志记录方式,w为覆盖记录,a为追加记录。
formatter = logging.Formatter('[%(asctime)s] - %(levelname)s: %(message)s ')
fh.setFormatter(formatter)
logger.addHandler(fh)

if os.path.exists(file_path):
    conf = configparser.ConfigParser()
    conf.read(file_path,encoding='utf-8')
    if conf.sections() != '':
        IP   = conf.get('NORMAL','ip')
        PORT = conf.get('NORMAL','port')
        MORE = conf.get('NORMAL','more')
        SINGLE  = conf.get('NORMAL','single')
        TIMEOUT = conf.get('NORMAL', 'timeout')
    else:
        print(u'未找到标签%s,请检查配置文件' % conf.sections())
else:
    print(u'Error: "%s"读取配置文件失败,请检查!' % file_path)

def check(ip,port):
    try:
        sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if TIMEOUT == '':
            sk.settimeout(5)
        else:
            sk.settimeout(int(TIMEOUT))
        sk.connect((ip,port))
        sk.close()
        data = '%s %s port response OK!' % (ip,port)
        logger.info(data)
    except Exception as e:
        logformat = '%s %s Port not response!' % (ip, port)
        logger.warning(logformat)

def Prange(ip,port):
    if 0 < port <= 65535:
        check(ip, port)
    else:
        msg = str(port).encode('utf8')
        logger.error('"%s" 端口超出范围 [1-65535]' % msg)

def main():
    for ip in IP.split(','):
        for port in PORT.split(','):
            port = int(port)
            Prange(ip,port)
    if SINGLE.title() == 'On':
        for tmp in MORE.strip().split(','):
            ip = tmp.split(":")[0]
            port = tmp.split(":")[1]
            Prange(ip, int(port))

if __name__ == '__main__':
    print(u'端口正在检测中 ... ')
    main()
    print(u'端口检测完毕,结果请查看当前路径下“info.log”')
    time.sleep(5)

conf.txt置文件

[NORMAL]
# 需要检测的IP和端口,多个IP和端口以逗号分隔
ip = 192.168.1.68
port = 10032
# 当single 等于On时,执行more,tag和more可以同时检测
single = On
# more用于检测一个ip对应一个端口,写法:ip1:port1,ip2:port2
more = 192.168.1.1:1001 192.168.1.3:2005
# 端口检测失败超时时间,为空执行默认时间5秒
timeout = 2

温馨提示:最开始使用ini格式配置文件,换台电脑运行脚本一直报no sections,路径和文件名也没错,换成txt格式后就解决了

Last modification:September 12th, 2019 at 10:39 am
If you think my article is useful to you, please feel free to appreciate