Python telnet编程代码


在进行telnet的相关设置中,我们通常会接触其他语言来进行编辑。这里我们主要介绍一下用脚本来实现这方面的操作。包括Python telnet的实现过程。那么具体的内容请大家来看文章内容吧。

一、Shell实现,文件名:autotelnet.sh,代码如下:

  1. (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,代码如下:

  1. #!/usr/bin/expect  
  2. set timeout 100  
  3. set TERM xterm  
  4. set SERVER "10.32.17.10"  
  5. set USER "root"  
  6. set PASSWD "123456"  
  7. spawn telnet  
  8. expect "telnet> "  
  9. send "open $SERVERr"  
  10. expect "Username:"  
  11. send "$USERr"  
  12. expect "Password:"  
  13. send "$PASSWDr"  
  14. expect "longjiang-zero>"  
  15. send "enr"  
  16. expect "Password:"  
  17. send "$PASSWDr"  
  18. expect "longjiang-zero#"  
  19. send "conf tr"  
  20. expect "longjiang-zero(config)#"  
  21. send "int fa0/1r"  
  22. expect "longjiang-zero(config-if)#"  
  23. send "switchport mode multir"  
  24. expect "longjiang-zero(config-if)#"  
  25. send "endr"  
  26. expect "longjiang-zero#"  
  27. send "exitr"  
  28. interact 

三、Python telnet的实现,文件名:autotelnet.py,代码如下:

  1. #!/usr/bin/python  
  2. import telnetlib  
  3. host = ''10.32.17.10''  
  4. user = ''root''  
  5. password = ''123456''  
  6. commands = [''en'',password,''conf t'',''int fa0/1'',''switchport mode multi'',''end'']  
  7. tn = telnetlib.Telnet(host)  
  8. tn.read_until("Username:")  
  9. tn.write(user + "n")  
  10. tn.read_until("Password:")  
  11. tn.write(password + "n")  
  12. for command in commands:  
  13. tn.write(command+''n'')  
  14. tn.write("exitn")  
  15. print tn.read_all()  
  16. print ''Finish!'' 

到这里我们就已经完成了Python telnet的实现过程了。

相关内容

    暂无相关文章