C# 利用开源项目SharpSsh远程执行linux的shell命令源码

SharpSSH是一个C#的开源项目,可以利用SSH连接linux系统。并执行shell等命令
 
项目中提供的例子的输入输出都是定向到console的。。所以只能用户输入命令然后返回结果,但我们想从C#中获取它的结果却不容易。
 
所以后面我会简单改一下源码。。就可以获取返回结果了。
 
要执行ssh,请确保linux主机上的服务已启用:service sshd start
 
 首先看下提供的例子代码和执行结果。。就不多说了,,后面有源码下载:
 
引用工程:SharpSSH
 
C# 代码

  1. static void Main(string[] args)  
  2. {  
  3. try  
  4. {  
  5. //Create a new JSch instance  
  6. JSch jsch = new JSch();  
  7.  
  8. //Prompt for username and server host  
  9. Console.WriteLine("Please input hostname:");  
  10. String host = Console.ReadLine();  
  11. Console.WriteLine("Please input username:");  
  12. String user = Console.ReadLine();  
  13. Console.WriteLine("Please input password:");  
  14. String pwd = Console.ReadLine();  
  15.  
  16. //Create a new SSH session  
  17. Session session = jsch.getSession(user, host, 22);  
  18.  
  19. // username and password will be given via UserInfo interface.  
  20. UserInfo ui = new ShellUserInfo();  
  21. ui.setPassword(pwd);  
  22. session.setUserInfo(ui);  
  23.  
  24. //Connect to remote SSH server  
  25. session.connect();  
  26.  
  27. //Open a new Shell channel on the SSH session  
  28. Channel channel = session.openChannel("shell");  
  29.  
  30. //Redirect standard I/O to the SSH channel  
  31. channel.setInputStream(Console.OpenStandardInput());  
  32. channel.setOutputStream(Console.OpenStandardOutput());  
  33.  
  34. //Connect the channel  
  35. channel.connect();  
  36.  
  37. Console.WriteLine("-- Shell channel is connected using the {0} cipher",  
  38. session.getCipher());  
  39.  
  40. //Wait till channel is closed  
  41. while (!channel.isClosed())  
  42. {  
  43. System.Threading.Thread.Sleep(500);  
  44. }  
  45.  
  46. //Disconnect from remote server  
  47. channel.disconnect();  
  48. session.disconnect();  
  49.  
  50. }  
  51. catch (Exception e)  
  52. {  
  53. Console.WriteLine(e);  
  54. }  
  55. }  

 
 
这个就不多说了。。把输入输出定向到console。我们无法直接从代码中获取输出,只能从界面上显示
 
 
下面我们小小改一个东西 。。就可以获取代码了
 
打开sharpssh中的SshStream.cs
 
在里面加一个方法
 
折叠展开C# 代码

  1. public void set_OutputStream(Stream stream)  
  2. {  
  3. m_channel.setOutputStream( stream);  
  4. }  

做用就是我们可以把输出定向到一个指定的stream中
 
虽然它提供的例子中也可以这样做。但还是得不到想要的效果,,不知道有没有人试出来过
 
然后我们封装一个类:
 

  1. class ShellHelp  
  2. {  
  3. System.IO.MemoryStream outputstream = new MemoryStream();  
  4. Tamir.SharpSsh.SshStream inputstream = null;  
  5. Channel channel = null;  
  6. Session session = null;  
  7. /// <summary>  
  8. /// 命令等待标识  
  9. /// </summary>  
  10. string waitMark = "]#";  
  11.  
  12. /// <summary>  
  13. /// 打开连接  
  14. /// </summary>  
  15. /// <param name="host"></param>  
  16. /// <param name="username"></param>  
  17. /// <param name="pwd"></param>  
  18. /// <returns></returns>  
  19. public bool OpenShell(string host, string username, string pwd)  
  20. {  
  21. try  
  22. {  
  23. Redirect standard I/O to the SSH channel  
  24. inputstream = new Tamir.SharpSsh.SshStream(host, username, pwd);  
  25.  
  26. ///我手动加进去的方法。。为了读取输出信息  
  27. inputstream.set_OutputStream(outputstream);  
  28.  
  29. return inputstream != null;  
  30. }  
  31. catch  
  32. {  
  33. throw;  
  34. }  
  35. }  
  36. /// <summary>  
  37. /// 执行命令  
  38. /// </summary>  
  39. /// <param name="cmd"></param>  
  40. public bool Shell(string cmd)  
  41. {  
  42. if (inputstream == null) return false;  
  43.  
  44. string initinfo = GetAllString();  
  45.  
  46. inputstream.Write(cmd);  
  47. inputstream.Flush();  
  48.  
  49. string currentinfo = GetAllString();  
  50. while (currentinfo == initinfo)  
  51. {  
  52. System.Threading.Thread.Sleep(100);  
  53. currentinfo = GetAllString();  
  54. }  
  55.  
  56. return true;  
  57. }  
  58.  
  59. /// <summary>  
  60. /// 获取输出信息  
  61. /// </summary>  
  62. /// <returns></returns>  
  63. public string GetAllString()  
  64. {  
  65. string outinfo = Encoding.UTF8.GetString(outputstream.ToArray());  
  66. //等待命令结束字符  
  67. while (!outinfo.Trim().EndsWith(waitMark))  
  68. {  
  69. System.Threading.Thread.Sleep(200);  
  70. outinfo = Encoding.UTF8.GetString(outputstream.ToArray());  
  71. }  
  72. outputstream.Flush();  
  73. return outinfo.ToString();  
  74. }  
  75.  
  76. /// <summary>  
  77. /// 关闭连接  
  78. /// </summary>  
  79. public void Close()  
  80. {  
  81. if (inputstream != null) inputstream.Close();  
  82. }  
  83. }  

 
注意:string waitMark = "]#"; 在这里是用来标识命令是否执行完成的,,执行完成就会在后面输出这个字符,,有时也有可能是"]$"
 
接着我们来远程执行SHELL命令:
 

  1. static void Main(string[] args)  
  2. {  
  3. Console.WriteLine("Please input hostname:");  
  4. String host = Console.ReadLine();  
  5. Console.WriteLine("Please input username:");  
  6. String user = Console.ReadLine();  
  7. Console.WriteLine("Please input password:");  
  8. String pwd = Console.ReadLine();  
  9.  
  10. ShellHelp shell = new ShellHelp();  
  11. //连接linux成功  
  12. if (shell.OpenShell(host, user, pwd))  
  13. {  
  14. shell.Shell("df -h");//执行获取命令  
  15. // shell.Shell("dmidecode");//执行获取命令  
  16. string info = shell.GetAllString();//获取返回结果  
  17.  
  18. Console.WriteLine(info);  
  19.  
  20. shell.Close();//关闭连接  
  21. }  
  22.  
  23. Console.ReadLine();  
  24. }  
  25. }  

info就是我们执行命令的结果,,也可以执行多个命令
 
效果:
 

源码下载:http://www.jiamaocode.com/Pros/1213.html

转载于:https://www.cnblogs.com/jiamao/articles/1836096.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值