bash 用于 ssh 到远程文件夹并检查所有文件的脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1662948/
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
A script to ssh into a remote folder and check all files?
提问by Vlad the Impala
I have a public/private key pair set up so I can ssh to a remote server without having to log in. I'm trying to write a shell script that will list all the folders in a particular directory on the remote server. My question is: how do I specify the remote location? Here's what I've got:
我设置了一个公钥/私钥对,因此我可以 ssh 到远程服务器而无需登录。我正在尝试编写一个 shell 脚本,该脚本将列出远程服务器上特定目录中的所有文件夹。我的问题是:如何指定远程位置?这是我所拥有的:
#!/bin/bash
for file in [email protected]:dir/*
do
if [ -d "$file" ]
then
echo $file;
fi
done
回答by Siddhartha Reddy
Try this:
尝试这个:
for file in `ssh [email protected] 'ls -d dir/*/'`
do
echo $file;
done
Or simply:
或者干脆:
ssh [email protected] 'ls -d dir/*/'
Explanation:
解释:
- The sshcommand accepts an optional command after the hostname and, if a command is provided, it executes that command on login instead of the login shell; ssh then simply passes on the stdout from the command as its own stdout. Here we are simply passing the lscommand.
- ls -d dir/*/ is a trick to make ls skip regular files and list out only the directories.
- 所述SSH命令主机名之后接受可选命令,并且如果提供了命令,则在登录而不是登录shell执行该命令; ssh 然后简单地将命令中的标准输出作为它自己的标准输出传递。这里我们只是简单地传递ls命令。
- ls -d dir/*/ 是一种让 ls 跳过常规文件并仅列出目录的技巧。

