Python telnet編程代碼
作者:佚名
下面我們簡單介紹一下Python telnet的實現過程,那么具體的代碼內容我們也做了詳細介紹,希望大家能夠得到參考。
在進行telnet的相關設置中,我們通常會接觸其他語言來進行編輯。這里我們主要介紹一下用腳本來實現這方面的操作。包括Python telnet的實現過程。那么具體的內容請大家來看文章內容吧。
一、Shell實現,文件名:autotelnet.sh,代碼如下:
- (sleep 1;echo "root";sleep 1;echo "123456";sleep 1;echo "en";sleep 1;echo "1qazse4";sleep 1;echo "conf t";sleep 1;echo "int fa0/1";sleep 1;echo "switchport mode multi";sleep 1;echo "end";sleep 1;echo "exit") | telnet 10.32.17.10
二、Expect來實現,文件名:autotelnet.exp,代碼如下:
- #!/usr/bin/expect
- set timeout 100
- set TERM xterm
- set SERVER "10.32.17.10"
- set USER "root"
- set PASSWD "123456"
- spawn telnet
- expect "telnet> "
- send "open $SERVERr"
- expect "Username:"
- send "$USERr"
- expect "Password:"
- send "$PASSWDr"
- expect "longjiang-zero>"
- send "enr"
- expect "Password:"
- send "$PASSWDr"
- expect "longjiang-zero#"
- send "conf tr"
- expect "longjiang-zero(config)#"
- send "int fa0/1r"
- expect "longjiang-zero(config-if)#"
- send "switchport mode multir"
- expect "longjiang-zero(config-if)#"
- send "endr"
- expect "longjiang-zero#"
- send "exitr"
- interact
三、Python telnet的實現,文件名:autotelnet.py,代碼如下:
- #!/usr/bin/python
- import telnetlib
- host = ''10.32.17.10''
- user = ''root''
- password = ''123456''
- commands = [''en'',password,''conf t'',''int fa0/1'',''switchport mode multi'',''end'']
- tn = telnetlib.Telnet(host)
- tn.read_until("Username:")
- tn.write(user + "n")
- tn.read_until("Password:")
- tn.write(password + "n")
- for command in commands:
- tn.write(command+''n'')
- tn.write("exitn")
- print tn.read_all()
- print ''Finish!''
到這里我們就已經完成了Python telnet的實現過程了。
責任編輯:佟健
來源:
互聯網