Search code examples
pythonpowershellscriptingtelnet

Script Telnet session with iterative command


I'm most familiar with powershell and python so a solution which utilized either of them would be ideal.

So I have a situation where an old device with a serial to ethernet adapter rebooted and fell off our network. I connected with a crossover cable and used wireshark to find it's IP and ended up seeing an arp req (206.250.11.x - not what it was set to before, obviously) A portscan gave me a few options and one pulled up the telnet prompt I was looking for.

I was able to connect and tried our default passwords - after connecting it prompts for a 4 digit pin - but none worked.

I want to write a python script which starts the session, waits a second, inputs the first pin: 0000 sees if it says "Connection to host lost." and, if not, report back which pin it used.

I have a pinging program I wrote awhile back which used subprocess.Popen and think I could adapt it to launch the telnet session with:

telneter = subprocess.Popen(["telnet", hostname, "9999"], stdout=subprocess.PIPE).stdout.read() I also saw there is some sort of python telnet module that can be imported.

If I have a file called 'pins.txt' which is a file that has 0000-9999 with one entry per line, how can I best do the following:

1) Launch Telnet to the address/port 2) Wait until it prompts for the pin (usually less than a second) 3) Input the first line of the pins.txt file 4) Check if the session ended and it printed "Connection to host lost" 5) Report which pin does not fail and the session stays alive?

Thank you so much for any help! I'll be working on it more but it is something we'd like to get up and running again sooner rather than later so I haven't done enough research yet.

Edit: I was trying to connect with a 25pin serial converter on the other side but struck out with the adapter so that is no longer an option.

Edit2: I have also tried using a telnetlib with telnetlib.Telnet(host) but I am unable to get a stream of the data back nor restart the sessions to iterate through the pin list.


Solution

  • It's fairly common to use pexpect for such things when one wants to use Python for something that should be interactive. pexpect is based on the concept of expect.

    It is very similar to popen like you're used to except it irons out a lot of the rough edges and comes with utilities to make life a bit easier.

    The general format is

    x = pexpect.spawn("telnet")
    x.expect("Connected")
    x.sendline("thing")
    x.expect("Connection ended")
    

    This example is somewhat similar to what you want except that it will run forever. I assume you can easily modify it to do what you want based on your experience.