mac本地执行shell脚本远程连接sftp服务器上传/下载文件

sftp服务器下载

#!/usr/bin/expect

#需要修改的参数  fileName通过下面的sql查询
#SELECT policyNo+'_'+fileseq+'.zip' FROM dbo.T_PDFFILEJOB where policyNo='X116583A01';
set policyNo X116583A01

#定义变量
set sftpDir /apps/mal/WAS90/MALAppSrv2/tempPDF/
set unzipDir /home/kappa01/pdffile
set port 22
set user kappa01
set host 10.137.30.25
set password uatweb12


spawn ssh -p $port $user@$host
expect "*assword:*"
send "$password\r"
#目前已经连接到了SIT服务器
#当找到"~>"这个字符时继续执行后续命令,使用send来保证在当前服务器输入操作
#expect -re "~>"
#expect "*Last login*"
#send "ls\r"
expect -re "~>"
#通过SIT服务器连接到UAT的服务器
send "sftp -P $port [email protected]\r"
expect "*Enter passphrase for key*"
send "\r"
expect "*assword:*"
send "$password\r"
#目前为止已经连接到了UAT服务器

#打开zip文件所在路径
expect -re "sftp>" 
send "cd /\r"

expect -re "sftp>" 
send "cd $sftpDir \r"

#通过get命令下载zip文件
expect -re "sftp>" 
set timeout -1
send "get $policyNo*.zip $unzipDir \r"

expect -re "sftp>" 
send "quit \r"

#下载完zip包后进行解压并删除原来的zip包
expect -re "~>"
send "cd pdffile \r"

expect -re "/pdffile>"
send "unzip $policyNo*.zip \r"

expect -re "/pdffile>"
send "rm -rf $policyNo*.zip \r"

expect -re "/pdffile>"
send "cd .. \r"

expect -re "~>"
send "./putFile.sh $policyNo \r"

#以下命令保证脚本不会中断
interact

sftp服务器批量上传

#!/bin/bash
echo $1
#接收传递的参数
policyNo=$1

#SFTP配置信息
#IP
IP=10.137.30.25
#端口
PORT=22
#用户名
USER=kappa01
#密码
PASSWORD=uatweb12
#待上传文件根目录
SRCDIR=/Users/aiait/Desktop/pdffile
#SFTP目录
DESDIR=/mnt/ipos2/app/2021-11
#获取文件
cd /;
cd ${SRCDIR};
#目录下的所有文件
#FILES=`ls` 
#修改时间在执行时间五分钟之前的xml文件 根据实际情况删除 -mmin -50
echo "start get files"
FILES='find ${SRCDIR} -mmin -50 -name *.pdf'
for FILE in ${FILES}
do
    echo ${FILE}
echo "end get files"
#发送文件 (关键部分)
/usr/bin/expect <<-EOF
spawn sftp $USER@$IP
#expect "*Enter passphrase for key '/home/kappa01/.ssh/id_rsa':" 
#send "\r"

expect {
"*yes/no*" { send "yes\r"; exp_continue }
"*assword:" { send "$PASSWORD\r" }
}

expect "sftp>" 
send "cd /\r"

expect "sftp>" 
send "cd $DESDIR\r"

expect "sftp>" 
send "mkdir $policyNo\r"

expect "sftp>"
send "cd $policyNo\r"

expect "sftp>"
set timeout -1
send "put $FILE \r"

expect "sftp>" 
send "quit \r"

expect eof
EOF

done

#删除已经上传完的pdf
cd /
cd ${SRCDIR};
rm -rf *.pdf
echo "delete file success"

你可能感兴趣的:(shell,服务器,ssh,运维)