通过 SFTP 将文件列表保存到文本文件

Lep*_*tor 4 sftp rsync shell-script

我在下面提供了我自己的答案。

我们有许多使用 SFTP 可以正常工作的 bash 脚本,我想要做的是简单地将文件夹的 ls 或 dir 重定向到我们 SFTP 服务器上的文件。

我们可以将其作为cron 作业运行,也可以手动运行。我可以查看来自远程服务器的文件列表,但我想以文本文件的形式生成从远程服务器到本地服务器的文件列表。 .

到目前为止,这是我对 bash 脚本所拥有的内容。下面列出的第四个回声是有问题的行。

#!/bin/bash

localpath=/home/localacct/somepath
remotelocation=/home/account/logs/archive
remotehost=' account@1.1.1.1'

    echo  > $localpath/list.sftp
    echo "cd $remotelocation " >> $localpath/list.sftp
    echo "dir *.* " >> $localpath/list.sftp
    echo "dir *.* > $localpath/dirlist.txt " >> $localpath/list.sftp
    echo "bye " >> $localpath/list.sftp
    sftp -b $localpath/list.sftp $remotehost

exit
Run Code Online (Sandbox Code Playgroud)

小智 6

这是迄今为止效果最好的:

echo 'ls' | sftp hostname
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式将输出转发到文件中

echo 'ls' | sftp hostname > /tmp/mylist.txt
Run Code Online (Sandbox Code Playgroud)

  • 每行返回一个文件应该会使输出更容易处理:`echo 'ls -1a' | sftp 主机名` (4认同)

Gil*_*il' 5

sftp命令是非常有限的。如果你不能让它做你想做的,你可以使用另一种方法,即使用SSHFS文件系统挂载远程目录。SSHFS 使用 SFTP 作为传输协议,所以服务器端只看到一个 SFTP 客户端。您需要能够在客户端使用FUSE

使用 SSHFS,您可以将远程目录挂载到现有的空目录并使用普通命令。

mkdir remote
sshfs "$remotehost:$remotelocation" remote
cd remote

echo *.* >"$localpath/dirlist.txt"

fusermount -u remote
rmdir remote
Run Code Online (Sandbox Code Playgroud)


Lep*_*tor 0

我最终使用了另一种方法。尝试使用 rsync。

我们发现以下内容:

  • 如果您未指定本地目标,则会提供远程服务器上指定文件的列表。

BASH 脚本则变为:

#!/bin/bash
localpath=/home/local-acct/path
remotelocation=/home/account/logs/archive
remotehost=' account@1.2.3.4'
rsync -avz $remotehost:/$remotelocation > $localpath/dirlist.txt
exit
Run Code Online (Sandbox Code Playgroud)

并且效果很好!

  • 请注意,“rsync”使用“ssh”(因此假设远程用户具有 shell 访问权限),而不是“sftp”(ssh 的子系统,不需要用户具有 shell 访问权限),并假设“rsync”安装在远程计算机上。所以你不妨执行 `ssh user@host ls /dir > file` (2认同)