Python使用Telnetlib模塊實現telnet遠程操做

Python使用Telnetlib實現遠程操做

Python內置了telnetlib模塊,支持telnet遠程操做,只要直接import就能夠。 下面是一個實例(參考http://blog.csdn.net/five3/article/details/8099997):html

#encoding=utf-8  
  
def do_telnet(Host, username, password, finish, commands):  
    import telnetlib  
    '''''Telnet遠程登陸:Windows客戶端鏈接Linux服務器'''  
   
    # 鏈接Telnet服務器  
    tn = telnetlib.Telnet(Host, port=23, timeout=10)  
    tn.set_debuglevel(2)  
       
    # 輸入登陸用戶名  
    tn.read_until('login: ')  
    tn.write(username + '\n')  
      
    # 輸入登陸密碼  
    tn.read_until('password: ')  
    tn.write(password + '\n')  
        
    # 登陸完畢後執行命令  
    tn.read_until(finish)  
    for command in commands:  
        tn.write('%s\n' % command)  
      
    #執行完畢後,終止Telnet鏈接(或輸入exit退出)  
    tn.read_until(finish)  
    tn.close() # tn.write('exit\n')  
  
if __name__=='__main__':  
     # 配置選項  
    Host = '10.255.254.205' # Telnet服務器IP  
    username = 'administrator'   # 登陸用戶名  
    password = 'dell1950'  # 登陸密碼  
    finish = ':~$ '      # 命令提示符  
    commands = ['echo "test"']  
    do_telnet(Host, username, password, finish, commands)

其中port和timeout是可選的參數,而timeout的只是在初始化socket鏈接時起做用,而一旦鏈接成功後若是出現等待那就不會起做用了,好比使用read_until方式獲取內容時返回的內容與指定的內容沒有吻合,那麼就會形成提示等待的狀況,這時timeout是不會起做用的,而這個socket鏈接會一直保持着,永生不死。python

那麼如何解決這個問題呢,其實還有一種比較原始的方法,就是使用sleep方法來代替read_until方法,這樣就不會出現種狀況,由於到點就會本身輸入,最多也就是最後得不到想要的結果,可是這個方式很不穩定,兼容性也很差;另外一種方法是使用線程來啓動這個函數,而後對子線程進行超時設置,這樣就能夠達到間接控制這個telnet鏈接的目的了。linux

import threading  

pars = replace_db_keyworlds(vars_dict, pars)  
configs = pars.split(r'@')  
host = configs[0].encode()  
user = configs[1]  
passwd = configs[2]  
finish = configs[3]  
commands = configs[4].split(r'\n')  
th1 = threading.Thread(target=do_telnet, args=(host.encode('utf-8'), user.encode('utf-8'), passwd.encode('utf-8'), finish.encode('utf-8'), commands))  
th1.start()  
th1.join(20)  ##20秒超時時間

遇到的問題:

** 傳遞給Telnet方法的字符串都會被解一次碼,因此若是你傳遞過去須要write的字符串是已經解碼的unicode的話,那麼就會報錯的,因此在傳遞發送的字符串以前仍是先編成utf-8爲妥,用ascii編碼也能夠。 **服務器

我用python3搭建了一個環境,telnet到嵌入式linux系統時,報以下錯誤信息:socket

TypeError: 'in <string>' requires string as left operand, not bytes函數

解決辦法: 用encode()函數將字符串編碼就能夠了,好比tn.read_until('login: '.encode('utf-8')) 就能夠解決。 又如(具體見https://docs.python.org/3/library/telnetlib.html):ui

import getpass  
import telnetlib  
  
HOST = "localhost"  
user = input("Enter your remote account: ")  
password = getpass.getpass()  
  
tn = telnetlib.Telnet(HOST)  
  
tn.read_until(b"login: ")  
tn.write(user.encode('ascii') + b"\n")  
if password:  
    tn.read_until(b"Password: ")  
    tn.write(password.encode('ascii') + b"\n")  
  
tn.write(b"ls\n")  
tn.write(b"exit\n")  
  
print(tn.read_all().decode('ascii'))

此外,還有一個pexpect的第三方模塊能夠支持telnet等一系列的協議鏈接,並支持交互式的通訊。編碼

參考博客:http://blog.csdn.net/five3/article/details/8099997.net

相關文章
相關標籤/搜索