Next, the first two issues to solve the Chinese problem is mainly in the character set on the hands and feet, will be translated into English, but there is a situation we are too late to do the conversion, that is, log on the server directly returned the Chinese content:
At this time the program reported the following error, in fact, the character set problem:
For this reason: we can receive the data directly to the abnormal capture, if the exception is a way to decode:
defverification_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)ifUsername! ='Root': SSH=S.invoke_shell () time.sleep (0.1) #start by judging the prompt, and then the next step is to begin sending commands so that most machines will not have problemsBuff ="' while notBuff.endswith ('$ '): Resp= SSH.RECV (9999) Try: # for exception snapping, if there is a problem decoding, then a different way to decode the buff + = Resp.decode ('utf8') except Exception as E:buff + = Resp.decode (' gb18030') print (RESP) Time.sleep (0.1) Print('get sign-in prompt:%s'%buff) ssh.send ('export Lang=en_us. UTF-8 \ n')#the key to solving the error, coding problemsSsh.send ('export language=en \ n') Ssh.send ('Su-\ n') Buff="" while notBuff.endswith ('Password:'):#trueRESP = SSH.RECV (9999) Print(RESP) Buff+=resp.decode ('UTF8') Print('hhhhh') Print(Buff) ssh.send (root_pwd) ssh.send ('\ n') Buff="" #n = 0 while notBuff.endswith ('# '): #n + = 1RESP = SSH.RECV (9999) Print(RESP) Buff+=resp.decode ('UTF8') #print (n) #if n >=3: # Break #print (Buff)Ssh.send ('sh/tmp/check/101.sh')#put the command you want to executeSsh.send ('\ n') Buff="' #m = 0 while notBuff.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 ('Test IP Address','General Account','password for normal account','52222','Root Password','ID')
Previous: Ssh.invoke_shell () switch root new issues
NOTE: Reprint please indicate the source
The third article: completely solve the Chinese problem returned by Ssh.invoke_shell ()