Mac (shell expect) (sftp ssh) 前端部署到服务器

0 前置条件

Mac, 部署环境需要有 zip,unzip 指令

1 步骤

1.1 brew 安装 expect

1.2 编写 deploy.sh, 保存在项目根路径, ./bin/ 目录下

1.3 将文件变为可执行文件,

1.4 运行 deploy.sh 文件

2 具体实践

2.1 brew 安装 expect

一个能实现自动和交互式任务的解释器,它也能解释常见的shell语法命令

# https://www.cnblogs.com/zhenbianshu/p/5867440.html
brew search expect
brew install expect

2.2 编写 deploy.sh

# -eq   等于
# -ne   不等于
# -gt   大于
# -lt   小于
# -ge   大于等于
# -le   小于等于

## 判断前一个指令是否完成
# if [ $? -eq 0 ]; then
#      echo "succeed"
# else
#      echo "failed"
# fi

## 时间戳
# timestamp=`date +"%Y-%m-%d %H:%M:%S"`

## zip 打包当前目录下所有文件
# zip -q -r dist.zip *

## expect
# spawn 创建一个shell线程
# expect 匹配shell中命令行中的内容
# send 在该shell中发送 shell 命令
# interact 创建的shell线程交互权限 交还给用户

echo "==============================================================="
echo "1 编译 -- 开始("`date +"%Y-%m-%d %H:%M:%S)"`
npm run build

if [ $? -eq 0 ]; then
  echo "1 编译 -- 结束("`date +"%Y-%m-%d %H:%M:%S)"`
  echo "==============================================================="
fi

echo "==============================================================="
echo "2 打包 -- 开始"
cd dist
zip -q -r dist.zip *

if [ $? -eq 0 ]; then
  echo "2 打包 -- 结束"
  echo "==============================================================="
fi

echo "==============================================================="
echo "3 上传 -- 开始"
expect -c "
  spawn sftp root@@172.16.1.2
  expect {
    \"*password:*\" {
      set timeout 3;
      send \"123456\r\";
      exp_continue;
    }
  }
  expect \"sftp>\"
  send \"cd /usr/local/nginx/html\r\";
  expect \"sftp>\"
  send \"put dist.zip\r\";
  expect \"sftp>\"
  send \"exit\r\"
  interact
"

if [ $? -eq 0 ]; then
  echo "3 上传 -- 结束"
  echo "==============================================================="
fi

echo "==============================================================="
echo "4 解压 -- 开始"
expect -c "
  spawn ssh root@172.16.1.2
  expect {
    \"*password:*\" {
      set timeout 3;
      send \"123456\r\";
      exp_continue;
    }
  }
  expect \"ssh>\"
  send \"cd /usr/local/nginx/html\r\";
  expect \"ssh>\"
  send \"rm -rf css fonts img js && unzip -o dist.zip -d ./ \r\"
  expect \"ssh>\"
  send \"rm -rf dist.zip\r\"
  expect \"ssh>\"
  send \"ls\r\"
  expect \"ssh>\"
  send \"exit\r\"
  interact
"
if [ $? -eq 0 ]; then
  echo "4 解压 -- 结束"
  echo "==============================================================="
fi

2.3 变成可执行文件

# shell当前目录在项目根路径
>chmod +x ./bin/deploy.sh

2.4 运行可执行文件

# shell当前目录在项目根路径
>./bin/deploy.sh