如果打印ok,則表示存在
import paramiko
client=paramiko.SSHClient()
client.load_system_host_keys()
client.connect("10.10.0.0",username="service",password="word")
_,stdout,_=client.exec_command("[ -f /opt/ad/bin/email_tidyup.sh ] && echo OK")
print(stdout.read())
client.close()
在有些情況下,你要測試文件是否存在於遠程Linux服務器的某個目錄下(例如:/var/run/test_daemon.pid),而無需登錄到遠程服務器進行交互。例如,你可能希望你的腳本根據特定文件是否存在的遠程服務器上而由不同的行爲。
在本教程中,我將向您展示如何使用不同的腳本語言(如:Bash shell,Perl,Python)查看遠程文件是否存在。
這裏描述的方法將使用ssh訪問遠程主機。您首先需要啓用無密碼的ssh登錄到遠程主機,這樣您的腳本可以在非交互式的批處理模式訪問遠程主機。您還需要確保ssh登錄文件有讀權限檢查。假設你已經完成了這兩個步驟,您可以編寫腳本就像下面的例子
使用bash判斷文件是否存在於遠程服務器上
#!/bin/bash
ssh_host="xmodulo@remote_server"
file="/var/run/test.pid"
if ssh $ssh_host test -e $file;
then echo $file exists
else echo $file does not exist
fi
使用perl判斷文件是否存在於遠程服務器上
#!/usr/bin/perl
my $ssh_host = "xmodulo@remote_server";
my $file = "/var/run/test.pid";
system "ssh", $ssh_host, "test", "-e", $file;
my $rc = $? >> 8;
if ($rc) {
print "$file doesn't exist\n";
} else {
print "$file exists\n";
}
使用python判斷文件是否存在於遠程服務器上
#!/usr/bin/python
import subprocess
import pipes
ssh_host = 'xmodulo@remote_server'
file = '/var/run/test.pid'
resp = subprocess.call(
['ssh', ssh_host, 'test -e ' + pipes.quote(file)])
if resp == 0:
print ('%s exists' % file)
else:
print ('%s does not exist' % file)