Linux 使用 ssh 检查远程主机上是否存在文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12845206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:35:05  来源:igfitidea点击:

check if file exists on remote host with ssh

linuxbashshellssh

提问by stdcerr

I would like to check if a certain file exists on the remote host. I tried this:

我想检查远程主机上是否存在某个文件。我试过这个:

$ if [ ssh user@localhost -p 19999 -e /home/user/Dropbox/path/Research_and_Development/Puffer_and_Traps/Repeaters_Network/UBC_LOGS/log1349544129.tar.bz2 ] then echo "okidoke"; else "not okay!" fi
-sh: syntax error: unexpected "else" (expecting "then") 

采纳答案by Florin Stingaciu

Here is a simple approach:

这是一个简单的方法:

#!/bin/bash
USE_IP='-o StrictHostKeyChecking=no [email protected]'

FILE_NAME=/home/user/file.txt

SSH_PASS='sshpass -p password-for-remote-machine'

if $SSH_PASS ssh $USE_IP stat $FILE_NAME \> /dev/null 2\>\&1
            then
                    echo "File exists"
            else
                    echo "File does not exist"

fi

You need to install sshpasson your machine to work it.

您需要在您的机器上安装sshpass才能使用它。

回答by Mat

You're missing ;s. The general syntax if you put it all in one line would be:

你缺少;s。如果将所有内容放在一行中,则一般语法是:

if thing ; then ... ; else ... ; fi

The thingcan be pretty much anything that returns an exit code. The thenbranch is taken if that thingreturns 0, the elsebranch otherwise.

thing可几乎任何返回退出代码。该then如果分支被采用thing返回0,该else分支除外。

[isn't syntax, it's the testprogram (check out ls /bin/[, it actually exists, man testfor the docs – although can also have a built-in version with different/additional features.) which is used to test various common conditions on files and variables. (Note that [[on the other hand issyntax and is handled by your shell, if it supports it).

[不是语法,而是test程序(检查ls /bin/[,它实际上存在,man test对于文档 - 尽管也可以具有具有不同/附加功能的内置版本。)用于测试文件和变量的各种常见条件。(请注意,[[另一方面语法并由您的 shell 处理,如果它支持的话)。

For your case, you don't want to use testdirectly, you want to test something on the remote host. So try something like:

对于您的情况,您不想test直接使用,而是想在远程主机上测试某些内容。所以尝试这样的事情:

if ssh user@host test -e "$file" ; then ... ; else ... ; fi

回答by JP Lew

In addition to the answers above, there's the shorthand way to do it:

除了上面的答案之外,还有一种速记方法:

ssh -q $HOST [[ -f $FILE_PATH ]] && echo "File exists" || echo "File does not exist";

-qis quiet mode, it will suppress warnings and messages.

-q是安静模式,它将抑制警告和消息。

As @Mat mentioned, one advantage of testing like this is that you can easily swap out the -ffor any test operator you like: -nt, -d, -setc...

作为@Mat提到,测试这样的一个好处是,你可以很容易地换出-f任何测试操作你喜欢:-nt-d-s等...

Test Operators:http://tldp.org/LDP/abs/html/fto.html

测试运营商:http : //tldp.org/LDP/abs/html/fto.html

回答by None

ssh -q $HOST [[ -f $FILE_PATH ]] && echo "File exists"

The above will run the echo command on the machine you're running the ssh command from. To get the remote server to run the command:

以上将在您运行 ssh 命令的机器上运行 echo 命令。要让远程服务器运行命令:

ssh -q $HOST "[[ ! -f $FILE_PATH ]] && touch $FILE_PATH"

回答by tarok

You can specify the shell to be used by the remote host locally.

您可以在本地指定远程主机要使用的 shell。

echo 'echo "Bash version: ${BASH_VERSION}"' | ssh -q localhost bash

And be careful to (single-)quote the variables you wish to be expanded by the remote host; otherwise variable expansion will be done by your local shell!

并小心(单)引用您希望由远程主机扩展的变量;否则变量扩展将由您的本地 shell 完成!

# example for local / remote variable expansion
{
echo "[[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive'" | 
    ssh -q localhost bash
echo '[[ $- == *i* ]] && echo "Interactive" || echo "Not interactive"' | 
    ssh -q localhost bash
}

So, to check if a certain file exists on the remote host you can do the following:

因此,要检查远程主机上是否存在某个文件,您可以执行以下操作:

host='localhost'  # localhost as test case
file='~/.bash_history'
if `echo 'test -f '"${file}"' && exit 0 || exit 1' | ssh -q "${host}" sh`; then
#if `echo '[[ -f '"${file}"' ]] && exit 0 || exit 1' | ssh -q "${host}" bash`; then
   echo exists
else
   echo does not exist
fi

回答by karni

Can't get much simpler than this :)

没有比这更简单的了:)

ssh host "test -e /path/to/file"
if [ $? -eq 0 ]; then
    # your file exists
fi

As suggested by dimo414, this can be collapsed to:

按照 dimo414 的建议,这可以折叠为:

if ssh host "test -e /path/to/file"; then
    # your file exists
fi

回答by estani

one line, proper quoting

一行,正确引用

ssh remote_host test -f "/path/to/file" && echo found || echo not found

回答by miguialberto

I wanted also to check if a remote file exist but with RSH. I have tried the previous solutions but they didn't work with RSH.

我还想检查远程文件是否存在但带有 RSH。我已经尝试过以前的解决方案,但它们不适用于 RSH。

Finally, I did I short function which works fine:

最后,我做了我的简短功能,效果很好:

function existRemoteFile ()
{
REMOTE=
FILE=
RESULT=$(rsh -l user $REMOTE  "test -e $FILE && echo \"0\" || echo \"1\"")
if [ $RESULT -eq 0 ]
then
    return 0
else
    return 1
fi
}

回答by Abhimanu Kumar

On CentOS machine, the oneliner bash that worked for me was:

在 CentOS 机器上,对我有用的 oneliner bash 是:

if ssh <servername> "stat <filename> > /dev/null 2>&1"; then echo "file exists"; else echo "file doesnt exits"; fi

It needed I/O redirection (as the top answer) as well as quotes around the command to be run on remote.

它需要 I/O 重定向(作为最佳答案)以及要在远程运行的命令周围的引号。

回答by rouble

Test if a file exists:

测试文件是否存在:

HOST="example.com"
FILE="/path/to/file"

if ssh $HOST "test -e $FILE"; then
    echo "File exists."
else
    echo "File does not exist."
fi

And the opposite, test if a file does not exist:

相反,测试文件是否不存在:

HOST="example.com"
FILE="/path/to/file"

if ! ssh $HOST "test -e $FILE"; then
    echo "File does not exist."
else
    echo "File exists."
fi