【问题标题】:Unable to append text returned by ssh client in python无法在 python 中附加 ssh 客户端返回的文本
【发布时间】:2022-01-20 17:41:00
【问题描述】:

使用 paramiko 模块。我正在尝试在远程系统上执行 ssh。在那里我正在执行一个命令,并且需要它们在文本文件 hcc.txt 中的输出。因此,我正在创建一个文件对象并将命令 o/p 保存在同一个文本文件中。 第一个功能是写入 o/p,第二个功能是将 o/p 附加到现有的文本文件 hcc 中。 不知何故,附加不起作用。 进口帕拉米科

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=str(usern),password=str(passwd),port=22)
    stdin, stdout, stderr = ssh.exec_command('finderr')
    x = str(stdout.read())
    fo = open("hcc.txt",'w')
    fo.write('aa' +x)
    fo.close()

def a():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname='2.2.2.2',username=str(usern),password=str(passwd),port=22)
    stdin, stdout, stderr = ssh.exec_command('finderr')
    x = str(stdout.read())
    fo = open("hcc.txt",'a')
    fo.write('a' +x)

aa()
a()

文件 hcc.txt 中的 O/p 为 "aab'There are no unfixed errors\n'" 我期待像下面这样的o/p

"aab'没有未修复的错误\n'" "ab'没有未修复的错误\n'"

【问题讨论】:

  • 上下文管理器怎么样:with open('hcc.txt', 'a') as fo: fo.write('a' + x)
  • 警告调用 f.write() 而不使用 with 关键字或调用 f.close() 可能会导致 f.write() 的参数没有完全写入磁盘,即使程序成功退出。 docs.python.org/3/tutorial/…
  • with open('hcc.txt', 'a') -- 我正在以追加模式重新打开文件,并且使用 fo.write('a' + x) 我期待命令输出function(a) 附加在 function(aa) 中返回的第一个输出旁边。
  • 当然可以,但之后你不会关闭它。
  • 你是对的。太感谢了。我把它修好了。

标签: python paramiko


【解决方案1】:

Python 文档中有一个warning 适用于您问题中的代码:

警告

不使用 with 关键字调用 f.write() 或调用 f.close() 可能会导致 f.write() 的参数没有完全写入磁盘,即使程序成功退出。

所以您应该调用fo.close 或使用上下文管理器:

with open("hcc.txt",'a') as fo:
    fo.write('a' + x)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 2015-07-17
    相关资源
    最近更新 更多