无法在 python 中追加 ssh 客户端返回的文本
Unable to append text returned by ssh client in python
使用 paramiko 模块。我正在尝试在远程系统上执行 ssh。我正在执行一个命令并需要在文本文件 hcc.txt 中输出它们。因此,我正在创建一个文件对象并将命令 o/p 保存在同一个文本文件中。
第一个功能是写入 o/p,第二个功能是将 o/p 附加到现有文本文件 hcc.txt 中。
不知何故附加不起作用。
导入 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=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()
O/p in file hcc.txt is "aab'There are no unfixed errors\n'"
我期待 o/p 如下所示
"aab'没有不固定的errors\n'"
"ab'没有不固定的errors\n'"
Python 文档中有一个 warning 适用于您问题中的代码:
Warning
Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.
因此您应该调用 fo.close
或使用上下文管理器:
with open("hcc.txt",'a') as fo:
fo.write('a' + x)
使用 paramiko 模块。我正在尝试在远程系统上执行 ssh。我正在执行一个命令并需要在文本文件 hcc.txt 中输出它们。因此,我正在创建一个文件对象并将命令 o/p 保存在同一个文本文件中。 第一个功能是写入 o/p,第二个功能是将 o/p 附加到现有文本文件 hcc.txt 中。 不知何故附加不起作用。 导入 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=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()
O/p in file hcc.txt is "aab'There are no unfixed errors\n'" 我期待 o/p 如下所示
"aab'没有不固定的errors\n'" "ab'没有不固定的errors\n'"
Python 文档中有一个 warning 适用于您问题中的代码:
Warning
Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.
因此您应该调用 fo.close
或使用上下文管理器:
with open("hcc.txt",'a') as fo:
fo.write('a' + x)