第三篇:徹底解決ssh.invoke_shell() 返回的中文問題


 接上一篇,前兩篇解決中文的問題主要是在字符集上做的手腳,即將中文轉成英文,但是有一種情況我們都來不及做轉換,即登錄時服務器直接返回了中文內容:

此時程序報了如下錯誤,其實還是字符集問題:

為此:我們可以在接收數據的時候直接對其進行異常捕捉,如果異常則換一種解碼方式:

def verification_ssh(host,username,password,port,root_pwd,cmd):
    s=paramiko.SSHClient()
    s.load_system_host_keys()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostname = host,port=int(port),username=username, password=password)

    if username != 'root':
        ssh = s.invoke_shell()
        time.sleep(0.1)

        #先判斷提示符,然后下一步在開始發送命令,這樣大部分機器就都不會出現問題
        buff = ''
        while not buff.endswith('$ '):
            resp = ssh.recv(9999)
            try: #進行異常捕捉,如果解碼有問題,則換一種解碼方式 buff += resp.decode('utf8') except Exception as e: buff += resp.decode('gb18030') print(resp)
            time.sleep(0.1)
        print('獲取登錄后的提示符:%s' %buff)


        ssh.send(' export LANG=en_US.UTF-8 \n') #解決錯誤的關鍵,編碼問題
        ssh.send('export LANGUAGE=en \n')

        ssh.send('su - \n')

        buff = ""
        while not buff.endswith('Password: '): #true
            resp = ssh.recv(9999)
            print(resp)
            buff +=resp.decode('utf8')

        print('hhhhh')
        print(buff)

        ssh.send(root_pwd)
        ssh.send('\n')

        buff = ""
        # n = 0
        while not buff.endswith('# '):
            # n += 1
            resp = ssh.recv(9999)
            print(resp)
            buff +=resp.decode('utf8')
            # print(n)
            # if n >=3:
            #     break



        # print(buff)

        ssh.send('sh /tmp/check/101.sh') #放入要執行的命令
        ssh.send('\n')
        buff = ''
        # m = 0
        while not buff.endswith('# '):
            resp = ssh.recv(9999).decode()
            buff +=resp
            # m += 1
            # print(m)

        result  = buff
        # print(type(result))
        # print(result)
        s.close()

if __name__ == "__main__":
    verification_ssh('測試IP地址', '普通賬號', '普通賬號的密碼', '52222', 'root密碼', 'id')

 

上一篇:ssh.invoke_shell() 切換root出現的新問題

 注:轉載請注明出處


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM