前端工程师通过nodejs链接linux,并上传代码进行半自动化更新,省去ssh+ftp的链接工具

栏目: Node.js · 发布时间: 5年前

内容简介:这几天,有一个临时项目,每次发布,都要我本地手动zip,上传fpt,然后shell unzip.搞得头大,不胜其烦。我是个懒人,这明显不是我的风格。

这几天,有一个临时项目,每次发布,都要我本地手动zip,上传fpt,然后shell unzip.

搞得头大,不胜其烦。

我是个懒人,这明显不是我的风格。

干脆nodejs写一个自动链接服务器,并上传文件,然后解压的操作吧。

/**
 * Created by jsoncode on 2019/4/25.
 */
var clientServer = require('./clientServer');
var ip = [
        '127.0.0.1'//server ip
    ];
var filename = 'test.zip';
var localPaht = './a/b/';
var serverPath = '/home/a/b/';
var newDirName = 'www';

var timestr = dateFormat('yyyy-MM-dd_HH.mm.ss');
var cmd = [
    `mkdir ${serverPath}${newDirName}`,
    `mv ${serverPath}${filename} ${serverPath}${newDirName}/`,
    `unzip ${serverPath}${newDirName}/${filename} -d ${serverPath}${newDirName}/`,
    `rm -f ${serverPath}${newDirName}/${filename}`,
    `mv ${serverPath}${newDirName} ${serverPath}${newDirName}-${timestr}`,
    `mv ${serverPath}${newDirName} ${serverPath}${newDirName}`,
];

var cmdIndex = 0;

new Promise(function (success,error) {
    console.log('开始上传')
    clientServer.putFiles(ip,filename, localPaht, serverPath,function (msg) {
        console.log(msg);
        success()
    })
})
.then(function () {
    loopCmd(0,true);
})

function loopCmd(index,indeep) {
    if (index>=cmd.length) {console.log('全部执行完毕');return;}
    var c = cmd[index];
    console.log(c);
    clientServer.cmdShell2(c,ip,function (result) {
        console.log(result);
        if (indeep) {
            index++;
            loopCmd(index,indeep);
        }
    })
}
function dateFormat(formatString,date){
    var date = date||new Date();
    var o = {
        Y: date.getFullYear(),
        M: date.getMonth() + 1,
        D: date.getDate(),
        H: date.getHours(),
        m: date.getMinutes(),
        S: date.getSeconds()
    };
    for (var i in o) {
        if (o.hasOwnProperty(i)) {
            if (o[i] < 10) {
                o[i] = '0' + o[i];
            }
        }
    }
    var formatString = formatString || 'yyyy/MM/dd HH:mm:ss';
    var reg = new RegExp('[Yy]+|M+|[Dd]+|[Hh]+|m+|[Ss]+', 'g');
    var regM = new RegExp('m');
    var regY = new RegExp('y', 'i');
    return formatString.replace(reg, function(v) {
        var old = v;
        if (regM.test(v)) {
            old = o.m;
        } else if (regY.test(v)) {
            var y = '' + o.Y;
            var le = y.length - (v.length == 1 ? 2 : v.length);
            old = y.substring(y.length, le)
        } else {
            var key = v.toUpperCase().substr(0, 1);
            old = o[key];
        }
        return old;
    });
}

以下是clientServer.js的代码,原作者kevalin,网上找的代码,忘了留原始链接。这里给作者说一声抱歉。

需要配置一个私钥路径,即可链接服务器了。

/**
 * Created by kevalin on 2015/4/27.
 */
var async = require('async');
var SSH2Utils = require('ssh2-utils');
var fs = require('fs');
var ssh = new SSH2Utils();
var privateKey = '../xxx.pem';

/*
exec linux shell on remote-servers
----------------------------------------------------------------------------------------------
 */
exports.cmdShell2 = function(cmd, ips, callback) {
    if(!cmd || !ips || !ips.length) {
        console.log('cmdShell2 ERR - 缺少参数')
    }
    else {
        var results = [];
        async.waterfall([
            function(cb1) {
                var servers = [];
                for(var i = 0; i < ips.length; i++) {
                    var _server = {};
                    _server['host'] = ips[i];
                    _server['username'] = 'root';
                    _server['privateKey'] = fs.readFileSync(privateKey);
                    servers.push(_server)
                }
                cb1(null, servers)
            },
            function(servers, cb1) {
                async.each(servers, function(server, cb2) {
                    var _result = {};
                    ssh.exec(server, cmd, function(err, stdout, stderr, server, conn) {
                        if (err) throw err;
                        _result['ip'] = server.host;
                        _result['cmdResult'] = stdout.replace('\n\n', '').replace('\n', '');
                        results.push(_result);
                        conn.end()
                        cb2()
                    })
                }, function(err) {
                    cb1(err, results)
                })
            }
        ], function(err, result) {
            if (err) throw err;
            callback(result)
        })
    }
}

/*
put file to remote-servers function
----------------------------------------------------------------------------------------------
 */
exports.putFiles = function(ips, filename, localPath, remotePath, callback) {
    if (!ips || !filename || !remotePath || !localPath) {
        console.log('putFiles ERR - 缺少参数')
    }
    else {
        async.waterfall([
            function(cb1) {
                var servers = [];
                for(var i = 0; i < ips.length; i++) {
                    var _server = {};
                    _server['host'] = ips[i];
                    _server['username'] = 'root';
                    _server['privateKey'] = fs.readFileSync(privateKey);
                    servers.push(_server)
                }
                cb1(null, servers)
            },
            function(servers, cb1) {
                async.each(servers, function(server, cb2) {
                    var _localFile = localPath + filename;
                    var _remoteFile = remotePath + filename;
                    ssh.putFile(server, _localFile, _remoteFile, function(err, server, conn) {
                        if (err) {
                            console.log(err)
                        }
                        conn.end();
                        cb2()
                    })
                }, function(err) {
                    cb1()
                })
            }
        ], function(err, result) {
            if (err) throw err;
            callback('put file success!!!')
        })
    }
}

我现在只需要吧代码打包成zip,就行了,然后执行:

node index.js

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Cascading Style Sheets 2.0 Programmer's Reference

Cascading Style Sheets 2.0 Programmer's Reference

Eric A. Meyer / McGraw-Hill Osborne Media / 2001-03-20 / USD 19.99

The most authoritative quick reference available for CSS programmers. This handy resource gives you programming essentials at your fingertips, including all the new tags and features in CSS 2.0. You'l......一起来看看 《Cascading Style Sheets 2.0 Programmer's Reference》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具