using Renci.SshNet; using System; namespace Tiobon.Core.OPS.Tool.OPS.Tool.Helper { public class SSHHelper { #region 字段或属性 private SshClient ssh; /// /// 连接状态 /// public bool Connected { get { return ssh.IsConnected; } } /// /// 用户名称 /// public string user { set; get; } #endregion #region 构造 /// /// 构造 /// /// IP /// 端口 /// 用户名 /// 密码 public SSHHelper(string ip, string port, string user, string pwd) { ssh = new SshClient(ip, Int32.Parse(port), user, pwd); this.user = user; } #endregion #region 连接SSH /// /// 连接SSH /// /// true成功 public bool Connect() { try { if (!Connected) { ssh.ConnectionInfo.Timeout = TimeSpan.FromSeconds(15); ssh.Connect(); } return true; } catch (Exception ex) { string log = $"ssh连接失败:原因 {ex.Message}"; Const.write_log(log); return false; } } #endregion #region 断开SSH /// /// 断开SSH /// public bool Disconnect() { try { if (!Connected) { ssh.Disconnect(); } return true; } catch (Exception ex) { MessageBoxEx.Show(ex.Message); return false; } } #endregion #region 执行长命令 public bool Excute_Longcmd(string command, out string result, string taskinfo = "正在安装,请稍等...") { try { if (taskinfo != "正在安装,请稍等...") Const.write_log(taskinfo); var cmd = ssh.RunCommand(command); if (cmd.Error != "") { result = cmd.Error; return false; } result = cmd.Result; return true; } catch (Exception ex) { result = ex.Message; return false; } } #endregion #region 执行命令 public bool Excute_cmd(string command, out string result) { try { Connect(); var cmd = ssh.RunCommand(command); if (cmd.Error != "") { result = cmd.Error; return false; } Disconnect(); result = cmd.Result; return true; } catch (Exception ex) { result = ex.Message; return false; } } #endregion #region 执行命令,长连接 /// /// 执行命令,长连接(手动连接) /// /// /// public void Excute_Longcmd(string command) { try { using (var cmd = ssh.RunCommand(command)) { if (cmd.Error != "") { throw new Exception($"命令执行失败:{cmd.Error}"); } } } catch (Exception ex) { throw new Exception($"执行命令出错:{ex.Message}"); } } /// /// 执行命令,长连接(手动连接)--不提示报错 /// /// /// public void Excute_Longcmd_NoError(string command) { try { ssh.RunCommand(command); } catch (Exception ex) { throw new Exception($"执行命令出错:{ex.Message}"); } } #endregion } }