实例介绍
【实例简介】
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;
}
}
}
}
}
标签: linux部署
网友评论
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
支持(0) 盖楼(回复)