接上一篇:按照上一篇的方式,在没有对ssh.invoke_shell()执行后的登陆提示符进行判断的话,那边有部分机器就回由于返回为空致使程序卡死。html
正常机器 ssh.recv(9999) 命令返回内容:python
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: 'shell
程序的模拟登录过程以下(如下图片内容为ssh.recv(9999) 命令接收返回值解码后的结果):服务器
异常机器ssh.recv(9999) 命令返回内容:ssh
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:位置,因此异常机器此时就回出现卡死现象,解决此问题的作法:在执行命令前,先判断一次登录符:“$”,而后在执行命令。spa
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')
上一篇:http://www.javashuo.com/article/p-kywvlfxm-gu.html(python如何实现普通用户登陆服务器后切换到root用户再执行命令遇到的错误解决 )code