python tcpポート検出、tcpポート監視

1070 ワード

#!/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"})