使用scp2和ssh2在node环境打包发布

// 1、项目根目录新建deploy.js并添加配置,方式二选一
// 2、package.json修改build配置: "build": "vue-cli-service build && node ./deploy"
// 3、运行命令npm run build打包发布
// *、使用私钥时在根目录新建文件xxx.private,启用privateKey和passphrase

const scpClient = require('scp2')
const Client = require('ssh2').Client
const conn = new Client()

const server = {
  host: '8.8.8.8',
  port: '22',
  username: 'root',
  password: 'password',
  // privateKey: require("fs").readFileSync('xxx.private'),
  // passphrase: 'private_key_password',
  path: '/data/dist',
  command: 'rm -rf /data/dist/*'
}

// 方式一
scpClient.scp(
  './dist/',
  {
    host: server.host,
    port: server.port,
    username: server.username,
    password: server.password,
    // privateKey: server.privateKey,
    // passphrase: server.passphrase,
    path: server.path
  },
  (err) => {
    if (err) {
      console.log('faild')
      throw err
    } else {
      console.log('success')
    }
  }
)

// 方式二
conn.on('ready', () => {
  conn.exec(server.command, (err, stream) => {
    if (err) { throw err }
    stream.on('close', () => {
      scpClient.scp(
        './dist/',
        {
          host: server.host,
          port: server.port,
          username: server.username,
          password: server.password,
          // privateKey: server.privateKey,
          // passphrase: server.passphrase,
          path: server.path
        },
        (err) => {
          if (err) {
            console.log('faild')
            throw err
          } else {
            console.log('success')
          }
        }
      )
      conn.end()
    }).on('data', (data) => {
      console.log('STDOUT: ' + data)
    })
    .stderr.on('data', (data) => {
      console.log('STDERR: ' + data)
    })
  })
}).connect({
  host: server.host,
  port: server.port,
  username: server.username,
  password: server.password,
  // privateKey: server.privateKey,
  // passphrase: server.passphrase,
})
 

 

posted @ 2022-08-12 16:34  鱿鱼须须  阅读(332)  评论(0编辑  收藏  举报