有時候我們會需要利用程式來操作一些設備

操作的方法有很多,可以透過telnet、ssh、snmp等等

import telnetlib

host = "192.168.127.162"
user = "test"
passwd = "123"

'''存放指令字串的陣列'''
command_arr = ["en","passwd","conf ter",
               "arp 120.119.77.248 0000.0000.1000 arpa",
               "exit","exit"]

'''連接主機'''
tn = telnetlib.Telnet(host)
'設定debug level
tn.set_debuglevel(2)

'''當程式讀到特定字串時,再將帳密送入'''
tn.read_until("Username:")
tn.write(user + "\n")

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

'''將指令依序傳入'''
for command in command_arr :
    tn.write(command + "\n")

'''讀取全部輸入的東西'''
print tn.read_all()

tn.close()

Categories: Python