从终端进行 SFTP 下载正常,但通过脚本无法正常工作

从终端进行 SFTP 下载正常,但通过脚本无法正常工作

我正在编写一个备份脚本,它将下载以主机名 fe MikroTik 开头的所有备份,该主机名包含在变量设备中。当我将命令放入终端时,它将下载我需要的所有文件,但是当我将其放入脚本时,它会显示消息文件 Mikrotik 未找到。

这是代码示例:

#!/bin/bash
user="admin"
address="IP"
#command will get devcie hostname in complex form 
ssh $user@$address '/system identity print interval=' > devices

#will get device hostname
tmpDevices=$(cat devices)

device=$(echo $tmpDevices | awk ' {print $2} ')
echo "Device hostname is $device"

echo "Connecting to device via SFTP and downloading files"
#sftp "${user}@${address}:/${device}*"
sftp $user@$address:$device* 

这是输出:

Device hostname is MikroTik
MikroTik
Connecting to device via SFTP and downloading files
Connected to 10.120.0.253.
File "/MikroTik" not found.

你能给我建议吗?

阿德里安。

答案1

您可以考虑使用 scp 而不是 sftp。假设要将文件从远程主机的根目录复制到本地主机的当前目录:

scp "${user}@${address}:/${device}*" . 

例如,我在远程主机上创建了以下文件:

$ ssh user@remoteHost "ls /MikroTik*"
/MikroTik_dec07backup.backup
/MikroTik_dec07export.rsc
/MikroTik_dec07log.txt

从我的本地主机,我可以执行以下操作:

$ mkdir /tmp/example
$ cd /tmp/example
$ scp "user@remoteHost:/MikroTik*" .
MikroTik_dec07backup.backup                   100%    0     0.0KB/s   00:00
MikroTik_dec07export.rsc                      100%    0     0.0KB/s   00:00
MikroTik_dec07log.txt                         100%    0     0.0KB/s   00:00
$ ls
MikroTik_dec07backup.backup  MikroTik_dec07export.rsc  MikroTik_dec07log.txt
$

答案2

adrian@adrian-ThinkPad-X230:~/Desktop/zaloha$ sftp admin@IP:/MikroTik*
Connected to IP.
Fetching /MikroTik_dec07backup.backup to MikroTik_dec07backup.backup
/MikroTik_dec07backup.backup                                                                                                                                                  100%   10KB  10.5KB/s   00:00    
Fetching /MikroTik_dec07export.rsc to MikroTik_dec07export.rsc
/MikroTik_dec07export.rsc                                                                                                                                                     100%  329     0.3KB/s   00:00    
Fetching /MikroTik_dec07log.txt to MikroTik_dec07log.txt
/MikroTik_dec07log.txt                                                                                                                                                        100%   75KB  75.1KB/s   00:00 

当我使用离子脚本时:

#!/bin/bash
user="admin"
address="IP"
#command will get devcie hostname in complex form 
ssh $user@$address '/system identity print interval=' > devices

#will get device hostname
tmpDevices=$(cat devices)

device=$(echo $tmpDevices | awk ' {print $2} ')
echo "Device hostname is $device"

echo "Connecting to device via SFTP and downloading files"
#sftp "${user}@${address}:/${device}*"
sftp $user@$address:$device* 

输出是:

Connecting to device via SFTP and downloading files
Connected to address.
File "/MikroTik" not found.

相关内容