Telnet from inside a telnet session (Python)
Question: I am trying to telnet to a remote device from another remote device, doing a
nested telnet using telnetlib. While I can easily communicate with the first
device, I am not able to get the output from the second device. Below is my
code, am I doing this correctly?

    
    
    import telnetlib
    
    HOST = "firstDevice"
    user = "lab"
    password = "lab"
    
    tn = telnetlib.Telnet(HOST)
    
    tn.read_until("Username: ")
    tn.write(user + "\n")
    if password:
        tn.read_until("Password: ")
        tn.write(password + "\n")
    
    #Nested telnet
    tn2 = telnetlib.Telnet("secondDevice") 
    tn2.read_until("#")   
    tn2.write("sh clock\n")
    
    #Close tn2
    tn2.write("exit\n")
    print tn2.read_all()
    
    #Close tn
    tn.write("exit\n")
    print tn.read_all()
    

**Edit 1**

    
    
    import telnetlib
    
    HOST = "firstDevice"
    user = "lab"
    password = "lab"
    
    tn = telnetlib.Telnet(HOST)
    
    tn.read_until("Username: ")
    tn.write(user + "\n")
    if password:
        tn.read_until("Password: ")
        tn.write(password + "\n")
    
    #Nested telnet
    tn.write("telnet secondDevice\n") 
    tn.write("sh clock\n")
    
    #Close nested session
    tn.write("exit\n")
    
    #Close tn
    tn.write("exit\n")
    print tn.read_all()
    


Answer: You are not doing a nested connection in your code. You are just connecting to
two different computers from localhost, but apparently you can not actually
connect to the second one. To do a nested Telnet to the second host, you have
to tell the first one to telnet to the second one: replace `tn2 =
telnetlib.Telnet("secondDevice")` with

    
    
    tn.write("telnet secondDevice\n")
    

Since you have a nested connection, all your localhost should see is `tn`. You
can get rid of the `tn2` object entirely. All interaction with the second
device will be done by sending strings to the first device, which is in a
session connected to the second device.

