简体   繁体   English

Bash脚本:通过SSH遍历目录并将其下载到本地计算机

[英]Bash script: Looping through directories over SSH and downloading them to local machine

I'm trying to write a bash script that: 我正在尝试编写一个bash脚本:

  • Loops through all the directories in a folder over an SSH server 循环浏览SSH服务器上文件夹中的所有目录
  • Downloads a file (titled say, "foo") inside each of these folders to a local machine. 将每个文件夹中的文件(标题为“ foo”)下载到本地计算机。

At the moment, I have: 目前,我有:

ssh username@server "for dir in ~/directoryname/*; (... something here!); done"

I don't think I can use scp while I'm accessing the SSH server, however. 但是,我认为我无法在访问SSH服务器时使用scp。 Is there a way I can loop through and download everything here? 有没有一种方法可以循环浏览并在此处下载所有内容?

running scp remotely would work only if the remote server has access to your own system. 仅当远程服务器可以访问您自己的系统时,才能远程运行scp let's assume it doesn't. 让我们假设没有。

you could do it in two steps: 您可以分两步进行操作:

ssh username@server "... some script that just echos the paths ..." > log
for line in $(<log); do scp username@server:$line ./dir/$line; done

or you could investigate rsync which is extremely powerful. 或者您可以研究功能非常强大的rsync it has --include and --exclude options which would allow you to do something like: 它具有--include--exclude选项,使您可以执行以下操作:

rsync -av username@server:~/somepath/ ./somepath/ [--exclude/--include flags]

Yeah, that script is an argument passed to ssh, and is run on the remote machine, which means you can't easily reference your own machine in order to tell it where to copy the files to. 是的,该脚本是传递给ssh的参数,并且在远程计算机上运行,​​这意味着您不能轻易引用自己的计算机来告诉它要将文件复制到何处。

You could try a bash script that runs locally to fetch the directory structure you're searching, and use scp to copy over any that you're interested in retrieving. 您可以尝试在本地运行的bash脚本来获取要搜索的目录结构,并使用scp复制任何您想要检索的内容。

Or, depending on the sizes involved, scp over all of directoryname/ , and get what you want from there. 或者,根据涉及的大小,遍历所有directoryname/ ,然后从中获取所需内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM