簡體   English   中英

使用Python檢查遠程SSH服務器上的文件是否存在

[英]Checking a file existence on a remote SSH server using Python

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

print os.path.exists('ubuntu@serverB.com:b.jpeg')

即使我在服務器B上放了一個確切的文件,結果也會返回false。我不確定這是我的語法錯誤還是有更好的解決方案來解決這個問題。 謝謝

os.path函數僅適用於同一台計算機上的文件。 它們在路徑上運行,而ubuntu@serverB.com: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('ubuntu@serverB.com', 'b.jpeg'):
    # it exists...

請注意,這可能會非常慢,甚至可能超過100毫秒。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM