SshClient.cs 17 KB

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