你的位置:首页 > ASP.net教程

[ASP.net教程].Net使用SSH.NET通过SSH访问Linux主机


使用了SSH.NET库,添加引用dll至项目,以下代码显示了点击按钮后SSH链接Linux主机执行命令并返回命令执行结果 

 1 protected void btnExcute_Click(object sender, EventArgs e) 2 { 3   string server = ServerAddr.Text; 4   string username = UserName.Text; 5   string password = Password.Text; 6   string command = Command.Text; 7  8   StringBuilder result = new StringBuilder(); 9   try10   {11     using (var client = new SshClient(server, username, password))12     {13       try14       {15         client.Connect();16         result.Append(client.RunCommand(command).Execute() + "\r\n");17         QAResult.Text = result.ToString();18         client.Disconnect();19       }20       catch (Exception e1)21       {22         result.Append(e1.Message + "\r\n");23       }24     }25   }26   catch (Exception e1)27   {28     result.Append(e1.Message + "\r\n");29     QAResult.Text = result.ToString();30   }31 }

 

以下代码演示了从本机拷贝文件到Linux主机

 1 private void TestTranferFiles() 2 { 3   string server = ServerAddr.Text; 4   string username = UserName.Text; 5   string password = Password.Text; 6   string command = Command.Text; 7   var scp = new ScpClient(server, username, password); 8   scp.Connect(); 9   scp.Upload(new DirectoryInfo(@"d:\aaaa"), "/home/zy"); //将d:\\aaaa下的所有文件上传10   scp.Disconnect();11 }