You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python paramiko SSH客户端返回文本无法追加写入文件问题

问题根因

追加功能失效的核心原因是a()函数中以追加模式打开文件写入内容后,没有调用close()方法关闭文件对象,写入的内容滞留在内存缓冲区,没有被实际写入磁盘文件。除此之外代码还有几个影响运行和输出格式的问题:

  • 直接用str()转换stdout.read()返回的字节类型结果,会把bytes类型的前缀b''和转义字符一起写入文件
  • 两次写入的内容之间没有添加换行符,就算追加成功也不会分成两行
  • 原代码缺失paramiko模块的导入语句,直接运行会报错
  • SSH连接使用完成后没有主动关闭,会造成资源泄露
修复后可直接运行的代码
import paramiko
usern = input("Enter your user name ")
passwd = input("Enter your password ")


def aa():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname='1.1.1.1', username=usern, password=passwd, port=22)
    stdin, stdout, stderr = ssh.exec_command('finderr')
    # 按utf-8解码命令输出的字节内容,避免出现b''格式标记
    cmd_output = stdout.read().decode('utf-8').strip()
    # with上下文管理器自动处理文件关闭、缓冲区刷新,无需手动调用close
    with open("hcc.txt", 'w', encoding='utf-8') as f:
        f.write(f"aa{cmd_output}\n")
    ssh.close()


def a():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname='2.2.2.2', username=usern, password=passwd, port=22)
    stdin, stdout, stderr = ssh.exec_command('finderr')
    cmd_output = stdout.read().decode('utf-8').strip()
    with open("hcc.txt", 'a', encoding='utf-8') as f:
        f.write(f"a{cmd_output}\n")
    ssh.close()


aa()
a()
修复说明
  • 补全import paramiko导入语句,解决基础运行报错
  • 用decode('utf-8')替代直接str()转换字节内容,输出内容不会带多余的b''标记
  • 所有文件操作改用with上下文管理器实现,从根源上避免忘记关闭文件导致内容写入失败的问题
  • 每次写入内容末尾添加换行符\n,保证两次写入的内容各占一行,符合预期格式
  • 增加SSH连接关闭逻辑,避免无用连接占用资源
  • 去掉了多余的str()转换,input()返回值本身就是字符串类型,无需重复转换

如果不想改动原有代码结构,只需要在a()函数的fo.write('a' +x)语句下新增一行fo.close(),就能解决追加内容不写入的问题,不过还是推荐使用上下文管理器的写法,更稳妥不易出错。

内容的提问来源于stack exchange,提问作者Ashish Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.17 16:16:01