2012-03-24 22 views
1

我想使用paramiko和sftp客戶端輪詢最後一行的日誌文件。我知道python中的sshtail模塊,但是使用它與我現在的編碼標準背道而馳。Paramiko - sftp客戶端用於獲取日誌文件的最後一行

我以前使用過,現在我想知道如何去閱讀日誌文件的最後一行?

感謝,

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

我假設該文件在遠程服務器上呢?你試過什麼了? – Ben 2012-03-24 21:30:51

+0

它在運行Ubuntu 11.10的遠程Linux服務器上。我剛剛使用sshtail模塊來定位文件。我只應該期待一個非空白的日誌。一旦我得到它,我保存並解析它。 – Parth 2012-03-24 21:32:01

+0

我的意思是你有任何代碼發佈,這是你試圖解決這個問題?預計你會先做一些嘗試,而不是僅僅詢問代碼:[ask] – Ben 2012-03-24 21:36:00

回答

2

它可以更快,更容易只需要調用tail -n1上的文件通過外殼和遠程讀取它的標準輸出。例如:

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

我應該只是做一個尾巴-f實際上?你能否提供你想要的代碼? – Parth 2012-03-26 16:21:16

+0

'tail -f'是* follow *模式 - 可能不是你想要的。我用一些代碼更新了我的回覆。 – 2012-03-26 16:28:14

+0

-n1會得到文件的最後一行。我正在等待文件下載,訪問日誌會指示它已完成下載。那麼如何使用尾巴-f – Parth 2012-03-26 16:30:00