实现autoTelnet的三类编程代码


在一些编程应用中,我们常会涉及到autoTelnet的相关内容。这里我们就对autoTelnet的实现方法进行了探讨。我们通过三种方法来实现这个文件。那么具体的代码实现就请从文中来详细看一下吧。

一、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,代码如下:

  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来实现,文件名: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!''  

相关内容