2011-08-25 60 views
0

我有一個使用的paramiko抓住從遠程服務器建立文件的一些Python代碼:Paramiko SFTP - 避免必須指定完整的本地文件名?

def setup_sftp_session(self, host='server.com', port=22, username='puppy'): 
    self.transport = paramiko.Transport((host, port)) 
    privatekeyfile = os.path.expanduser('~/.ssh/id_dsa') 
    try: 
     ssh_key = paramiko.DSSKey.from_private_key_file(privatekeyfile) 
    except IOError, e: 
     self.logger.error('Unable to find SSH keyfile: %s' % str(e)) 
     sys.exit(1) 
    try: 
     self.transport.connect(username = username, pkey = ssh_key) 
    except paramiko.AuthenticationException, e: 
     self.logger.error("Unable to logon - are you sure you've added the pubkey to the server?: %s" % str(e)) 
     sys.exit(1) 
    self.sftp = paramiko.SFTPClient.from_transport(self.transport) 
    self.sftp.chdir('/some/location/buildfiles') 

def get_file(self, remote_filename): 
    try: 
     self.sftp.get(remote_filename, 'I just want to save it in the local cwd') 
    except IOError, e: 
     self.logger.error('Unable to find copy remote file %s' % str(e)) 

def close_sftp_session(self): 
    self.sftp.close() 
    self.transport.close() 

我想檢索每個文件,並在當前本地工作目錄存入銀行。

但是,Paramiko似乎沒有這個選項 - 您需要指定完整的本地目標。你甚至不能指定一個目錄(例如「./」,甚至「/ home/victorhooi/files」) - 你需要包含文件名的完整路徑。

有沒有辦法解決這個問題?如果我們必須指定本地文件名,而不是僅僅複製遠程文件名就會很麻煩。

另外 - 我在setup_sftp_session中處理異常的方式,退出(1) - 是一種很好的做法,還是有更好的方法?

乾杯, 維克多

+0

我真的只是編碼,並沒有找到一種方式,我害怕。你需要一個本地文件名,但你可以把它當作一個小小的sop來稱呼它。 – Ben

回答

1

你必須插入

os.path.join(os.getcwd(), remote_filename) 

調用exit()函數中是不是一個好主意。也許你想重用代碼並在發生異常時採取一些行動。如果你保持退出()電話,你會失去。 我建議修改這個函數,如果成功則返回True,否則返回False。然後來電者可以決定要做什麼。

另一種方法是不去捕捉例外。因此,調用者必須處理它們,調用者獲取有關失敗情況的完整信息(包括堆棧跟蹤)。

+0

啊哈,很酷,我會用os.getcwd()then =)。嗯,你的評論關於不在函數中調用exit() - 我從__main__調用它。如果無法獲取文件,我需要退出程序 - 您是否說我應該在__main__中執行該調用。還是有更好的辦法讓這些例外很好地退出程序? – victorhooi

+0

好的,如果你在main中使用exit()是一種不同的情況。如果我將這個程序用於個人使用,我根本就不會去捕捉這些例外。所以你得到一個關於失敗的信息的堆棧跟蹤。如果您將它交付給客戶,我會捕獲異常並將堆棧跟蹤記錄到日誌文件中。 – rocksportrocker