如何使用python利用telnet指令到網路設備下指令並捉取回傳的資料
範例如下
#!/usr/bin/python
import os
import telnetlib
host="1.1.1.1"
user="abc"
passwd="password"
tn = telnetlib.Telnet(host)
tn.read_until("login: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(passwd + "\n")
#read_until()到下完password 即可 接下來的指令必須一直下
#不再使用read_until() 否則最後的 print tn.read_all() 會沒有資料
tn.write("ls -al" + "\n")
tn.write("exit" + "\n")
print tn.read_all()
2014/01/05
import telnetlib
f = open("switch")
lines = f.read().splitlines()
#print lines
command_arr = ["123456","en","123456","terminal length 0","sh mac add","exit"]
#print command_arr
for HOST in lines:
#print HOST
tn = telnetlib.Telnet(HOST)
for command in command_arr :
tn.write(command + "\n")
#print tn.read_all()
content = tn.read_all()
print content
chk = content.find("1122.3344.5566") #找出這個mac是否在這台switch上 在那一個port上
print chk
tn.close()
f = open("switch")
lines = f.read().splitlines()
#print lines
command_arr = ["123456","en","123456","terminal length 0","sh mac add","exit"]
#print command_arr
for HOST in lines:
#print HOST
tn = telnetlib.Telnet(HOST)
for command in command_arr :
tn.write(command + "\n")
#print tn.read_all()
content = tn.read_all()
print content
chk = content.find("1122.3344.5566") #找出這個mac是否在這台switch上 在那一個port上
print chk
tn.close()
2014/01/04
使用python的 telnetlib對網路設備進行一些自動化的操作
範例如下
import telnetlib
HOST = "1.1.1.1"
tn = telnetlib.Telnet(HOST)
tn.read_until("Password: ")
tn.write("12345\n")
tn.read_until("cc>")
tn.write("en\n")
tn.read_until("Password: ")
tn.write("12345\n")
tn.write("sh flash\n")
tn.write("exit\n")
print tn.read_all()
http://blog.johnsonlu.org/category/programe/pythin/
http://docs.python.org/2/library/telnetlib.html
範例如下
import telnetlib
HOST = "1.1.1.1"
tn = telnetlib.Telnet(HOST)
tn.read_until("Password: ")
tn.write("12345\n")
tn.read_until("cc>")
tn.write("en\n")
tn.read_until("Password: ")
tn.write("12345\n")
tn.write("sh flash\n")
tn.write("exit\n")
print tn.read_all()
http://blog.johnsonlu.org/category/programe/pythin/
http://docs.python.org/2/library/telnetlib.html
訂閱:
文章 (Atom)