我有一台远程服务器,安装的是 CentOS,我现在想通过 Python 获取该服务器上的日志(messages)文件,并将内容写入到一个 txt 文件中
import paramiko
ip = "192.168.4.5"
username = "root"
password = "P@ssw0rd"
log = open("log.txt", "w")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, port=22, username=username, password=password, timeout=20)
ssh_stdin, ssh_stdout, ssh_stderr = client.exec_command("cat /var/log/messages | grep -i error")
blog.write(str(ssh_stdout.read()))
log.close()
client.close()
通过该方法我可以将日志内容写入到 log.txt 文件中,但是所有脚本内容却写在了同一行。
b'Aug 5 15:45:18 localhost kernel: RAS: Correctable Errors collector initialized.\nAug 5 15:45:19 localhost kernel: [drm] It appears like vesafb is loaded. Ignore