SshClient.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Collections.ObjectModel;
  5. using System.Text;
  6. using System.Diagnostics.CodeAnalysis;
  7. namespace Renci.SshNet
  8. {
  9. /// <summary>
  10. /// Provides client connection to SSH server.
  11. /// </summary>
  12. public class SshClient : BaseClient
  13. {
  14. /// <summary>
  15. /// Holds the list of forwarded ports
  16. /// </summary>
  17. private List<ForwardedPort> _forwardedPorts = new List<ForwardedPort>();
  18. private bool _disposeConnectionInfo;
  19. private Stream _inputStream;
  20. /// <summary>
  21. /// Gets the list of forwarded ports.
  22. /// </summary>
  23. public IEnumerable<ForwardedPort> ForwardedPorts
  24. {
  25. get
  26. {
  27. return this._forwardedPorts.AsReadOnly();
  28. }
  29. }
  30. #region Constructors
  31. /// <summary>
  32. /// Initializes a new instance of the <see cref="SshClient"/> class.
  33. /// </summary>
  34. /// <param name="connectionInfo">The connection info.</param>
  35. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
  36. public SshClient(ConnectionInfo connectionInfo)
  37. : base(connectionInfo)
  38. {
  39. }
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="SshClient"/> class.
  42. /// </summary>
  43. /// <param name="host">Connection host.</param>
  44. /// <param name="port">Connection port.</param>
  45. /// <param name="username">Authentication username.</param>
  46. /// <param name="password">Authentication password.</param>
  47. /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception>
  48. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception>
  49. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>
  50. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification="Disposed in Dispose(bool) method.")]
  51. public SshClient(string host, int port, string username, string password)
  52. : this(new PasswordConnectionInfo(host, port, username, password))
  53. {
  54. this._disposeConnectionInfo = true;
  55. }
  56. /// <summary>
  57. /// Initializes a new instance of the <see cref="SshClient"/> class.
  58. /// </summary>
  59. /// <param name="host">Connection host.</param>
  60. /// <param name="username">Authentication username.</param>
  61. /// <param name="password">Authentication password.</param>
  62. /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception>
  63. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception>
  64. public SshClient(string host, string username, string password)
  65. : this(host, 22, username, password)
  66. {
  67. }
  68. /// <summary>
  69. /// Initializes a new instance of the <see cref="SshClient"/> class.
  70. /// </summary>
  71. /// <param name="host">Connection host.</param>
  72. /// <param name="port">Connection port.</param>
  73. /// <param name="username">Authentication username.</param>
  74. /// <param name="keyFiles">Authentication private key file(s) .</param>
  75. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is null.</exception>
  76. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is null or contains whitespace characters.</exception>
  77. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>
  78. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
  79. public SshClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
  80. : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles))
  81. {
  82. this._disposeConnectionInfo = true;
  83. }
  84. /// <summary>
  85. /// Initializes a new instance of the <see cref="SshClient"/> class.
  86. /// </summary>
  87. /// <param name="host">Connection host.</param>
  88. /// <param name="username">Authentication username.</param>
  89. /// <param name="keyFiles">Authentication private key file(s) .</param>
  90. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is null.</exception>
  91. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is null or contains whitespace characters.</exception>
  92. public SshClient(string host, string username, params PrivateKeyFile[] keyFiles)
  93. : this(host, 22, username, keyFiles)
  94. {
  95. }
  96. #endregion
  97. /// <summary>
  98. /// Called when client is disconnecting from the server.
  99. /// </summary>
  100. protected override void OnDisconnecting()
  101. {
  102. base.OnDisconnecting();
  103. foreach (var port in this._forwardedPorts)
  104. {
  105. port.Stop();
  106. }
  107. }
  108. /// <summary>
  109. /// Adds the forwarded port.
  110. /// </summary>
  111. /// <param name="port">The port.</param>
  112. public void AddForwardedPort(ForwardedPort port)
  113. {
  114. // Ensure that connection is established.
  115. this.EnsureConnection();
  116. if (port.Session != null && port.Session != this.Session)
  117. throw new InvalidOperationException("Forwarded port is already added to a different client.");
  118. port.Session = this.Session;
  119. this._forwardedPorts.Add(port);
  120. }
  121. /// <summary>
  122. /// Stops and removes the forwarded port from the list.
  123. /// </summary>
  124. /// <param name="port">Forwarded port.</param>
  125. /// <exception cref="ArgumentNullException"><paramref name="port"/> is null.</exception>
  126. public void RemoveForwardedPort(ForwardedPort port)
  127. {
  128. if (port == null)
  129. throw new ArgumentNullException("port");
  130. // Stop port forwarding before removing it
  131. port.Stop();
  132. port.Session = null;
  133. this._forwardedPorts.Remove(port);
  134. }
  135. /// <summary>
  136. /// Creates the command to be executed.
  137. /// </summary>
  138. /// <param name="commandText">The command text.</param>
  139. /// <returns><see cref="SshCommand"/> object.</returns>
  140. public SshCommand CreateCommand(string commandText)
  141. {
  142. return this.CreateCommand(commandText, Encoding.UTF8);
  143. }
  144. /// <summary>
  145. /// Creates the command to be executed with specified encoding.
  146. /// </summary>
  147. /// <param name="commandText">The command text.</param>
  148. /// <param name="encoding">The encoding to use for results.</param>
  149. /// <returns><see cref="SshCommand"/> object which uses specified encoding.</returns>
  150. public SshCommand CreateCommand(string commandText, Encoding encoding)
  151. {
  152. // Ensure that connection is established.
  153. this.EnsureConnection();
  154. return new SshCommand(this.Session, commandText, encoding);
  155. }
  156. /// <summary>
  157. /// Creates and executes the command.
  158. /// </summary>
  159. /// <param name="commandText">The command text.</param>
  160. /// <returns>Returns an instance of <see cref="SshCommand"/> with execution results.</returns>
  161. /// <remarks>This method internally uses asynchronous calls.</remarks>
  162. /// <exception cref="ArgumentException">CommandText property is empty.</exception>
  163. /// <exception cref="Renci.SshNet.Common.SshException">Invalid Operation - An existing channel was used to execute this command.</exception>
  164. /// <exception cref="InvalidOperationException">Asynchronous operation is already in progress.</exception>
  165. public SshCommand RunCommand(string commandText)
  166. {
  167. var cmd = this.CreateCommand(commandText);
  168. cmd.Execute();
  169. return cmd;
  170. }
  171. /// <summary>
  172. /// Creates the shell.
  173. /// </summary>
  174. /// <param name="input">The input.</param>
  175. /// <param name="output">The output.</param>
  176. /// <param name="extendedOutput">The extended output.</param>
  177. /// <param name="terminalName">Name of the terminal.</param>
  178. /// <param name="columns">The columns.</param>
  179. /// <param name="rows">The rows.</param>
  180. /// <param name="width">The width.</param>
  181. /// <param name="height">The height.</param>
  182. /// <param name="terminalMode">The terminal mode.</param>
  183. /// <param name="bufferSize">Size of the internal read buffer.</param>
  184. /// <returns>Returns a representation of a <see cref="Shell"/> object.</returns>
  185. public Shell CreateShell(Stream input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, string terminalMode, int bufferSize)
  186. {
  187. // Ensure that connection is established.
  188. this.EnsureConnection();
  189. return new Shell(this.Session, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalMode, bufferSize);
  190. }
  191. /// <summary>
  192. /// Creates the shell.
  193. /// </summary>
  194. /// <param name="input">The input.</param>
  195. /// <param name="output">The output.</param>
  196. /// <param name="extendedOutput">The extended output.</param>
  197. /// <param name="terminalName">Name of the terminal.</param>
  198. /// <param name="columns">The columns.</param>
  199. /// <param name="rows">The rows.</param>
  200. /// <param name="width">The width.</param>
  201. /// <param name="height">The height.</param>
  202. /// <param name="terminalMode">The terminal mode.</param>
  203. /// <returns>Returns a representation of a <see cref="Shell"/> object.</returns>
  204. public Shell CreateShell(Stream input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, string terminalMode)
  205. {
  206. return this.CreateShell(input, output, extendedOutput, terminalName, columns, rows, width, height, terminalMode, 1024);
  207. }
  208. /// <summary>
  209. /// Creates the shell.
  210. /// </summary>
  211. /// <param name="input">The input.</param>
  212. /// <param name="output">The output.</param>
  213. /// <param name="extendedOutput">The extended output.</param>
  214. /// <returns>Returns a representation of a <see cref="Shell"/> object.</returns>
  215. public Shell CreateShell(Stream input, Stream output, Stream extendedOutput)
  216. {
  217. return this.CreateShell(input, output, extendedOutput, string.Empty, 0, 0, 0, 0, string.Empty, 1024);
  218. }
  219. /// <summary>
  220. /// Creates the shell.
  221. /// </summary>
  222. /// <param name="encoding">The encoding to use to send the input.</param>
  223. /// <param name="input">The input.</param>
  224. /// <param name="output">The output.</param>
  225. /// <param name="extendedOutput">The extended output.</param>
  226. /// <param name="terminalName">Name of the terminal.</param>
  227. /// <param name="columns">The columns.</param>
  228. /// <param name="rows">The rows.</param>
  229. /// <param name="width">The width.</param>
  230. /// <param name="height">The height.</param>
  231. /// <param name="terminalMode">The terminal mode.</param>
  232. /// <param name="bufferSize">Size of the internal read buffer.</param>
  233. /// <returns>Returns a representation of a <see cref="Shell"/> object.</returns>
  234. public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width , uint height , string terminalMode, int bufferSize)
  235. {
  236. // Ensure that connection is established.
  237. this.EnsureConnection();
  238. this._inputStream = new MemoryStream();
  239. var writer = new StreamWriter(this._inputStream, encoding);
  240. writer.Write(input);
  241. writer.Flush();
  242. this._inputStream.Seek(0, SeekOrigin.Begin);
  243. return this.CreateShell(this._inputStream, output, extendedOutput, terminalName, columns, rows, width, height, terminalMode, bufferSize);
  244. }
  245. /// <summary>
  246. /// Creates the shell.
  247. /// </summary>
  248. /// <param name="encoding">The encoding.</param>
  249. /// <param name="input">The input.</param>
  250. /// <param name="output">The output.</param>
  251. /// <param name="extendedOutput">The extended output.</param>
  252. /// <param name="terminalName">Name of the terminal.</param>
  253. /// <param name="columns">The columns.</param>
  254. /// <param name="rows">The rows.</param>
  255. /// <param name="width">The width.</param>
  256. /// <param name="height">The height.</param>
  257. /// <param name="terminalMode">The terminal mode.</param>
  258. /// <returns>Returns a representation of a <see cref="Shell"/> object.</returns>
  259. public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, string terminalMode)
  260. {
  261. return this.CreateShell(encoding, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalMode, 1024);
  262. }
  263. /// <summary>
  264. /// Creates the shell.
  265. /// </summary>
  266. /// <param name="encoding">The encoding.</param>
  267. /// <param name="input">The input.</param>
  268. /// <param name="output">The output.</param>
  269. /// <param name="extendedOutput">The extended output.</param>
  270. /// <returns>Returns a representation of a <see cref="Shell"/> object.</returns>
  271. public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput)
  272. {
  273. return this.CreateShell(encoding, input, output, extendedOutput, string.Empty, 0, 0, 0, 0, string.Empty, 1024);
  274. }
  275. /// <summary>
  276. /// Releases unmanaged and - optionally - managed resources
  277. /// </summary>
  278. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  279. protected override void Dispose(bool disposing)
  280. {
  281. base.Dispose(disposing);
  282. if (this._disposeConnectionInfo)
  283. ((IDisposable)this.ConnectionInfo).Dispose();
  284. if (this._inputStream != null)
  285. {
  286. this._inputStream.Dispose();
  287. this._inputStream = null;
  288. }
  289. }
  290. }
  291. }