基本信息
源码名称:windows环境jar包部署到linux服务器,一键操作
源码大小:0.18M
文件格式:.zip
开发语言:C#
更新时间:2019-07-29
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 1 元 
   源码介绍

 windows系统下生成的jar包通过FTP上传到linux服务器,然后通过XShell进行jar包的发布,这样反复了几个月后,开发阶段需要频繁更新包的部署。个人觉得很繁琐,想一键式把这个工作做了,不想经常花时间发布。前几天去了解了下Docker Jenkins的方式,但是过于麻烦,对我个人学习时间和成本比较高。从而衍生出想用自己比较拿手的C#编写一个小工具解决我这个问题

using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Windows.Forms;

namespace Deploy
{
    public partial class DeployFrm : Form
    {
        public DeployFrm()
        {
            InitializeComponent();
            deployBus.TxtLog = this.txtLog;
        }

        public static DeployBusness deployBus = new DeployBusness();


        public Deploy GetDeploy()
        {
            DateTime dt = DateTime.Parse("2019-09-30");
            if (DateTime.Now > dt)
            {
                throw new Exception("请联系shexun进行版本更新");
            }
            var deploy = new Deploy(this.txtIP.Text, this.txtPort.Text, this.txtServerDirectory.Text, this.txtUserName.Text, this.txtPassword.Text, this.txtLocalFilePath.Text, this.txtServerFilePath.Text, "");
            return deploy;
        }


        public void LoadInfo()
        {
            var deploy = deployBus.ReadInfo();
            if (deploy != null)
            {
                this.txtIP.Text = deploy.Host;
                this.txtPort.Text = deploy.Port;
                this.txtServerDirectory.Text = deploy.ServerDirectory;
                this.txtUserName.Text = deploy.UserName;
                this.txtPassword.Text = deploy.Password;
                this.txtLocalFilePath.Text = deploy.LocalFilePath;
                this.txtServerFilePath.Text = deploy.ServerFilePath;

            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                deployBus.Upload(GetDeploy());
            }
            catch (Exception ex)
            {
                deployBus.ShowLog(ex.Message);
            }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                deployBus.Run(GetDeploy());
            }
            catch (Exception ex)
            {
                deployBus.ShowLog(ex.Message);
            }
        }

        private void btnSaveInfo_Click(object sender, EventArgs e)
        {
            try
            {
                deployBus.SaveInfo(GetDeploy());
            }
            catch (Exception ex)
            {
                deployBus.ShowLog(ex.Message);
            }
        }

        private void DeployFrm_Load(object sender, EventArgs e)
        {
            try
            {
                LoadInfo();
            }
            catch (Exception ex)
            {
                deployBus.ShowLog(ex.Message);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                deployBus.Stop(GetDeploy());
            }
            catch (Exception ex)
            {
                deployBus.ShowLog(ex.Message);
            }
        }

        private void btnBackUp_Click(object sender, EventArgs e)
        {
        }

        private void btnConnection_Click(object sender, EventArgs e)
        {
            try
            {
                deployBus.Connection(GetDeploy());
            }
            catch (Exception ex)
            {
                deployBus.ShowLog(ex.Message);
            }
        }
        /// <summary>
        /// 部署类
        /// </summary>
        [DataContract]
        public class Deploy
        {

            public Deploy(string Host, string Port, string ServerDirectory, string UserName, string Password, string LocalFilePath, string ServerFilePath, string Log)
            {
                this.Host = Host != null ? Host.Trim() : null;
                this.Port = Port != null ? Port.Trim() : null;
                this.ServerDirectory = ServerDirectory != null ? ServerDirectory.Trim() : null;
                this.UserName = UserName != null ? UserName.Trim() : null;
                this.Password = Password != null ? Password.Trim() : null;
                this.LocalFilePath = LocalFilePath != null ? LocalFilePath.Trim() : null;
                this.ServerFilePath = ServerFilePath != null ? ServerFilePath.Trim() : null;
                this.Log = Log != null ? Log.Trim() : null;
            }

            [DataMember]
            public string Host { get; set; }
            [DataMember]
            public string Port { get; set; }
            [DataMember]
            public string ServerDirectory { get; set; }
            [DataMember]
            public string UserName { get; set; }
            [DataMember]
            public string Password { get; set; }
            [DataMember]
            public string LocalFilePath { get; set; }
            [DataMember]
            public string ServerFilePath { get; set; }
            [DataMember]
            public string Log { get; set; }
        }

        public class DeployBusness
        {

            public TextBox TxtLog { get; set; }

            public emAction EmAction { get; set; }

            public enum emAction { ___, Connection, Upload, BackUp, Run, Stop, SaveInfo, ReadInfo, Download }
            public void ShowLog(string log)
            {
                string logStr = "";
                logStr = EmAction.ToString();
                var defaultNull = 10 - logStr.Length;
                if (defaultNull > 0)
                {
                    string temp = "";
                    for (int i = 0; i < defaultNull; i )
                    {
                        temp = " ";
                    }
                    logStr = temp;
                }
                logStr = " => [ " DateTime.Now.ToString() " ] ";
                logStr = log "。\r\n";
                if (this.TxtLog != null)
                {
                    TxtLog.Text = logStr;
                }
                EmAction = emAction.___;
            }

            public bool Connection(Deploy deploy)
            {
                this.EmAction = emAction.Connection;
                using (var client = new SftpClient(deploy.Host, int.Parse(deploy.Port), deploy.UserName, deploy.Password)) //创建连接对象
                {
                    client.Connect(); //连接
                    this.ShowLog("连接服务器成功");
                }
                return true;
            }

            public bool BackUp(Deploy deploy)
            {
                //对应的服务未停止不能进行上传

                this.EmAction = emAction.BackUp;
                using (var client = new SftpClient(deploy.Host, int.Parse(deploy.Port), deploy.UserName, deploy.Password)) //创建连接对象
                {
                    client.Connect(); //连接
                    var fileName = Path.GetFileName(deploy.ServerFilePath);
                    var changeDir = deploy.ServerFilePath.Replace(fileName, "");
                    client.ChangeDirectory(changeDir); //切换目录
                                                       //复制文件到新的文件目录


                    using (var fileStream = new FileStream(deploy.LocalFilePath, FileMode.Open))
                    {
                        this.ShowLog("正在上传文件,请稍等......");
                        client.BufferSize = 4 * 1024; // bypass Payload error large
                        client.UploadFile(fileStream, fileName); //上传文件
                        this.ShowLog("上传文件成功");
                    }
                }
                return true;
            }

            public bool Upload(Deploy deploy)
            {
                //对应的服务未停止不能进行上传

                this.EmAction = emAction.Upload;
                using (var client = new SftpClient(deploy.Host, int.Parse(deploy.Port), deploy.UserName, deploy.Password)) //创建连接对象
                {
                    client.Connect(); //连接
                    var fileName = Path.GetFileName(deploy.ServerFilePath);
                    var changeDir = deploy.ServerFilePath.Replace(fileName, "");
                    client.ChangeDirectory(changeDir); //切换目录
                    using (var fileStream = new FileStream(deploy.LocalFilePath, FileMode.Open))
                    {
                        this.ShowLog("正在上传文件,请稍等......");
                        client.BufferSize = 4 * 1024; // bypass Payload error large
                        client.UploadFile(fileStream, fileName); //上传文件
                        this.ShowLog("上传文件成功");
                    }
                }
                return true;
            }

            public void Run(Deploy deploy)
            {
                this.EmAction = emAction.Run;
                var con = new ConnectionInfo(deploy.Host, int.Parse(deploy.Port), deploy.UserName,
                    new AuthenticationMethod[]{
                // Pasword based Authentication
                new PasswordAuthenticationMethod(deploy.UserName,deploy.Password)
                    });
                // Execute (SHELL) Commands
                using (var sshclient = new SshClient(con))
                {
                    sshclient.Connect();
                    this.ShowLog("连接服务器成功");
                    var psResevice = sshclient.CreateCommand("ps -ef").Execute();
                    var runList = new List<string>();
                    string[] lines = psResevice.Split('\n'); //用\n表示换行符 注意是char类型 分割行
                    var fileName = Path.GetFileName(deploy.ServerFilePath);
                    foreach (var item in lines)
                    {
                        if (item.Contains(fileName))
                        {
                            runList.Add(item);
                            this.ShowLog("找到服务:" item);
                        }
                    }

                    foreach (var item in runList)
                    {
                        var temp = item.Substring(0, 15);
                        var pid = temp.Substring(4, 15 - 4).Trim();
                        //获取到PID
                        var msg = sshclient.CreateCommand("kill -9 " pid).Execute();
                        this.ShowLog("关闭服务PID:" pid);
                    }
                    //更新文件  成功后执行命令
                    var changeDir = deploy.ServerFilePath.Replace(fileName, "").TrimEnd('/');
                    var command = "nohup java -jar " fileName ">>m.out.log 2>&1 &";
                    var msg2 = sshclient.CreateCommand("cd " changeDir ";" command).Execute();
                    this.ShowLog("启动服务成功");
                }
            }

