python tcp端口检测,tcp端口监控

#!/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"})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容