python【telnet】使用


def open_telnet_connection(ip_address, port=3000):
    socket.setdefaulttimeout(3)
    try:
        session = telnetlib.Telnet(ip_address, int(port))
    except (ConnectionRefusedError,
            socket.timeout):
        pass
    else:
        return session


def telnet_command(session, command, UntilContent=‘\n‘, timeout=10):
    _write(session,command)
    return read_buff(session,UntilContent, timeout)


def _write(session, command):
    if session:
        session.write(command.encode() + "\n".encode())


def read_buff(session,UntilContent, timeout=30):
    if session:
        response = session.read_until((UntilContent).encode(), timeout)
        response = response.decode()
        return response


def telnet_close(session):
    session.close()


def get_alive_topyang(alive_host_ip, port=1):
    topyang_alive_ip = []
    for host in alive_host_ip:
        try:
            session = open_telnet_connection(host, 3000)
            if session is None: raise ConnectionRefusedError
            response = telnet_command(session, "READ:%s" % port).split(":")[2].strip("\r\n")
            telnet_close(session)

        except (ConnectionRefusedError, # 端口没开
                ):
            print(host,‘: ‘,‘telnet failed !‘)
            continue
        else:
            topyang_alive_ip.append((host,response))
    return topyang_alive_ip

python【telnet】使用

上一篇:使用cmd命令来检测局域网中存在的主机


下一篇:【pta】练习4.1 根据后序和中序遍历输出先序遍历 (25 分) <已知两种遍历求另一种>