在本教程中,我将向您展示如何使用不同的脚本语言(如: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)
两个方式:find命令或者shell脚本。
1、find命令
(1)find是linux下用于查找文件的通用方法。
(2)find语法: find [指定查找目录] [查找规则] [查找完后执行的action]
(3)例如:find /tmp -name wa* -type l ,是在/tmp下查找名为wa开头且类型为符号链接的文件。找到就表示存在。
2、shell脚本
(1)在进行文件的自动处理中常常需要自动判别,下面的脚本判断test.log是否存在,存在则显示文件存在,否则显示文件不存在。
(2)例子:编辑一个脚本判断文件是否存在。
vi t.sh
#!/bin/bash
if [ -e /temp/test.log ];then //这里是判断语句,-e表示进行比较结果为真则存在
echo "文件存在"
else
echo "文件不存在"
fi
保存退出
执行:
sh t.sh
你可以用os.path.isfile如果路径下是现有普通文件返回true。因此islink()和isflie()都可以来判断相同目录下是否有文件。
import os.path
os.path.isfile(fname)
在Python3.4之后pathlib模块提供了一种面向对象的方法用于判断文件是否存在:
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)