ssh2-sftp-client和ssh2配合使用js脚本快速部署项目到服务器

81 阅读1分钟

有时候因为服务器不能实现github或者gitlab的自动部署服务,所以就需要使用脚本来实现自动部署,可以省时省力,一劳永逸。这里就使用ssh2-sftp-client和ssh2来实现,即便是需要sudo权限,也是可以的。

ssh2-sftp-client开源地址:github.com/theophilusx…

安装依赖:

pnpm install ssh2-sftp-client


pnpm install ssh2

安装fs-extra用于管理文件和文件夹:

npm install fs-extra

1.先将本地打包后的目录上传到服务器

2.然后将上传后的文件夹使用sudo命令移动到指定位置

const Client = require('ssh2-sftp-client')
const { Client: SSHClient } = require('ssh2')

const sftp = new Client()
const ssh = new SSHClient()

const localFolderPath = './dist/build/h5' // 本地文件夹路径
const remoteTempPath = '/home/songjj/h5I18n' // 远程临时路径
const remoteTargetPath = '/var/www' // 远程目标路径
const sudoPassword = 'sudo密码'

const sftpConfig = {
    host: '服务器地址',
    port: 22,
    username: '账号',
    password: '密码',
}

// 连接到 SFTP 服务器
sftp.connect(sftpConfig)
    .then(() => {
        console.log('Connected to server. start uploading...')
        // 上传文件夹到服务器
        return sftp.uploadDir(localFolderPath, remoteTempPath)
    })
    .then((res) => {
        console.log('Upload complete.', res)
        // 将h5文件夹内容拷贝到/var/www/h5I18n/
        ssh.on('ready', () => {
            console.log('SSH 连接成功')
            // 执行sudo命令,并使用echo和管道将密码传递给sudo
            ssh.exec(
                `echo '${sudoPassword}' | sudo -S mv ${remoteTempPath} ${remoteTargetPath}`,
                (err, stream) => {
                    if (err) throw err
                    stream
                        .on('close', (code, signal) => {
                            console.log(
                                `命令执行完成: ${code}, 信号: ${signal}`
                            )
                            ssh.end()
                        })
                        .on('data', (data) => {
                            console.log('输出:', data.toString())
                        })
                        .stderr.on('data', (data) => {
                            // 错误输出: mv: cannot move '/home/songjj/h5I18n' to '/var/www/h5I18n': Directory not empty
                            console.error('错误输出:', data.toString())
                        })
                }
            )
        }).connect(sftpConfig)
    })
    .catch((err) => {
        console.error(`Upload error: ${err.message}`)
    })
    .finally(async () => {
        console.log('Disconnected from server.')
        await sftp.end()
    })

然后保存文件为deploy.cjs

然后使用node运行这个脚本就可以了:

node deploy.cjs