ssh2-sftp-client 上传文件至服务器

之前搞过一个前端自动化部署的东西:

前端 docker jenkins

这个玩意比较复杂,涉及到从git上拉代码,然后编译上传的过程。我们能不能直接本地打包后,不用xshell这种工具,直接上传到服务器呢?这就需要一个node插件:ssh2-sftp-client 。通过他我们可以使用node的sftp上传文件。

上传文件写在script文件夹下:

代码:

// script/sftp.json
{
    "zhixingyun_production": {
        "sftp": {
            "host": "10.10.10.10",
            "port": 22,
            "username": "xxx",
            "password": "xxx"
        },
        "pathConfig": {
            "remotePath": "/home/xiaochong/web/website/dist",
            "remoteBackupPath": "/home/xiaochong/web/website/dist_backup",
            "localPath": "./dist"
        }
    },
    "zhixingyun_test": {
        "sftp": {
            "host": "10.10.10.10",
            "port": 22,
            "username": "xxx",
            "password": "xxx"
        },
        "pathConfig": {
            "remotePath": "/home/xiaochong/web/test",
            "remoteBackupPath": "/home/xiaochong/web/test_backup",
            "localPath": "./test"
        }
    }
}
// script/upload.js
let Client = require('ssh2-sftp-client');
let client = new Client();
const config = require('./sftp.json')
const args = process.argv.slice(2)
const { sftp, pathConfig } = config[args[0]];

const main = async () => {
	try {
		await client.connect(sftp);
		//删除备份文件,如果有
		if (await client.exists(pathConfig.remoteBackupPath)) {
			await client.rmdir(pathConfig.remoteBackupPath, true)
			console.log('删除备份文件成功')
		}

		// 重命名之前的文件作为备份文件
		if (await client.exists(pathConfig.remotePath)) {
			await client.rename(pathConfig.remotePath, pathConfig.remoteBackupPath)
			console.log('新的备份文件重命名成功');
		}
		// 上传本地文件
		await client.uploadDir(pathConfig.localPath, pathConfig.remotePath);
		console.log('上传成功')
	} catch (err) {
		console.log(err);
	} finally {
		client.end();
	}
}

main();

  最后我们怎么执行upload呢,打包后用node执行即可:

//package.json
"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build &  node script/upload.js zhixingyun_production",
    "build:test": "vue-cli-service build --mode test &  node script/upload.js zhixingyun_test",
}

  注意点:sftp里的  localPath 写的是./ 因为npm run build执行时,dist文件夹在当前命令行的同级目录。

  这种上传方式是 SFTP,不是stp,用的账号密码是ssh的。


 

posted @ 2022-04-26 16:00  小虫1  阅读(1356)  评论(0编辑  收藏  举报