如果目录在登录sftp服务器后不存在,我想创建一个目录。
test.sh
sftp name@example.com << EOF
mkdir test
put test.xml
bye
EOF
现在我调用test.sh并每次上传不同的文件来测试文件夹。运行时
mkdir test
第一次工作,第二次抛出无法创建目录:失败错误?
如果目录不存在且如果存在则不在sftp中创建目录。
答案 0 :(得分:6)
我理解这个帖子已经过时了并且已被标记为已回答,但答案在我的情况下不起作用。关于“sftp检查目录”的搜索谷歌的第二页,所以这里是一个更新,可以节省我几个小时。
使用EOT无法捕获由于找不到目录而导致的错误代码。我发现的工作是创建一个包含调用指令的文件,然后捕获该自动调用的结果。
以下示例使用sshpass,但我的脚本也使用与sshkeys进行身份验证的相同方法。
创建包含说明的文件:
echo "cd $RemoteDir" > check4directory
cat check4directory; echo "bye" >> check4directory
设置权限:
chmod +x check4directory
然后使用批处理功能建立连接:
export SSHPAA=$remote_pass
sshpass -e sftp -v -oBatchMode=no -b check4directory $remote_user@$remote_addy
最后检查错误代码:
if [ $? -ge "1" ] ; then
echo -e "The remote directory was not found or the connection failed."
fi
此时您可以退出1或启动其他操作。请注意,如果SFTP连接因密码或地址错误等其他原因而失败,则错误将使操作失效。
答案 1 :(得分:3)
您可以使用帐户的SSH访问权限来首先验证目录是否存在(使用“test”命令)。如果它返回退出代码0,则dir存在,否则不存在。你可以据此采取行动。
# Both the command and the name of your directory are "test"
# To avoid confusion, I just put the directory in a separate variable
YOURDIR="test"
# Check if the folder exists remotely
ssh name@example.com "test -d $YOURDIR"
if [ $? -ne 0 ]; then
# Directory does not exist
sftp name@example.com << EOF
mkdir test
put test.xml
bye
EOF
else
# Directory already exists
sftp name@example.com << EOF
put test.xml
bye
EOF
fi
答案 2 :(得分:3)
另一种变体是将SFTP会话拆分为两个。
第一个SFTP会话只发出MKDIR命令。
然后,第二个SFTP会话可以假定存在目录并放置文件。
答案 3 :(得分:1)
man 1 sftp
(来自openssh-client
包):
-b batchfile
Batch mode reads a series of commands from an input
batchfile instead of stdin. Since it lacks user
interaction it should be used in conjunction with
non-interactive authentication. A batchfile of ‘-’
may be used to indicate standard input. sftp will
abort if any of the following commands fail: get,
put, reget, reput, rename, ln, rm, mkdir, chdir, ls,
lchdir, chmod, chown, chgrp, lpwd, df, symlink, and
lmkdir. Termination on error can be suppressed on a
command by command basis by prefixing the command
with a ‘-’ character (for example, -rm /tmp/blah*).
所以:
{
echo -mkdir dir1
echo -mkdir dir1/dir2
echo -mkdir dir1/dir2/dir3
} | sftp -b - $user@$host