前端项目部署——告别可视化工具,拥抱脚本

514 阅读1分钟

目前市面上有很多例如Jenkins这样优秀的一键部署工具,无奈公司的前端部署还处于刀耕火种时代(sftp可视化工具对文件进行上传、删除)。

今天刚好有时间,简单学习了下shell脚本相关东西,搞了个脚本来一键部署项目。

废话不多说,直入主题

1. 上传文件

uploadFile.sh文件

#!/bin/bash

ip="服务器ip"
password="服务器密码"
local_dir="项目所在目录的绝对路径" #eg: /Users/geekchen/Desktop/juejin/
remote_dir="要上传到服务器的绝对路径" #/web/juejin/
opt_type="dir" #dir or file 上传的类型:整个目录或文件

chmod +x command.sh # 这句是为了给command.sh添加可执行的权限

./command.sh ${local_dir} root ${ip} ${remote_dir} ${password} ${opt_type} # 传递参数 注:这里默认是root身份,如果是其他身份,请修改上述第二个参数

command.sh文件

#!/usr/bin/expect 

if {$argc < 2} {
    send_user "usage: $argv0 src_file username host_ip dest_file password\n"
    exit
}

set src_file [lindex $argv 0] # 接收参数 下同
set username [lindex $argv 1]
set host_ip [lindex $argv 2]
set dest_file [lindex $argv 3]
set password [lindex $argv 4]
set opt_type [lindex $argv 5]
set timeout 60

if { "$opt_type" == "dir" } { 
    spawn scp -r $src_file $username@$host_ip:$dest_file #使用scp协议进行上传
    expect {
        "Connection refused" exit
        "continue connecting" {send "yes\r";exp_continue}
        "password:" {send "$password\r";exp_continue}
        eof
    }
} elseif { "$opt_type" == "file" } {
    spawn scp $src_file $username@$host_ip:$dest_file #使用scp协议进行上传
    expect {
        "Connection refused" exit
        "continue connecting" {send "yes\r";exp_continue}
        "password:" {send "$password\r";exp_continue}
        eof
    }
}
exit

食用方法: 开箱即食

将上述两个脚本放在同一目录下,在当前目录下打开终端,输入

sh upload_file.sh

静待上传完成即可




2. 删除文件

delete_file.sh文件

#!/bin/bash

ip="服务器ip"
password="服务器密码"
file_delete="要删除的远程服务器上的文件夹路径" #/web/juejin/

chmod +x command.sh # 这句是为了给command.sh添加可执行的权限

./command.sh root ${ip} ${password} ${file_delete}# 传递参数 注:这里默认是root身份,如果是其他身份,请修改上述第一个参数

if [ $? -ne 0 ]; then
    echo "./command.sh root ${ip} ${password} error!"
    exit 1
fi

exit 0

command.sh文件

#!/usr/bin/expect  

if {$argc < 2} {
    send_user "usage: $argv0 username host_ip password\n"
    exit
}

set username [lindex $argv 0]
set host_ip [lindex $argv 1]
set password [lindex $argv 2]
set file_delete [lindex $argv 3]
set timeout 15

spawn ssh $username@$host_ip
expect {
    "Connection refused" exit
    "continue connecting" {send "yes\r";exp_continue}
    "password:" {send "$password\r";exp_continue}
    eof
}

expect "#"
send "rm -rf ${file_delete}\r" 
expect eof
exit

食用方法: 开箱即食

将上述两个脚本放在同一目录下,在当前目录下打开终端,输入

sh delete_file.sh

静待删除完成即可


注:有堡垒机的情况不确定是否可用。

第一次写博客,欢迎一起学习,提issue,一起merge新功能。😝