Next: In accordance with the previous article, in the Ssh.invoke_shell () after the execution of the login prompt to judge, there is a part of the machine back because the return to empty causes the program to die.
Normal machine SSH.RECV (9999) command return content:
B ' Last Login:sat-22:06:17 2018 from 172.37.100.111\r\r\n[[email protected]_kt_mas2 ~]$ '
B ' Export Lang=en_us. UTF-8 \r\n[[email protected]_kt_mas2 ~]$ export language=en \r\n[[email protected]_kt_mas2 ~]$ Su-\r\nPassword: '
The program's simulation login process is as follows (SSH.RECV (9999) command receives the decoded result of the return value):
Abnormal machine SSH.RECV (9999) command return content:
B ' Export Lang=en_us. UTF-8 \ r \ n '
B ' Export language=en \r\nsu-\r\nlast Login:sat 21:42:09 from 172.16.112.2\r\n[[email protected] ~]$ '
The program's simulation login process is as follows (SSH.RECV (9999) command receives the decoded result of the return value)
As above, according to the original cycle, the loop can not judge password: position, so the abnormal machine at this time, the phenomenon of deadlock, the practice of solving this problem: Before executing the command, the first time to judge the login: "$", and then execute the command.
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)
#先判断提示符, and then the next step is to start sending commands so that most machines will not have problem buff="' while notBuff.endswith ('$ '): Resp= SSH.RECV (9999) #print (RESP)Buff + = Resp.decode ('UTF8') 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: https://www.cnblogs.com/apff/p/9484939.html (Python How to implement a normal user login server after switching to the root user and then execute the command encountered error resolution)
Article Two: Ssh.invoke_shell () switch root new issues