如果登录到sftp服务器后它不存在,我想创建一个目录.
test.sh
sftp name@example.com << EOF
mkdir test
put test.xml
bye
EOF
Run Code Online (Sandbox Code Playgroud)
现在我调用test.sh并每次上传不同的文件来测试文件夹.在运行时
mkdir test
Run Code Online (Sandbox Code Playgroud)
第一次它工作,第二次它抛出无法创建目录:失败错误?
如果目录不存在且如果存在则不创建目录在sftp中如何创建目录.
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*).
Run Code Online (Sandbox Code Playgroud)
所以:
{
echo -mkdir dir1
echo -mkdir dir1/dir2
echo -mkdir dir1/dir2/dir3
} | sftp -b - $user@$host
Run Code Online (Sandbox Code Playgroud)
小智 6
我知道此线程较旧,并且已被标记为已回答,但在我的情况下,该答案无效。谷歌第二页上有关“ sftp检查目录”的搜索,因此这是一个更新,可以节省我几个小时。
使用EOT,您无法捕获由于找不到目录而导致的错误代码。我发现的解决方法是创建一个包含有关呼叫说明的文件,然后捕获该自动呼叫的结果。
下面的示例使用sshpass,但是我的脚本也使用与sshkeys身份验证相同的方法。
创建包含说明的文件:
echo "cd $RemoteDir" > check4directory
cat check4directory; echo "bye" >> check4directory
Run Code Online (Sandbox Code Playgroud)
设置权限:
chmod +x check4directory
Run Code Online (Sandbox Code Playgroud)
然后使用批处理功能进行连接:
export SSHPAA=$remote_pass
sshpass -e sftp -v -oBatchMode=no -b check4directory $remote_user@$remote_addy
Run Code Online (Sandbox Code Playgroud)
最后检查错误代码:
if [ $? -ge "1" ] ; then
echo -e "The remote directory was not found or the connection failed."
fi
Run Code Online (Sandbox Code Playgroud)
此时,您可以退出1或启动其他操作。请注意,如果SFTP连接由于其他原因(例如密码)或地址不正确而失败,则该错误将触发操作。
您可以使用您帐户的 SSH 访问权限首先验证该目录是否存在(使用“test”命令)。如果它返回退出代码 0,则该目录存在,否则不存在。您可以据此采取行动。
# 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
Run Code Online (Sandbox Code Playgroud)