python tcp端口檢測(cè),tcp端口監(jiān)控

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
def check_tcp_port(kw, timeout=3):
    try:
       #socket.AF_INET 服務(wù)器之間網(wǎng)絡(luò)通信
       #socket.SOCK_STREAM  流式socket , 當(dāng)使用TCP時(shí)選擇此參數(shù)
        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"})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容