Paramiko - sftp客户端用于获取最后一行日志文件

时间:2012-03-24 21:26:01

标签: python file ssh paramiko

我想使用paramiko和sftp客户端轮询最后一行的日志文件。我知道python中的sshtail模块,但使用它违反了我现在的编码标准。

我之前使用过,现在我想知道如何阅读日志文件的最后一行?

谢谢,

PARTH

EDIT2:

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")

1 个答案:

答案 0 :(得分:2)

通过shell远程调用文件tail -n1并读取其标准输出可以更快更容易。类似的东西:

remote_command = "tail -n1 /var/log/apache2/access.log"
stdin, stdout, stderr = client.exec_command(remote_command)
last_line = stdout.read()