欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-07 19:18:33
这几天,有一个临时项目,每次发布,都要我本地手动zip,上传fpt,然后shell unzip.搞得头大,不胜其烦。我是个懒人,这明显不是我的风格。干脆nodejs写一个自动链接服...

这几天,有一个临时项目,每次发布,都要我本地手动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