C#调用putty连接ssh服务器,附两种连接方式源码 您所在的位置:网站首页 putty源码分析 C#调用putty连接ssh服务器,附两种连接方式源码

C#调用putty连接ssh服务器,附两种连接方式源码

2024-07-17 02:18| 来源: 网络整理| 查看: 265

方法一:使用putty插件子程序plink.exe连接ssh

优点:稳定

缺点:有时plink.exe未退出,需要手动强制退出

 1.安装putty,测试版本是0.73,2019-09-29 PuTTY 0.73 released

官网下载

https://www.chiark.greenend.org.uk/~sgtatham/putty/

2.修改默认连接方式为SSH,然后保存到默认连接方式

3.调用下面代码即可实现ssh数据传输

using System; using System.Diagnostics; using System.IO; using System.Threading; using System.Windows.Forms; namespace TcpClientDemo { class PlinkSSh { public bool Connected = false; private SshConnectionInfo scInfo; public PlinkSSh(SshConnectionInfo scInfo) { this.scInfo = scInfo; for (int i = 0; i < 3; i++) { AddLine("SSH Connect>>" + (i + 1)); SSH(scInfo.Host, scInfo.User, scInfo.Pass); while (!TimeOut()) { if (ReadData.Contains("Using username")) { Connected = true; return; } } if (!Connected) Close(); } } public string ReadData = ""; DateTime dt = DateTime.Now; public bool TimeOut() { DateTime dt0 = DateTime.Now; if ((dt0 - dt).TotalMinutes > 0.4) { return true; } return false; } public void AddLine(string s) { scInfo.dr.Cells["col_Note"].Value = s; //Console.Write(scInfo.Host + ":" + s); } public void Close() { //try //{ // p.StandardInput.WriteLine("&exit"); //} //catch { } p.Close(); p.Dispose(); } public bool SendCmd(string cmd) { ReadData = ""; try { p.StandardInput.WriteLine(cmd); dt = DateTime.Now; return true; } catch { return false; } } //putty -ssh -l root -pw *** 192.168.0.101 //Plink.exe -l root -pw *** 192.168.0.101 //public void SSH(string ip = "192.168.0.101", string user = "root", string psw = "***") //{ // InitProcess(@"C:\Windows\System32\cmd.exe", "", null); // string path = Application.StartupPath + ""; // p.StandardInput.WriteLine(@"C:\Windows\plink.exe -l " + user + " -pw " + psw + " " + ip); //} public void SSH(string ip = "192.168.0.101", string user = "root", string psw = "***") { string path = Application.StartupPath + @"\plink.exe"; InitProcess(path, "-l " + user + " -pw " + psw + " " + ip, null); } private Process p = new Process(); private void InitProcess(string file, string args, string dir) { try { p.StartInfo.FileName = file; p.StartInfo.Arguments = args; if (!string.IsNullOrEmpty(dir)) { p.StartInfo.WorkingDirectory = dir; } p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //p.StartInfo.WindowStyle = ProcessWindowStyle.Normal; p.Start(); new Thread(GetStdErr).Start(); new Thread(GetStdOut).Start(); new Thread(SetStdIn).Start(); } catch (Exception e) { Console.Error.WriteLine("SetStdIn: " + e.Message); } } private void SetStdIn() { string line = ""; try { StreamReader reader = new StreamReader(Console.OpenStandardInput());// p.StandardOutput; while (!reader.EndOfStream) { line = reader.ReadLine(); p.StandardInput.WriteLine(line); } } catch (Exception e) { Console.Error.WriteLine("SetStdIn: " + e.Message); } } private void GetStdOut() { string line = ""; try { StreamReader reader = p.StandardOutput; while (!reader.EndOfStream) { line = reader.ReadLine(); Console.WriteLine(">>" + line); ReadData += line + "\r\n"; } } catch (Exception e) { Console.Error.WriteLine("GetStdOut: " + e.Message); } } private void GetStdErr() { string line = ""; try { StreamReader reader = p.StandardError; while (!reader.EndOfStream) { line = reader.ReadLine(); ReadData += line + "\r\n"; if (ReadData.Contains("press Return")) SendCmd("n"); Console.WriteLine("E>" + line); } } catch (Exception e) { Console.Error.WriteLine("GetStdErr: " + e.Message); } } } }

方法二:使用SSH协议库连接

PS:使用过程中出现无法接受消息的异常,程序在调试状态一直正常。

初步判断协议库有bug,未找到问题,故采用上面方法一替换了下面的代码块

using System; using System.IO; using System.Text; using System.Threading; using System.Windows.Forms; using Tamir.SharpSsh; namespace TcpClientDemo { public class SshConnectionInfo { public DataGridViewRow dr; public string Host { get; internal set; } public string IdentityFile { get; internal set; } public string Pass { get; internal set; } public string User { get; internal set; } } internal class sshHelper { public bool Connected = false; private SshShell ss = null; private Stream io = null; private SshConnectionInfo scInfo; private byte[] buffer; private int bufSize = 256; private AsyncCallback readCallback; private delegate void addLineDelegate(string s); public sshHelper(SshConnectionInfo scInfo) { this.scInfo = scInfo; try { ss = new SshShell(scInfo.Host, scInfo.User); if (scInfo.Pass != null) { ss.Password = scInfo.Pass; } if (scInfo.IdentityFile != null) { ss.AddIdentityFile(scInfo.IdentityFile); } AddLine("Connect:" + scInfo.Host); ss.Connect(22); Connected = true; io = ss.GetStream(); buffer = new byte[bufSize]; readCallback = new AsyncCallback(OnCompletedRead); io.BeginRead(buffer, 0, bufSize, readCallback, null); } catch (Exception ex) { Connected = false; AddLine("Terminated yet!" + ex.Message); } AddLine("Connect:" + (Connected ? "Pass" : "Failed")); Thread.Sleep(500); } public void Close() { try { if (ss.Connected) { io.Close(); ss.Close(); } } catch { } } public string ReadData = ""; //public string ReadTotal = ""; private void OnCompletedRead(IAsyncResult ar) { int bytesRead = io.EndRead(ar); if (bytesRead > 0) { String str = Encoding.UTF8.GetString(buffer, 0, bytesRead); AddLine(str); ReadData += str; //ReadTotal += str; //this.Invoke(new addLineDelegate(addLine), new object[] { str }); io.BeginRead(buffer, 0, bufSize, readCallback, null); } } public void AddLine(string s) { scInfo.dr.Cells["col_Note"].Value = s; //Console.Write(scInfo.Host + ":" + s); } DateTime dt = DateTime.Now; public bool TimeOut() { DateTime dt0 = DateTime.Now; if ((dt0 - dt).TotalMinutes > 0.4) { return true; } return false; } public bool SendCmd(string cmd) { ReadData = ""; try { AddLine("SendCmd:" + cmd); Thread.Sleep(100); StreamWriter sw = new StreamWriter(io); sw.Write(cmd + '\n'); sw.Flush(); Thread.Sleep(100); dt = DateTime.Now; return true; } catch (Exception ex) { Connected = false; AddLine("Terminated yet!" + ex.Message); } return false; } } }

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有