Is it possible to create a sensor via Telnet?, or a script to get data via Telnet Commands?

If you can do it in Python, then you can use telnetlib. The following is what I use to login to a router and get some data. By no means saying its well written, but it does work :smiley:

I run it via cron periodically, and the results are output in JSON, which I decode in HA to create sensors. I am sure you could tailor it to achieve what you do above.

    try:
#        print("Opening Telnet connection")
        telnet = telnetlib.Telnet('192.168.xxx.xxx')
#        print("Created new Telnet instance")
        telnet.read_until(b'Username : ', 20)
#        print("Found username")
        telnet.write(('xxxxxx' + '\r\n').encode('ascii'))
#        print("Sending username")
        telnet.read_until(b'Password : ', 20)
#        print("Found password")
        telnet.write(('xxxxxx' + '\r\n').encode('ascii'))
#        print("Sending password")
        telnet.read_until(b'=>', 20)
#        print("Found prompt")
        telnet.write(('hostmgr list\r\n').encode('ascii'))
#        print("Calling hostmgr")
        devices_result = telnet.read_until(b'=>').split(b'\r\n', 60)
#        print("Command complete")
        telnet.write(('exit' + '\r\n').encode('ascii'))
#        print("Sent exit command")
        exit
    except EOFError:
        print("Unexpected response from router")
        return
    except ConnectionRefusedError:
        print("Connection refused by router. Telnet enabled?")
        return
    except:
        print("Error")
        return

Hope that helps get you started.

1 Like