
如何检查文件是否存在于远程服务器上
展开全部
在有些情况下,你要测试文件是否存在于远程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)
在本教程中,我将向您展示如何使用不同的脚本语言(如: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)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |