Search code examples
pythontelnetethernet

Make telnet communication using python


It is my first question here :D

I have to send some commands from my personal computer (Linux-Red Hat) to a server (Robot Controller). I saw that the controller have a Ethernet protocol that allows sending commands using telnet communication.

My question: is it possible to make telnet connection, send commands and read the output using python? If it is, can you help me?

Thank you.


Solution

  • In python they have telnetlib, which allows telnet communication. I'm pretty sure that this is what you're looking for. You can find the docs at https://docs.python.org/2/library/telnetlib.html Here is a basic way to logon to a windows server and get the directory listing (Courtesy of the docs pages above)

    import telnetlib
    
    HOST = "localhost"
    user = "username"
    password = "password"
    
    tn = telnetlib.Telnet(HOST)
    
    tn.read_until("login: ")
    tn.write(user + "\n")
    if password:
        tn.read_until("Password: ")
        tn.write(password + "\n")
    
    tn.write("dir\n")
    tn.write("exit\n")
    
    print tn.read_all()