usingRenci.SshNet;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Runtime.Serialization;usingSystem.Runtime.Serialization.Json;usingSystem.Windows.Forms;namespaceDeploy
{public partial classDeployFrm : Form
{publicDeployFrm()
{
InitializeComponent();
deployBus.TxtLog= this.txtLog;
}public static DeployBusness deployBus = newDeployBusness();publicDeploy 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, "");returndeploy;
}public voidLoadInfo()
{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(objectsender, EventArgs e)
{try{
deployBus.Upload(GetDeploy());
}catch(Exception ex)
{
deployBus.ShowLog(ex.Message);
}
}private void btnRun_Click(objectsender, EventArgs e)
{try{
deployBus.Run(GetDeploy());
}catch(Exception ex)
{
deployBus.ShowLog(ex.Message);
}
}private void btnSaveInfo_Click(objectsender, EventArgs e)
{try{
deployBus.SaveInfo(GetDeploy());
}catch(Exception ex)
{
deployBus.ShowLog(ex.Message);
}
}private void DeployFrm_Load(objectsender, EventArgs e)
{try{
LoadInfo();
}catch(Exception ex)
{
deployBus.ShowLog(ex.Message);
}
}private void btnStop_Click(objectsender, EventArgs e)
{try{
deployBus.Stop(GetDeploy());
}catch(Exception ex)
{
deployBus.ShowLog(ex.Message);
}
}private void btnBackUp_Click(objectsender, EventArgs e)
{
}private void btnConnection_Click(objectsender, EventArgs e)
{try{
deployBus.Connection(GetDeploy());
}catch(Exception ex)
{
deployBus.ShowLog(ex.Message);
}
}///
///部署类///
[DataContract]public classDeploy
{public Deploy(string Host, string Port, string ServerDirectory, string UserName, string Password, string LocalFilePath, string ServerFilePath, stringLog)
{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 classDeployBusness
{public TextBox TxtLog { get; set; }public emAction EmAction { get; set; }public enumemAction { ___, Connection, Upload, BackUp, Run, Stop, SaveInfo, ReadInfo, Download }public void ShowLog(stringlog)
{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 + "。";if (this.TxtLog != null)
{
TxtLog.Text+=logStr;
}
EmAction=emAction.___;
}public boolConnection(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 boolBackUp(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 = newFileStream(deploy.LocalFilePath, FileMode.Open))
{this.ShowLog("正在上传文件,请稍等......");
client.BufferSize= 4 * 1024; //bypass Payload error large
client.UploadFile(fileStream, fileName); //上传文件
this.ShowLog("上传文件成功");
}
}return true;
}public boolUpload(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 = newFileStream(deploy.LocalFilePath, FileMode.Open))
{this.ShowLog("正在上传文件,请稍等......");
client.BufferSize= 4 * 1024; //bypass Payload error large
client.UploadFile(fileStream, fileName); //上传文件
this.ShowLog("上传文件成功");
}
}return true;
}public voidRun(Deploy deploy)
{this.EmAction =emAction.Run;var con = new ConnectionInfo(deploy.Host, int.Parse(deploy.Port), deploy.UserName,newAuthenticationMethod[]{//Pasword based Authentication
newPasswordAuthenticationMethod(deploy.UserName,deploy.Password)
});//Execute (SHELL) Commands
using (var sshclient = newSshClient(con))
{
sshclient.Connect();this.ShowLog("连接服务器成功");var psResevice = sshclient.CreateCommand("ps -ef").Execute();var runList = new List();string[] lines = psResevice.Split(''); //用
表示换行符 注意是char类型 分割行
var fileName =Path.GetFileName(deploy.ServerFilePath);foreach (var item inlines)
{if(item.Contains(fileName))
{
runList.Add(item);this.ShowLog("找到服务:" +item);
}
}foreach (var item inrunList)
{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 voidStop(Deploy deploy)
{this.EmAction =emAction.Stop;var con = new ConnectionInfo(deploy.Host, int.Parse(deploy.Port), deploy.UserName,newAuthenticationMethod[]{//Pasword based Authentication
newPasswordAuthenticationMethod(deploy.UserName,deploy.Password)
});//Execute (SHELL) Commands
using (var sshclient = newSshClient(con))
{
sshclient.Connect();var psResevice = sshclient.CreateCommand("ps -ef").Execute();string[] lines = psResevice.Split(''); //用
表示换行符 注意是char类型 分割行
var fileName =Path.GetFileName(deploy.ServerFilePath);if (lines != null && lines.Length > 0)
{this.ShowLog("存在" + lines.Length.ToString() + "个服务");
}foreach (var item inlines)
{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(''); //用
表示换行符 注意是char类型 分割行
var stopStatus = false;foreach (var item inlines)
{if(item.Contains(fileName))
{
stopStatus= true;
}
}if (!stopStatus)
{this.ShowLog("停止服务成功");
}
}
}///
///读取信息///
publicDeploy ReadInfo()
{this.EmAction =emAction.ReadInfo;string path = AppDomain.CurrentDomain.BaseDirectory + @"TempRecord";var defaultFileName = "Info.txt";string fileFullPath = path +defaultFileName;//加载对应的文件目录的所有文件
if(File.Exists(fileFullPath))
{string info =File.ReadAllText(fileFullPath);this.ShowLog("读取配置成功");//反序列化
var deploy = MySerializer.JsonToObject(info);returndeploy;
}return null;
}///
///保存信息///
public voidSaveInfo(Deploy deploy)
{this.EmAction =emAction.SaveInfo;string path = AppDomain.CurrentDomain.BaseDirectory + @"TempRecord";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 classMySerializer
{///
///将对象序列化为json字符串///
/// 类型
/// 实例
/// json字符串
public static string ObjectToJson(T t) where T : class{
DataContractJsonSerializer formatter= new DataContractJsonSerializer(typeof(T));using (MemoryStream stream = newMemoryStream())
{
formatter.WriteObject(stream, t);string result =System.Text.Encoding.UTF8.GetString(stream.ToArray());returnresult;
}
}///
///json字符串转成对象///
/// 类型
/// json格式字符串
/// 对象
public static T JsonToObject(string json) where T : class{
DataContractJsonSerializer formatter= new DataContractJsonSerializer(typeof(T));using (MemoryStream stream = newMemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
{
T result= formatter.ReadObject(stream) asT;returnresult;
}
}
}
}
}