我想使用paramiko和sftp客户端来轮询日志文件的最后一行。我知道python中的sshtail模块,但是使用它违反了我现在的编码标准。
我以前用过,现在我想知道如何去读取日志文件的最后一行?
谢谢,
帕斯
编辑2:
try:
self.logger.info("SSH Log: trying to connect to: " + self.ssh_server_ip + "," + str(self.ssh_port) + "," + self.ssh_username + "," + self.ssh_password)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.ssh_server_ip, self.log_server_port, self.ssh_username, self.ssh_password)
self.logger.info("SSH LOG: Deleting files from HTTP Upload Server")
sftp = client.open_sftp()
remote_command = "tail -n1 /var/log/apache2/access.log"
stdin, stdout, stderr = client.exec_command(remote_command)
last_line = stdout.read()
old_line = last_line
while 1:
remote_command = "tail -n1 /var/log/apache2/access.log"
stdin, stdout, stderr = client.exec_command(remote_command)
last_line = stdout.read()
if last_line != old_line:
finish_line = last_line
break
self.logger.info("SSH Log: closing connection")
sftp.close()
client.close()
except Exception, e:
self.logger.error(str(e))
self.logger.error("Failed to delete file on HTTP server: " + str(e))
except:
self.logger.error("Failed to delete file on HTTP server")
最佳答案
通过 shell 远程调用文件上的tail -n1
并读取其stdout可以更快,更轻松。就像是:
remote_command = "tail -n1 /var/log/apache2/access.log"
stdin, stdout, stderr = client.exec_command(remote_command)
last_line = stdout.read()