Node交互式的SFTP上传实现过程剖析

 

背景

由于业务的原因,我们日常的测试环境,都是通过脚本,将本地打包的代码,进行SFTP上传到对应的测试机目录的(这个业务在测试环境没有CI/CD)。

最近由于安全问题,测试机的权限被收紧了,需要进行交互式的SFTP(即上传时需要用到令牌做二次校验)。

 

存在问题

此项目用的 ssh2-sftp-client 作为SFTP上传插件,主要是通过自定义的webpack-plugin,在构建完之后进行SFTP上传。

因为原来的stfp配置,是不支持交互式SFTP的,导致运维修改安全策略后,我们无法通过构建命令直接上传测试机,只能通过SFTP工具进行拖拽上传,相当影响工作效率

 

查阅资料

通过ssh2-sftp-client的文档,发现是没有交互式相关的配置的。而ssh2-sftp-client是基于ssh2的,通过查阅ssh2的文档,发现是支持type:keyboard-interactive(交互式链接的类型)的。

然后就发现有ssh2-sftp-client 存在以下issue:

Whether to support keyboard-interactive parameters

作者描述:

You can add any event listener you want with the on() method, so you should be able to setup keyboard interaction listeners that will gather the information. You will also need to set the tryKeyboard property to true in the connect config object.

意思就是,因为插件是base ssh2 的,我们可以用ssh2对象的事件监听,然后我们在配置链接时,也可以通过配置来进行链接配置。

 

最后的实现

我们将上传拆分成三个步骤

  • 安全令牌询问
  • 交互式校验监听
  • 创建交互式类型链接
//引用 ssh2-sftp-client库
const Client = require('ssh2-sftp-client')
// 第一步询问令牌
const { interactivePassword } = await inquirerList.interactivePassword()
  if (!interactivePassword) {
    throw new Error('请输入校验令牌')
  }
let sftp = new Client()
// 交互式校验监听
sftp.on('keyboard-interactive', function(
name,
instructions,
instructionsLang,
prompts,
finish
) {
finish([interactivePassword]) //将第一步的令牌填入
})
//创建交互式类型链接
await sftp.connect({
type: 'keyboard-interactive', //设置类型
tryKeyboard: true,
host: 'xxxxx',
port: 'xxxxx',
username: 'xxxxx',
password: 'xxxxx',
})

 

总结

通过上述代码,就能够通过node实现交互式的SFTP功能

参考文献

ssh2-sftp-client issue#327

ssh2的github仓库

以上就是Node交互式的SFTP上传实现过程剖析的详细内容,更多关于Node交互式SFTP上传的资料请关注编程宝库其它相关文章!

 在vue.config.js配置推荐方法1:const Timestamp = new Date().getTime()module.exports = { . ...