python检测远程服务器tcp端口的代码

2022-05-03 00:00:00 代码 端口 检测
"""
功能描述:python检测远程服务器tcp端口是否开放的代码
"""
import socket
import sys

NORMAL = 0
ERROR = 1
TIMEOUT = 5


def ping(ip, port, timeout=TIMEOUT):
    try:
        cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        address = (str(ip), int(port))
        status = cs.connect_ex((address))
        cs.settimeout(timeout)
        if status != NORMAL:
            print(ERROR)
        else:
            print(NORMAL)
    except Exception  as e:
        print(ERROR)
        print("error:%s" % e)
        return ERROR
    return NORMAL


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('请按照如下格式使用: ./tcp.py www.pidancode.com 80')
        sys.exit(1)
    ip = sys.argv[1]
    port = sys.argv[2]
    try:
        timeout = sys.argv[3]
    except IndexError  as e:
        timeout = TIMEOUT
    ping(ip, port, timeout)

如果端口开放输出结果为0
以上代码在python3.9环境下测试通过

相关文章