zoukankan      html  css  js  c++  java
  • 彻底解决ssh.invoke_shell() 返回的中文问题

    上一篇:https://www.cnblogs.com/apff/p/9484939.html (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)
    
            #先判断提示符,然后下一步在开始发送命令,这样大部分机器就都不会出现问题
            buff = ''
            while not buff.endswith('$ '):
                resp = ssh.recv(9999)
                try: #进行异常捕捉,如果解码有问题,则换一种解码方式
                    buff += resp.decode('utf8')
                except Exception as e:
                    buff += resp.decode('gb18030')
                print(resp)
                time.sleep(0.1)
            print('获取登录后的提示符:%s' %buff)
    
    
            ssh.send(' export LANG=en_US.UTF-8 
    ') #解决错误的关键,编码问题
            ssh.send('export LANGUAGE=en 
    ')
    
            ssh.send('su - 
    ')
    
            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('
    ')
    
            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('
    ')
            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')
  • 相关阅读:
    。。。Hibernate 查询数据 事务管理。。。
    如何在easyui datagrid 中显示外键的值
    easyui datagrid 中序列化后的日期格式化
    使用Log4net把日志写入到SqlServer数据库
    在ALV点击Key值调用TCode,跳过初始屏幕
    JAVA环境变量设置
    在Jsp中调用静态资源,路径配置问题
    eclipse下项目复制改名注意事项
    HTML5与CSS3基础教程第八版学习笔记16-21章
    HTML5与CSS3基础教程第八版学习笔记11~15章
  • 原文地址:https://www.cnblogs.com/lgj8/p/12981873.html
Copyright © 2011-2022 走看看