在实际工作中,我们有时需要测试本地跟目标地址是否开通网络策略,一般都是telnet Ip port 这样逐个测试,当目标主机很多的时候,这样测试效率就很低了,下面脚本可以实现批量主机测试,并且将结果打印出来
实际执行环境:redhat 7.4
1,第一步:编辑脚本内容,将ip和port放进去
cat /telnet-test
#! /usr/bin/env python
import socket
ipaddress = [
'110.63.136.130:9187',
'110.63.1.111:80',
'110.63.1.161:80',
'110.63.1.162:80',
'110.68.61.31:8080'
]
def check_ip(ip,port):
try:
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(2)
sk.connect((ip,port))
return True
except socket.error as e:
return False
finally:
sk.close()
if __name__ == '__main__':
for ipaddr in ipaddress:
port = int(ipaddr.split(":",1)[1])
ip = ipaddr.split(":",1)[0]
status = check_ip(ip,port)
if status == True:
info = 'server \033[1;32m %s \033[0m port \033[1;32m %s \033[0m is successed!' %(ip,port)
print(info)
else:
info = 'server \033[1;31m %s \033[0m port \033[1;31m %s \033[0m is fail!' %(ip,port)
print(info)
2,执行脚本:
python telnet-test