第二篇:ssh.invoke_shell() 切換root出現的新問題
接上一篇:按照上一篇的方式,在沒有對ssh.invoke_shell()執行後的登錄提示符進行判斷的話,那邊有部分機器就回因為返回為空導致程序卡死。
正常機器 ssh.recv(9999) 命令返回內容:
b‘Last login: Sat Aug 18 22:06:17 2018 from 172.37.100.111\r\r\n[cattsoft@ZB_KT_MAS2 ~]$ ‘
b‘export LANG=en_US.UTF-8 \r\n[cattsoft@ZB_KT_MAS2 ~]$ export LANGUAGE=en \r\n[cattsoft@ZB_KT_MAS2 ~]$ su - \r\nPassword: ‘
程序的模擬登陸過程如下(以下圖片內容為ssh.recv(9999) 命令接收返回值解碼後的結果):
異常機器ssh.recv(9999) 命令返回內容:
b‘export LANG=en_US.UTF-8 \r\n‘
b‘export LANGUAGE=en \r\nsu - \r\nLast login: Sat Aug 18 21:42:09 from 172.16.112.2\r\n[cattsoft@trancache01 ~]$ ‘
程序的模擬登陸過程如下(以下圖片內容為ssh.recv(9999) 命令接收返回值解碼後的結果)
如上,按照原來的循環方式,循環無法判斷Password:位置,所以異常機器此時就回出現卡死現象,解決此問題的做法:在執行命令前,先判斷一次登陸符:“$”,然後在執行命令。
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) # print(resp) buff += resp.decode(‘utf8‘) 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‘)
上一篇:https://www.cnblogs.com/apff/p/9484939.html (python如何實現普通用戶登錄服務器後切換到root用戶再執行命令遇到的錯誤解決 )
第二篇:ssh.invoke_shell() 切換root出現的新問題