我知道这个问题已经被问了很多,但我似乎找不到一个好的开始方式。
我一直在使用 sharpssh,但它是为控制台应用程序制作的。因此,当我尝试创建一个 winforms 应用程序时,我无法让它按我想要的方式运行。
在我的表单中,我有: 显示输出的文本框 用户应在其中写入命令的文本框。
我卡在了 readline() 上,我需要暂停应用程序,直到用户按下回车键,然后发送插入到文本框中的命令。我不知道如何将应用程序转换为 winform 应用程序。
那么问题是如何解决这个问题? - 我是否应该使用一个在初始化应用程序时启动的进程,以及一个在收到输出和需要输入时启动的进程?并使用第二个进程收集输入,监听在文本框中按下的事件输入键,并启动另一个进程发送输入并再次等待输出?
如果有的话,有没有关于如何解决的例子?
这是代码?
public Form1()
{
InitializeComponent();
txthost.Text = "XXX";
txtuser.Text = "XXXXX";
txtpass.Text = "XXXXX";
string pattern = "sdf:";
mPattern = pattern;
this.txtInput.KeyPress += new System.Windows.Forms.KeyPressEventHandler(checkforenter);
}
public void button1_Click(object sender, EventArgs e)
{
try
{
mShell = new SshShell(Host, User);
mShell.Password = Pass;
//WRITING USER MESSAGE
txtOutput.AppendText("Connecting...");
mShell.Connect();
txtOutput.AppendText("OK");
//txtOutput.AppendText("Enter a pattern to expect in response [e.g. '#', '$', C:\\\\.*>, etc...]: ");
//Stop for user input
mShell.ExpectPattern = mPattern;
mShell.RemoveTerminalEmulationCharacters = true;
_writer = new TextBoxStreamWriter(txtOutput);
Console.SetOut(_writer);
StringReader reader = new StringReader(txtInput.Text);
while (mShell.ShellOpened)
{
txtOutput.AppendText("\r\n" + "TERMINAL MODE ENGAGED");
txtOutput.AppendText(mShell.Expect( pattern ));
txtInput.Text = Console.ReadLine();
Console.ReadLine();
Console.WriteLine(Environment.NewLine);
txtOutput.AppendText(mShell.Expect(pattern));
MessageBox.Show("innan enter 2");
Console.WriteLine(Environment.NewLine);
txtOutput.AppendText(mShell.Expect(("(continue)")));
MessageBox.Show("efter enter 2");
Console.WriteLine(Environment.NewLine);
//Data from termninal --> Append to text
string output = mShell.Expect(Pattern);
txtOutput.AppendText(output);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
最佳答案
根据 Codeproject 上的 SharpSSH 文章 (http://www.codeproject.com/Articles/11966/sharpSsh-A-Secure-Shell-SSH-library-for-NET),有两种方法供您阅读和写入 SSH 连接:
//Writing to the SSH channel
ssh.Write( command );
//Reading from the SSH channel
string response = ssh.ReadResponse();
您的文本框成为您的控制台,因此您不再需要使用 Console 对象。您需要检测何时按下 Enter 键。按下时,执行 Write 命令并将最后输入的内容发送到 SSH 连接中。然后执行 ReadResponse,这将暂停应用程序并等待响应。返回后,您可以将结果字符串附加到文本框。
您可能会担心检测用户输入的内容并将其发送到 SSH 连接。您可以做的是每次执行 ReadResponse 时,在文本框中获取字符索引,然后在他们按 Enter 后将其用于字符所在的位置。
或者您可以只使用两个文本框,一个用于输入,一个用于输出。
希望这对您有所帮助!
关于C# - SSH Winforms 模拟控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10667561/