2013-01-18 367 views
5

我有兩個服務器A和B.我想從服務器A發送圖像文件到另一個服務器B.但是在服務器A可以發送文件結束我想檢查服務器B中是否存在類似的文件。我嘗試使用os.path.exists(),它不起作用。使用Python檢查遠程SSH服務器上的文件是否存在

print os.path.exists('[email protected]:b.jpeg') 

結果返回假,即使我已經把我不知道是否是我的語法錯誤或者是有沒有更好的辦法解決這個問題上的服務器B.一個確切的文件。謝謝

+0

你是什麼意思的「服務器」?它是一個SSH服務器?我很確定'os.path'模塊不理解任何網絡協議。當然,如果網絡路徑安裝在文件系統的某處,那麼您可以通過它的路徑訪問它。 – DaveP

+0

是的,它是一個SSH服務器 –

回答

16

os.path函數只能在同一臺計算機上的文件。他們在路徑上運行,而[email protected]:b.jpeg不是路徑。

爲了做到這一點,您需要遠程執行腳本。這樣的事情會的工作,通常是:

def exists_remote(host, path): 
    """Test if a file exists at path on a host accessible with SSH.""" 
    status = subprocess.call(
     ['ssh', host, 'test -f {}'.format(pipes.quote(path))]) 
    if status == 0: 
     return True 
    if status == 1: 
     return False 
    raise Exception('SSH failed') 

所以,你可以,如果一個文件在另一臺服務器上存在獲取:

if exists_remote('[email protected]', 'b.jpeg'): 
    # it exists... 

注意,這將可能是難以置信緩慢,可能甚至超過100毫秒。

+0

謝謝。它工作很棒! –

+3

'return subprocess.call(['ssh',host,'test -e'+ pipes.quote(path)])== 0' – jfs

相關問題