一开始,我用securecrt软件远程ssh到服务器没有问题(服务器是别人的)(外网用户名、密码直接连,内网除了用户名、密码,还有一个短信验证码,然后才能连,连进去后有一个交互界面可以选择,我就想用c# asp.net写个网页ssh连到服务器在网页上做一个命令交互。
首先,我在网上下载Renci.SshNet这个库,在网上找各种代码,遇到的第一个问题是网上的代码要使用这个库,至少要.net framework4.0以上才行,花了我好多时间才明白。
using (var client = new SshClient(IP, PORT, USERNAME, PASSWORD))
{
//启动连接
client.Connect();
Response.Write(client.IsConnected);
SshCommand output = client.RunCommand(COMMAND);
TextBox1.Text = output.Result;
client.Disconnect();
}
以上是Renci.SshNet基本使用,但是我遇到了第二个问题,用这个代码可以外网无交互连到服务器,内网的验证码没法输,花了我好长时间,用下面的代码解决了验证码的输入,这是涉及到一个ssh的连接方式,有PASSWORD(密码连接),Interactive(交互连接,必须键盘输密码),PUBLICKEY(公钥连接),还有GSSAPI,这些连接方式是服务器端设定的,我连的服务器内网只允许Interactive(交互连接),对应下面的KeyboardInteractiveConnectionInfo
KeyboardInteractiveConnectionInfo connectionInfo = new KeyboardInteractiveConnectionInfo(IP, PORT, USERNAME);//连接前台服务器主机
connectionInfo.Timeout = TimeSpan.FromSeconds(240); //设置连接时长必须有
connectionInfo.AuthenticationPrompt += new EventHandler<Renci.SshNet.Common.AuthenticationPromptEventArgs>(delegate (object sender1, Renci.SshNet.Common.AuthenticationPromptEventArgs e2)
{
foreach (var prompt in e2.Prompts)
{
TextBox2.Text = prompt.Request;
if (prompt.Request.Equals("Password: ", StringComparison.InvariantCultureIgnoreCase))
{
prompt.Response = PASSWORD; //服务器端发“Password: ”,我这边回发密码
}
else if (prompt.Request.Equals(" input smsVerifyCode:", StringComparison.InvariantCultureIgnoreCase))
{
Session["imscode"] = ""; //Session["imscode"]保存的是验证码,在另一按钮输验证码事件中会被更改,一旦更改下面的循环会被打破
while (Session["imscode"].ToString() == "")
{
Thread.Sleep(1000);
}
prompt.Response = Session["imscode"].ToString();//回发验证码
}
}
});
SshClient client = new SshClient(connectionInfo);
client.Connect();
解决完验证码,又遇到了第三个问题,内网登录有一个交互界面,我始终无法获取交互界面,后来我看了一个博主的文章。https://b