nuget上安装SSH.NET,封装类如下
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SSH
{
public class MySSH
{
SshClient ssh = null;
ShellStream sh;
StreamReader reader;
public MySSH(string host, string username, string password, int port = 22)
{
ssh = new SshClient(host, port, username, password);
}
public bool Connect()
{
try
{
ssh.Connect();
sh = ssh.CreateShellStream("MySSH", 80, 40, 8000, 4000, 1024);
reader = new StreamReader(sh, Encoding.GetEncoding("gb2312"));
}
catch (Exception ex)
{
return false;
}
return ssh.IsConnected;
}
public bool IsConnect
{
get { return ssh.IsConnected; }
}
/// <summary>
/// 执行命令,返回得到的结果
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public string Exec(string input)
{
return ssh.RunCommand(input).Execute();
}
/// <summary>
/// 执行命令,返回得到的结果GBK
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public string ExecGBK(string input)
{
return ssh.CreateCommand(input, Encoding.GetEncoding("gb2312")).Execute();
}
/// <summary>
/// ShellStream互动后,返回的结果,可以自定义结束字符
/// </summary>
/// <param name="input"></param>
/// <param name="endstr"></param>
/// <returns></returns>
public string ExecSh(string input, List<string> endstr = null)
{
sh.WriteLine(input);
return ReadToEnd(endstr);
}
public string ReadToEnd(List<string> endstr = null)
{
string result = "";
for (int i = 0; i < 30; i++)
{
Thread.Sleep(100);
result += reader.ReadToEnd();
if(IsMatch(result, endstr)) break;
}
return result;
}
private bool IsMatch(string output, List<string> endstr = null)
{
if (endstr == null)
{
endstr = new List<string>() { "]#", "]$", "]?", "]%", "#]" };
}
foreach (string item in endstr)
{
if (output.TrimEnd().EndsWith(item)) return true;
}
return false;
}
//public string SendCommand(string cmd)
//{
// //StreamReader reader = null;
// //try
// //{
// // reader = new StreamReader(sh);
// // if (sh.Length > 0) reader.ReadToEnd();
// // StreamWriter writer = new StreamWriter(sh);
// // writer.AutoFlush = true;
// // writer.WriteLine(cmd);
// // while (sh.Length == 0)
// // {
// // Thread.Sleep(500);
// // }
// //}
// //catch (Exception ex)
// //{
// // Console.WriteLine("exception: " + ex.ToString());
// //}
// //return reader.ReadToEnd();
//}
~MySSH()
{
reader?.Close();
sh?.Dispose();
ssh?.Dispose();
}
}
}
使用方法
MySSH ssh = new MySSH(ip, 用户名, 密码);
ssh.Connect();
// 读取回话内容
txtLog.Text = ssh.ReadToEnd();
// 切换root
txtLog.Text += ssh.ExecSh("su -", new List<string>() { ":" });
txtLog.Text += ssh.ExecSh("111111");
// 直接执行命令,返回结果
txtLog.Text += ssh.Exec("ps -ef|grep mysql");