2015-08-27 83 views
0

訪問Cisco交換機我安裝python 2.7.10和試試這個代碼:Python中,通過telnet

import getpass 
import sys 
import telnetlib 

HOST = '172.17.0.42' 
user = raw_input("Enter your remote account: ") 
password = getpass.getpass() 

tn = telnetlib.Telnet(HOST,23,5) 

tn.read_until("Username: ", 5) 
tn.write(user + "\n") 
if password: 
    tn.read_until("Password: ", 5) 
    tn.write(password + "\n") 

tn.write("en\n") 
tn.write("sh ver\n") 
tn.write("exit\n") 

print tn.read_all() 

,我有這樣的錯誤:

D:>test.py
Enter your remote account: vfomin
Password:
Traceback (most recent call last):
File "D:\test.py", line 21, in
print tn.read_all()
File "C:\Python27\lib\telnetlib.py", line 385, in read_all self.fill_rawq()
File "C:\Python27\lib\telnetlib.py", line 576, in fill_rawq buf = self.sock.recv(50)
socket.timeout: timed out

我怎樣才能連接到172.17.0.42用python?

回答

1

看來你使用的是Python3,所以你需要input而不是raw_input

0

試試這個庫(Python的2.X作品):

pip install git+https://github.com/sergeyzelyukin/cisco-telnet.git 

import ciscotelnet 
with ciscotelnet.CiscoTelnet(host, verbose = False) as cisco: 
    #if cisco.login(final_mode=CiscoTelnet.MODE_ENABLE, user="john", user_pass="12345678", enable_pass="cisco"): 
    if cisco.login(final_mode=CiscoTelnet.MODE_ENABLE, line_pass="abcdef", enable_pass="cisco"): 
    print cisco.cmd("sh int status | inc Fa0/1") 
    print cisco.conf(["interface fast0/1", "descr blank", "load-interval 300"]) 
    print cisco.wr()