Command FTP/SFTP (with/without password) to connect, download and upload

mac shell environment

The main instructions are to use expect to automatically enter the password form for access. The following is the a.sh script (the suffix must be .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"

 Let me explain separately what this more complicated line of code does;

# Create the directory tree under local/local to /remote/ on the SFTP specified host (use 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\""; }'`

It can be broken down into the following small pieces to explain roughly what to do one by one.

find /local/ -type d -exec ls -d {} \;

        Query all folder paths under the local/local/ path and output them to the {} cache

awk '{ gsub("/local/","/remote/",$1}; if($1=="")next;print "expect \"sftp>\"";print "send \"mkdir " $1"\r\""; }'`

        The awk instruction takes out the folder paths in the cache and performs the following operations one by one:

gsub("/local/","/remote/",$1};

        Replace the path with /remote/ for /local/ (replace all) and the result will be output to $1. That is, if gsub is a one-time replacement, it will definitely be output to the $1 variable.

if($1=="")next;

        If $1 is an empty string, skip this time directly, otherwise proceed as follows:

print "expect \"sftp>\"";

        Print the expect "sftp>" command and execute it in the sftp environment.

print "send \"mkdir " $1"\r\"";

        Print the send "mkdir $1 \r" command and execute it in the sftp environment.

 The method of executing a.sh is as follows

cd ~/Users
./a.sh

 FTP anonymous

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 non-anonymous [username] and [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 only enters 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

Guess you like

Origin blog.csdn.net/qq_39574690/article/details/133206796