在bash脚本中使用lftp传输文件

8
我有一个名为test-lx的A服务器和一个名为test2-lx的B服务器,我想从A服务器传输文件到B服务器。在传输文件的同时,我需要创建目录,但只有在该目录不存在时才需要创建。如何在lftp连接期间检查目录是否存在?如何使用一条命令同时输出多个文件,而不是分开两行进行操作?是否可以使用find -maxdepth 1 -name DirName选项?
以下是我的代码:
lftp -u drop-up,1Q2w3e4R   ftp://ta1bbn01:21 << EOF

cd $desFolder
mkdir test
cd test
put $srcFil
put $srcFile

bye 
EOF
3个回答

26

使用ftp的简单方法:

#!/bin/bash

ftp -inv ip << EOF
user username password

cd /home/xxx/xxx/what/you/want/
put what_you_want_to_upload

bye
EOF

使用lftp:

#!/bin/bash

lftp -u username,password ip << EOF

cd /home/xxx/xxx/what/you/want/
put what_you_want_to_upload

bye
EOF

来自 lftp 手册:

-u <user>[,<pass>]  use the user/password for authentication

你可以使用 mkdir 命令来创建一个目录。而且你可以像这样多次使用 put 命令:
put what_you_want_to_upload
put what_you_want_to_upload2
put what_you_want_to_upload3

你可以使用bye来关闭连接。


你可以像这样检查文件夹是否存在:

#!/bin/bash
checkfolder=$(lftp -c "open -u user,pass ip; ls /home/test1/test1231")

if [ "$checkfolder" == "" ];
then
echo "folder does not exist"
else
echo "folder exist"
fi

来自 lftp 手册:

-c <cmd>            execute the commands and exit

你可以打开另一个连接以上传一些文件。


我不知道如何在一个连接中检查文件夹是否存在,但是我可以像这样做。也许你能找到更好的解决方案:

#!/bin/bash
checkfolder=$(lftp -c "open -u user,pass ip; ls /home/test1/test2")

if [ "$checkfolder" == "" ];
then

lftp -u user,pass ip << EOF

mkdir test2
cd test2
put testfile.txt
bye
EOF

else

echo "The directory already exists - exiting"

fi

如果我在终端中运行它,它可以工作,但是在bash脚本中,它无法工作。 它建立了连接,但没有执行putcd命令。 这是我用来建立连接的命令: lftp -u myUser,myPass ftp://ta1bbn01:21 SwDrop\Repository sleep 5 cd $desFolder sleep 5 put $srcFile bye - Alex Brodov
1
你不能使用if,因为它不是ftp命令。只有在打开ftp连接后才能使用ftp命令。你可以通过另一个连接来检查文件夹是否存在。请问你想要什么,能否编辑你的问题进行解释? - onur
1
命令 ls 即使目录不存在也会返回一个字符串。 这是我得到的字符串:550 /MSP-3.0.0.0: 没有那个文件或目录 - Alex Brodov
2
我找到了一种让 find 命令工作的方法。 find -d 1 DirToSearch - Alex Brodov
当您使用lftp命令时,“cd”指的是远程目录,而不是本地目录。您必须使用“!cd”来切换到本地目录。 - Tristan
显示剩余3条评论

1

我使用了与phe相同的基本编码大纲,但是我发现如果文件夹为空,则使用ls /foldername将输出“文件夹不存在”。为了解决这个问题,我使用

#!/bin/bash
checkfolder=$(lftp -c "open -u user,pass ip; ls | grep /test1231")

if [ "$checkfolder" == "" ];
then
echo "folder does not exist"
else
echo "folder exists"
fi

请注意,此方法仅适用于文件夹位于根目录的情况。对于文件夹中的子目录,请使用以下方法。
#!/bin/bash
checkfolder=$(lftp -c "open -u user,pass ip; find | grep home/test1/test1231")

if [ "$checkfolder" == "" ];
then
echo "folder does not exist"
else
echo "folder exists"
fi

0

首先将凭据记录准备好,存储到 ~/.netrc 文件中:

machine site-url-here
login user-login-here
password user-password-here

这样你就不必在命令行上暴露密码来在脚本中使用它。

然后调用:

lftp -e "lftp-command-here" ftps://user-login-here@site-url-here/initial-folder-here/`

在我的情况下,我运行mget -c * lftp命令,从在Azure基础设施上运行的Linux应用实例中获取Java Spring Boot应用程序的所有日志。当然,您可以在那里使用分号分隔您的命令。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接