#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
def check_tcp_port(kw, timeout=3):
try:
#socket.AF_INET 服务器之间网络通信
#socket.SOCK_STREAM 流式socket , 当使用TCP时选择此参数
cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = (str(kw["host"]), int(kw["port"]))
cs.settimeout(timeout)
#s.connect_ex(adddress)功能与connect(address)相同,但是成功返回0,失败返回error的值。
status = cs.connect_ex(address)
except Exception, e:
return {"status": False, "message": str(e), "info": "tcp check"}
else:
if status != 0:
return {"status": False, "message": "Connection %s:%s failed" % (kw["host"], kw["port"]),
"info": "tcp check"}
else:
return {"status": True, "message": "OK", "info": "tcp check"}
print check_tcp_port({"host":"localhost","port":"2311"})
网友评论