测试连通性的工具有很多,比如telnet,nc,netcat等等。但telnet检测一些超时的连接时会变成交互式,影响批量脚本书写,而nc和netcat等工具又由于一些限制,并不是每一台服务器上都有这些工具,因此基于python的socket模块写了一个检测的脚本
import socket
list_str = '''
10.78.199.62 9101
10.78.199.62 9102
'''
OK_list = []
Timeout_list = []
DOWN_list = []
ip_list = list(list_str.split())
# socket try connect
def IsOpen(ip, port):
socket.setdefaulttimeout(2)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, port))
s.shutdown(2)
OK_list.append([ip, port])
return True
except socket.timeout:
Timeout_list.append([ip, port])
return False
except:
# print '%s %d is DOWN' % (ip, port)
DOWN_list.append([ip, port])
return False
if __name__ == '__main__':
for _ in range(0, len(ip_list), 2):
IsOpen(ip_list[_], int(ip_list[_ + 1]))
lists={'ok': OK_list, 'timeout': Timeout_list, 'donw': DOWN_list}
for status, _ in lists.items():
print status.center(40, '-')
# print '-' * 30
# print 'status: %s is :' % status
if not _:
print 'null'
continue
for ip, port in _:
print ip, port
只需脚本内容放入其中,然后复制到命令行中回车即可
cat << eof | python
# 脚本内容
eof