有時候因為服務器不能實現github或者gitlab的自動部署服務,所以就需要使用腳本來實現自動部署,可以省時省力,一勞永逸。這里就使用ssh2-sftp-client和ssh2來實現,即便是需要sudo權限,也是可以的。
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和管道將密碼傳遞給sudossh.exec(`echo '${sudoPassword}' | sudo -S mv ${remoteTempPath} ${remoteTargetPath}`,(err, stream) => {if (err) throw errstream.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 emptyconsole.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