第一篇:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 0: invalid continuation byte


需求:python如何實現普通用戶登錄服務器后切換到root用戶再執行命令 

解決參考:

代碼:

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)
        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.send(' export LANG=en_US.UTF-8 \n'),即可解決上述問題

 因為中文和英文字符集轉換不同,所以導致報錯。

補充:由於操作系統字符集中‘LANGUAGE="zh_CN.GB18030:zh_CN.GB2312:zh_CN"’的緣故,即使修改了LANG也是無用的,入下圖

此時還需將LANGUAGE的變量值修改:export LANGUAGE=en

 

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

注:轉載請注明出處


免責聲明!

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



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