mac shell环境
主要说明使用expect自动输入密码形式访问,以下是a.sh脚本(后缀必须是.sh)
- #!/bin/bash
-
- echo "SFTP 连接"
-
- # SFTP默认端口22 FTP默认端口21 (注意以下所有参数必须是字符串"")
- Port="22"
- User="UserName"
- Host="127.0.0.1"
- Pass="123456"
-
- # 将本地/local下的目录树创建到SFTP指定主机的/remote/下(利用find awk gsub进行)
- createFolder = `find /local/ -type d -exec ls -d {} \; | awk '{ gsub("/local/","/remote/",$1}; if($1=="")next;print "expect \"sftp>\"";print "send \"mkdir " $1"\r\""; }'`
-
- /usr/bin/expect <<FLAGEOF
- spawn sftp -P ${Port} ${User}@${Host}
- expect "password:"
- send ${Pass}\r
- expect "sftp>"
- send "put /local/a.txt /remote/a.txt\r"
- expect "sftp>"
- send "get /remote/a.txt /local/a.txt\r"
- $createFolder
- expect "sftp>"
- send "bye\r"
- FLAGEOF
-
- echo "结束 SFTP"
单独解释下这一行复杂点的代码做了什么事情;
# 将本地/local下的目录树创建到SFTP指定主机的/remote/下(利用find awk gsub进行)
createFolder = `find /local/ -type d -exec ls -d {} \; | awk '{ gsub("/local/","/remote/",$1}; if($1=="")next;print "expect \"sftp>\"";print "send \"mkdir " $1"\r\""; }'`可拆解如下几个小块,逐一说明大概做的事情
find /local/ -type d -exec ls -d {} \;
查询出本地/local/路径下的全部文件夹路径输出到{}缓存
awk '{ gsub("/local/","/remote/",$1}; if($1=="")next;print "expect \"sftp>\"";print "send \"mkdir " $1"\r\""; }'`
awk指令取出缓存里的文件夹路径逐个进行如下操作:
gsub("/local/","/remote/",$1};
将路径使用/remote/替换/local/(全部替换)结果会输出到$1,即gsub是一次性替换则一定会输出到$1变量
if($1=="")next;
如果$1是空字符串则直接跳过这一次,否则进入如下:
print "expect \"sftp>\"";
打印输出expect "sftp>"指令到sftp环境下执行
print "send \"mkdir " $1"\r\"";
打印输出send "mkdir $1 \r"指令到sftp环境下执行
执行a.sh方法如下
- cd ~/Users
- ./a.sh
FTP匿名
- ftip -nv $Host <<EOF
- user anonymous \r
- type binary
- prompt
- put /local/a.txt /remote/a.txt
- get /remote/b.txt /local/b.txt
- bye
- EOF
FTP非匿名[username]和[password]
- ftip -nv $Host <<EOF
- user yourUserName yourPassword
- type binary
- prompt
- put /local/a.txt /remote/a.txt
- get /remote/b.txt /local/b.txt
- bye
- EOF
FTP仅输入password情况
- ftip -nv $Host <<EOF
- pass yourPassword
- type binary
- prompt
- put /local/a.txt /remote/a.txt
- get /remote/b.txt /local/b.txt
- bye
- EOF