-1

Running the following script that I got off of stackoverflow to login into a Cisco switch connected to a console server, and issue a "sh run" command.

#!usr/bin/python
import getpass
import telnetlib

HOST = "10.252.128.81:3132"

user = input("Enter your username: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")

if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("show run\n")
tn.write("exit\n")

print(tn.read_all()) 

New to Python so when I run the script, I get the following output.

Enter your username: user1
Warning: Password input may be echoed.
Password: cisco123
Traceback (most recent call last):
  File "D:\Users\ted\workspace\Test\cisco.py", line 10, in <module>
    tn = telnetlib.Telnet(HOST)
  File "C:\Python34\lib\telnetlib.py", line 221, in __init__
    self.open(host, port, timeout)
  File "C:\Python34\lib\telnetlib.py", line 237, in open
    self.sock = socket.create_connection((host, port), timeout)
  File "C:\Python34\lib\socket.py", line 494, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Python34\lib\socket.py", line 533, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11004] getaddrinfo failed

Any thoughts?

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
  • Check what kind of format telnetlib needs for address. Usually port is a separate argument. – Mikko Ohtamaa Oct 23 '15 at 18:45
  • What switch you have? I tried on a Cisco 2600 with `HOST="10.1.1.1"` and it works. You might have to remove the port as suggested above. – flamenco Oct 23 '15 at 18:55
  • Per the above comments, https://docs.python.org/2/library/telnetlib.html states that the host and port are definitely separate. `HOST = "10.252.128.81"`, then call like `tn = telnetlib.Telnet(HOST, '3132')` and see if that helps. – stevieb Oct 23 '15 at 19:15

1 Answers1

0

Not strictly answering your question, but it may help depending on your goals. I am using PrettyGoodTerminal to script Cisco routers as it manages the connections for me and the Python part is more about sending commands and processing the result. For a simple "sh run" you don't need Pytonh either, but would look like this:

result = Terminal.ExecCommand("sh run","#")
commandResult = result[0]
timedOut = result[1]
if not timedOut:
  ActionResult = commanResult
  ScriptSuccess = True