            public void Stop(Deploy deploy)
            {
                this.EmAction = emAction.Stop;
                var con = new ConnectionInfo(deploy.Host, int.Parse(deploy.Port), deploy.UserName,
                   new AuthenticationMethod[]{
                // Pasword based Authentication
                new PasswordAuthenticationMethod(deploy.UserName,deploy.Password)
                   });
                // Execute (SHELL) Commands
                using (var sshclient = new SshClient(con))
                {
                    sshclient.Connect();
                    var psResevice = sshclient.CreateCommand("ps -ef").Execute();
                    string[] lines = psResevice.Split('\n'); //用\n表示换行符 注意是char类型 分割行
                    var fileName = Path.GetFileName(deploy.ServerFilePath);
                    if (lines != null && lines.Length > 0)
                    {
                        this.ShowLog("存在" lines.Length.ToString() "个服务");
                    }
                    foreach (var item in lines)
                    {
                        if (item.Contains(fileName))
                        {
                            this.ShowLog("找到服务:" item);
                            var temp = item.Substring(0, 15);
                            var pid = temp.Substring(4, 15 - 4).Trim();
                            //获取到PID
                            var msg = sshclient.CreateCommand("kill -9 " pid).Execute();

                        }
                    }
                    psResevice = sshclient.CreateCommand("ps -ef").Execute();
                    lines = psResevice.Split('\n'); //用\n表示换行符 注意是char类型 分割行
                    var stopStatus = false;
                    foreach (var item in lines)
                    {
                        if (item.Contains(fileName))
                        {
                            stopStatus = true;
                        }
                    }
                    if (!stopStatus)
                    {
                        this.ShowLog("停止服务成功");
                    }

                }
            }

            /// <summary>
            /// 读取信息
            /// </summary>
            public Deploy ReadInfo()
            {
                this.EmAction = emAction.ReadInfo;
                string path = AppDomain.CurrentDomain.BaseDirectory @"Temp\Record\";
                var defaultFileName = "Info.txt";
                string fileFullPath = path defaultFileName;
                //加载对应的文件目录的所有文件
                if (File.Exists(fileFullPath))
                {
                    string info = File.ReadAllText(fileFullPath);
                    this.ShowLog("读取配置成功");
                    //反序列化
                    var deploy = MySerializer.JsonToObject<Deploy>(info);
                    return deploy;
                }

                return null;
            }

            /// <summary>
            /// 保存信息
            /// </summary>
            public void SaveInfo(Deploy deploy)
            {
                this.EmAction = emAction.SaveInfo;
                string path = AppDomain.CurrentDomain.BaseDirectory @"Temp\Record\";
                var fileFullPath = path "Info.txt";
                StreamWriter sw;
                if (File.Exists(fileFullPath))
                {
                    File.Delete(fileFullPath);
                }
                var info = MySerializer.ObjectToJson(deploy);
                sw = File.CreateText(fileFullPath);
                sw.WriteLine(info);
                sw.Close();
                this.ShowLog("保存配置成功");
            }



        }

        public class MySerializer
        {
            /// <summary>
            /// 将对象序列化为json字符串
            /// </summary>
            /// <typeparam name="T">类型</typeparam>
            /// <param name="t">实例</param>
            /// <returns>json字符串</returns>
            public static string ObjectToJson<T>(T t) where T : class
            {
                DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
                using (MemoryStream stream = new MemoryStream())
                {
                    formatter.WriteObject(stream, t);
                    string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                    return result;
                }
            }

            /// <summary>
            /// json字符串转成对象
            /// </summary>
            /// <typeparam name="T">类型</typeparam>
            /// <param name="json">json格式字符串</param>
            /// <returns>对象</returns>
            public static T JsonToObject<T>(string json) where T : class
            {
                DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
                using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
                {
                    T result = formatter.ReadObject(stream) as T;
                    return result;
                }
            }
        }
    }
}