1. 程式人生 > 其它 >python連線telnet服務

python連線telnet服務

import telnetlib


def main(host, port, username: str, password: str):
    try:
        tn = telnetlib.Telnet(host=host, port=port, timeout=15)
        res = tn.read_some()
        if b'Kernel' in res:
            tn.read_until(b"login:", timeout=15)
            """
            b'\r\nKernel 3.10.0-1160.42.2.el7.x86_64 on an x86_64\r\nnode01 login:'
            """
            tn.write(username.encode() + b'\r\n')
            tn.read_until(b"Password", timeout=15)
            tn.write(password.encode() + b'\r\n')
            login_res = tn.read_until(b"Last login", timeout=15)
            if b'Last login' in login_res:
                return True
            return False

        elif b'Microsoft' in res:
            tn.read_until(b"login:", timeout=15)
            tn.write(username.encode() + b'\r\n')
            tn.read_until(b"password:", timeout=15)
            tn.write(password.encode() + b'\r\n')

            login_res = tn.read_until(b"*====")
            if b"*====" in login_res:
                return True
            return False

        else:
            print("Unknown system.")
            return False

    except Exception as e:
        print(e)


if __name__ == '__main__':
    ip = "10.4.7.11"
    po = 23
    user_info = "huan"
    word_info = '1'
    main(ip, po, user_info, word_info)