执行效果如下:
VIP通道:一起学Python-通过python脚本进行批量telnet连通性测试
文档内容如下:
代码如下:
使用方法:
python3 ${文件名} -t ${超时时间设定} -f ${测试素材文件} -n ${测试次数}
源代码如下:
import argparse
import os
import logging
import telnetlib
run_log = 'run.txt'
if os.path.exists(run_log):
os.remove(run_log)
logger = logging.getLogger()
logger.setLevel('DEBUG')
BASIC_FORMAT = "%(asctime)s :%(levelname)s :%(message)s"
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
chlr = logging.StreamHandler() # 输出到控制台的handler
chlr.setFormatter(formatter)
chlr.setLevel('DEBUG') # 也可以不设置,不设置就默认用logger的level
fhlr = logging.FileHandler(run_log) # 输出到文件的handler
fhlr.setFormatter(formatter)
logger.addHandler(chlr)
logger.addHandler(fhlr)
##telnet访问函数
def to_up(Host, port, timeout, frequency):
info = ("第[%s]次访问地址[%s:%s]" %(frequency, Host, port))
try:
tn = telnetlib.Telnet(Host, port=port, timeout=timeout)
tn.close()
de = info + "成功\n"
logger.debug(de)
except:
err = info + "失败\n"
logger.error(err)
#测试功能类
class Test:
def __init__(self, frequency, port, timeout, host):
self.frequency = frequency
self.host = host
self.port = int(port)
self.timeout = int(timeout)
def telnet(self):
end = self.frequency + 1
for s in range(1, end):
to_up(Host=self.host, port=self.port, timeout=self.timeout, frequency=s)
#获取文本内容
def get_info(url_file, frequency=1, timeout=None):
if os.path.exists(url_file):
# 打开文件
file = open(url_file, "r", encoding='utf-8')
# 遍历文件行内容
for (num, line) in enumerate(file, 1):
line = str.replace(line,'\n','')
logger.info("正在检测第[%s]行内容:[%s]" % (num, line))
xi2 = [line]
for i in xi2:
domain_port = i.split(' ')
domain = domain_port[0]
port = domain_port[1]
logger.info("第[%s]行获取的域名:[%s]" % (num, domain))
logger.info("第[%s]行获取的端口:[%s]\n" % (num, port))
Program = Test(frequency=frequency, port=port, timeout=timeout, host=domain)
Program.telnet()
file.close()
else:
exit("找不到文件[%s]" %url_file)
def main():
#all_info :接收所有传入的信息
all_info = argparse.ArgumentParser(description="设置测试参数")
data = {'-f': '--file', '-n': '--frequency', '-t': '--time'}
for i in data:
parameter = i
parameters = data.get(i)
all_info.add_argument(parameter, parameters, required=True)
all = all_info.parse_args()
##下面开始拆分信息,all.xxx中,xxx为上面定义的--后面的字符串
f = all.file
s = all.frequency
t = all.time
logger.info("\n文件选择:[%s]\n访问次数:[%s]次\n超时时间:[%s]秒\n" %(f, s, t))
get_info(url_file=f, frequency=int(s), timeout=int(t))
if __name__ == '__main__':
main()