第三篇:彻底解决ssh.invoke_shell() 返回的中文问题

本文介绍了一种解决SSH登录时遇到的中文字符集问题的方法。通过使用异常捕捉及多种解码方式,确保了不同环境下中文内容的正确显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 接上一篇,前两篇解决中文的问题主要是在字符集上做的手脚,即将中文转成英文,但是有一种情况我们都来不及做转换,即登录时服务器直接返回了中文内容:

此时程序报了如下错误,其实还是字符集问题:

为此:我们可以在接收数据的时候直接对其进行异常捕捉,如果异常则换一种解码方式:

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 \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')

 

上一篇:ssh.invoke_shell() 切换root出现的新问题

 注:转载请注明出处

转载于:https://www.cnblogs.com/apff/p/9502640.html

``` import paramiko,re,time from datetime import datetime from config01 import userlist,x_xml from threading import Thread import threading class SW(): def __init__(self): self.ssh=paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname="192.168.100.1",port=22,username="python", password="Huawei@123",allow_agent=False,look_for_keys=False) self.vty=self.ssh.invoke_shell() print("ssh 连接成功") self.send_com("screen-length 0 temporary") def send_com(self,com): self.vty.send(com+"\n") time.sleep(2) return self.vty.recv(65535).decode("utf-8") def jhjzt(self): while True: p_list=[] for i in userlist.keys(): pat=self.send_com(userlist[i]["com"]) res = re.compile(userlist[i]["re"]).findall(pat) if i =="fan":res =res if res else "all fan are faulty" p_list.append(f"{i}:{res}") with open(r"E:\PYTHON\tets011", 'w') as f: f.write(pat) print("\n".join(p_list)) time.sleep(60*5) def xiazai(self): while True: with paramiko.Transport(("192.168.100.1",22)) as t : t.connect(username="python",password="Huawei@123") sftp= paramiko.SFTPClient.from_transport(t) sftp.get("/vrpcfg.zip", f"{datetime.now().strftime('%Y_%d_%m_%H_%M_%S')}_X_T1_AGG1.zip") print("下载成功") time.sleep(60*60*24) def binfa(self): Thread(target=self.jhjzt).start() Thread(target=self.xiazai).start() file_lock = threading.Lock() def write_file(data, file_path): with file_lock: # 获取锁 try: with open(file_path, 'w') as f: f.write(data) except PermissionError as e: print(f"权限错误: {e}") # 添加重试逻辑(见步骤3) if __name__ == '__main__': SW().binfa()```我想让所有的txt全部放入一个文件夹中 已日期命名并且为我自动在目录下创建
03-22
``` import paramiko, re, time from datetime import datetime from config02 import userlist from threading import Thread import os # 新增导入 class SW(): def __init__(self): self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname="192.168.100.1", port=22, username="python", password="Huawei@123", allow_agent=False, look_for_keys=False) self.vty = self.ssh.invoke_shell() print("ssh 连接成功") self.send_com("screen-length 0 temporary") def send_com(self, com): self.vty.send(com + "\n") time.sleep(2) return self.vty.recv(65535).decode("utf-8") def jhjzt(self): while True: p_list = [] for i in userlist.keys(): pat = self.send_com(userlist[i]["com"]) res = re.compile(userlist[i]["re"]).findall(pat) if i == "fan": res = res if res else "all fan are faulty" p_list.append(f"{i}:{res}") # 创建日期目录逻辑 current_date = datetime.now().strftime("%Y-%m-%d") # 生成日期字符串 target_dir = os.path.join(r"E:\PYTHON", current_date) # 拼接目标路径 os.makedirs(target_dir, exist_ok=True) # 自动创建目录(存在则不创建) file_path = os.path.join(target_dir, "device_status.txt") # 新文件路径 with open(file_path, 'w') as f: f.write(pat) print("\n".join(p_list)) time.sleep(60 * 5) def xiazai(self): while True: current_date = datetime.now().strftime("%Y-%m-%d") target_dir = os.path.join(r"E:\PYTHON", current_date) os.makedirs(target_dir, exist_ok=True) file_name = f"{datetime.now().strftime('%H-%M-%S')}_X_T1_AGG1.zip" # 按时间命名文件 file_path = os.path.join(target_dir, file_name) with paramiko.Transport(("192.168.100.1", 22)) as t: t.connect(username="python", password="Huawei@123") sftp = paramiko.SFTPClient.from_transport(t) sftp.get("/vrpcfg.zip", file_path) # 保存到日期目录 print("下载成功") time.sleep(60 * 60 * 24) def binfa(self): Thread(target=self.jhjzt).start() Thread(target=self.xiazai).start() if __name__ == '__main__': SW().binfa()```Exception in thread Thread-4: Traceback (most recent call last): File "E:\Users\zzChen\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "E:\Users\zzChen\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "E:/PYTHON/tets011/test03.py", line 63, in xiazai sftp.get("/vrpcfg.zip", file_path) # 保存到日期目录 File "E:\PYTHON\tets011\venv\lib\site-packages\paramiko\sftp_client.py", line 840, in get size = self.getfo( File "E:\PYTHON\tets011\venv\lib\site-packages\paramiko\sftp_client.py", line 795, in getfo file_size = self.stat(remotepath).st_size File "E:\PYTHON\tets011\venv\lib\site-packages\paramiko\sftp_client.py", line 493, in stat t, msg = self._request(CMD_STAT, path) File "E:\PYTHON\tets011\venv\lib\site-packages\paramiko\sftp_client.py", line 857, in _request return self._read_response(num) File "E:\PYTHON\tets011\venv\lib\site-packages\paramiko\sftp_client.py", line 909, in _read_response self._convert_status(msg) File "E:\PYTHON\tets011\venv\lib\site-packages\paramiko\sftp_client.py", line 938, in _convert_status raise IOError(errno.ENOENT, text) FileNotFoundError: [Errno 2] No such file Process finished with exit code -1
最新发布
03-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值