#!/usr/bin/env python
#coding:utf-8
#Author: zikang
import socket
list_str = '''
172.31.7.103 8080
172.31.7.104 6379
172.31.7.105 3306
'''
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)
标签:__,socket,批量,python,ip,list,print,port,端口号
From: https://www.cnblogs.com/zikang/p/17103918.html