using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SshClient sshClient = null;
private ShellStream shellStreamSSH = null;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//创建并且连接ssh客户端
this.sshClient = new SshClient("192.168.220.128", 22, "aidenxl", "123456");
this.sshClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(120);
this.sshClient.Connect();
//创建shellStream
this.shellStreamSSH= this.sshClient.CreateShellStream("admin", 80, 60, 800, 600, 65536);
//线程休眠100毫秒待连接
System.Threading.Thread.Sleep(100);
bool sshlive = shellStreamSSH.DataAvailable;
if (sshlive)
{
string result = shellStreamSSH.Read();
showbox.Text = result.ToString();
labelState.Text = "连接状态:已连接";
}
else
{
labelState.Text = "连接状态:未连接";
}
}
catch (Exception exp)
{
MessageBox.Show("ERROR:" + exp.Message);
}
}
private void entBtn_Click(object sender, EventArgs e)
{
if (shellStreamSSH != null&&inputTxtBox.Text!="")
{
shellStreamSSH.Write(inputTxtBox.Text.ToString()+ "\r");
shellStreamSSH.Flush();
System.Threading.Thread.Sleep(500);
if (shellStreamSSH.DataAvailable) { labelState.Text = "连接状态:已连接"; } else { labelState.Text = "连接状态:未连接"; };
string bb = shellStreamSSH.Read();
bb = bb.Replace("[01;34m", "");
bb = bb.Replace("[0m", "");
bb = bb.Replace("[01;31m", "");
showbox.Text = showbox.Text + bb.ToString();
inputTxtBox.Text = "";
}
else {
MessageBox.Show("还没有连接通上ssh或者文本为空");
}
}
private void showbox_TextChanged(object sender, EventArgs e)
{
showbox.SelectionStart = this.showbox.Text.Length;
showbox.SelectionLength = 0;
showbox.ScrollToCaret();
}
}
}