使用 socket 库检测端口连接

#!/usr/bin/env python
#encoding:utf8
#author: linuxhub.org
#Python检测IP端口连接是否正常
 
import socket
 
def is_open(ip,port):
              s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
              try:
                            s.connect((ip,int(port)))
                            s.shutdown(2)
                            return True
              except:
                            return False
 
 
if __name__ == '__main__': 
 
            host = '192.168.0.202'
            port = '6379'
 
            if is_open(host, port):
                            print "OK"
            else:
                            print "NO"