最新消息:阿啰哈,本人90后,目前单身,欢迎妹子们来撩!.(。→‿←。)

如何检查远程服务器的文件是否存在

Shell 林志斌 1000浏览

There are circumstances where you want to test if a file exists somewhere on a remote Linux server (e.g., /var/run/test_daemon.pid), without logging in to the server interactively. For example, you may want your script to behave differently depending on whether or not a specific file exists on a remote server.
In this tutorial, I will show you how to check if a remote file exists in different script languages (e.g., Bash shell, Perl, Python).
The approach described here will use ssh to access a remote host. You first need to enable password-less ssh login to the remote host, so that your script can access a remote host in non-interactive batch mode. You also need to make sure that ssh login has read permission on the file to check. Assuming that you have finished these two steps, you can write scripts like the following examples.
关键:在本地执行了远程服务器上的一条命令:

ssh -p222 [email protected] "test -e /root/123"

Check if a file exists on a remote server in Bash

#!/bin/bash
ssh_host="[email protected]_server"
file="/var/run/test.pid"
 
ifssh$ssh_hosttest-e $file;
    thenecho$fileexists
    elseecho$filedoes not exist
fi

Check if a file exists on a remote server in Perl

#!/usr/bin/perl
my$ssh_host="[email protected]_server";
my$file="/var/run/test.pid";
 
system"ssh",$ssh_host,"test","-e",$file;
my$rc= $? >> 8;
if($rc) {
    print"$file doesn't existn";
}else{
    print"$file existsn";
}

Check if a file exists on a remote server in Python

#!/usr/bin/python
importsubprocess
importpipes
 
ssh_host='[email protected]_server'
file='/var/run/test.pid'
 
resp=subprocess.call(
    ['ssh', ssh_host,'test -e '+pipes.quote(file)])
 
ifresp==0:
    print('%s exists'%file)
else:
    print('%s does not exist'%file)

via: http://xmodulo.com/how-to-check-if-file-exists-on-remote-server.html

转载请注明:林志斌 » 如何检查远程服务器的文件是否存在

发表评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址