SshClient.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. /// <example>
  40. /// <code source="..\..\Renci.SshNet.Tests\Classes\PasswordConnectionInfoTest.cs" region="Example PasswordConnectionInfo" language="C#" title="Connect using PasswordConnectionInfo object" />
  41. /// <code source="..\..\Renci.SshNet.Tests\Classes\PasswordConnectionInfoTest.cs" region="Example PasswordConnectionInfo PasswordExpired" language="C#" title="Connect using PasswordConnectionInfo object with passwod change option" />
  42. /// <code source="..\..\Renci.SshNet.Tests\Classes\PrivateKeyConnectionInfoTest.cs" region="Example PrivateKeyConnectionInfo PrivateKeyFile" language="C#" title="Connect using PrivateKeyConnectionInfo" />
  43. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient Connect Timeout" language="C#" title="Specify connection timeout when connecting" />
  44. /// </example>
  45. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
  46. public SshClient(ConnectionInfo connectionInfo)
  47. : base(connectionInfo)
  48. {
  49. }
  50. /// <summary>
  51. /// Initializes a new instance of the <see cref="SshClient"/> class.
  52. /// </summary>
  53. /// <param name="host">Connection host.</param>
  54. /// <param name="port">Connection port.</param>
  55. /// <param name="username">Authentication username.</param>
  56. /// <param name="password">Authentication password.</param>
  57. /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception>
  58. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception>
  59. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="F:System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>
  60. [SuppressMessage("Microsoft.Reliability", "C2A000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
  61. public SshClient(string host, int port, string username, string password)
  62. : this(new PasswordConnectionInfo(host, port, username, password))
  63. {
  64. this._disposeConnectionInfo = true;
  65. }
  66. /// <summary>
  67. /// Initializes a new instance of the <see cref="SshClient"/> class.
  68. /// </summary>
  69. /// <param name="host">Connection host.</param>
  70. /// <param name="username">Authentication username.</param>
  71. /// <param name="password">Authentication password.</param>
  72. /// <example>
  73. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient(host, username) Connect" language="C#" title="Connect using username and password" />
  74. /// </example>
  75. /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception>
  76. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception>
  77. public SshClient(string host, string username, string password)
  78. : this(host, ConnectionInfo.DEFAULT_PORT, username, password)
  79. {
  80. }
  81. /// <summary>
  82. /// Initializes a new instance of the <see cref="SshClient"/> class.
  83. /// </summary>
  84. /// <param name="host">Connection host.</param>
  85. /// <param name="port">Connection port.</param>
  86. /// <param name="username">Authentication username.</param>
  87. /// <param name="keyFiles">Authentication private key file(s) .</param>
  88. /// <example>
  89. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient(host, username) Connect PrivateKeyFile" language="C#" title="Connect using username and private key" />
  90. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient(host, username) Connect PrivateKeyFile PassPhrase" language="C#" title="Connect using username and private key and pass phrase" />
  91. /// </example>
  92. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is null.</exception>
  93. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is null or contains whitespace characters.</exception>
  94. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="F:System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>
  95. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
  96. public SshClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
  97. : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles))
  98. {
  99. this._disposeConnectionInfo = true;
  100. }
  101. /// <summary>
  102. /// Initializes a new instance of the <see cref="SshClient"/> class.
  103. /// </summary>
  104. /// <param name="host">Connection host.</param>
  105. /// <param name="username">Authentication username.</param>
  106. /// <param name="keyFiles">Authentication private key file(s) .</param>
  107. /// <example>
  108. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient(host, username) Connect PrivateKeyFile" language="C#" title="Connect using private key" />
  109. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient(host, username) Connect PrivateKeyFile PassPhrase" language="C#" title="Connect using private key and pass phrase" />
  110. /// </example>
  111. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is null.</exception>
  112. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is null or contains whitespace characters.</exception>
  113. public SshClient(string host, string username, params PrivateKeyFile[] keyFiles)
  114. : this(host, ConnectionInfo.DEFAULT_PORT, username, keyFiles)
  115. {
  116. }
  117. #endregion
  118. /// <summary>
  119. /// Called when client is disconnecting from the server.
  120. /// </summary>
  121. protected override void OnDisconnecting()
  122. {
  123. base.OnDisconnecting();
  124. foreach (var port in this._forwardedPorts)
  125. {
  126. port.Stop();
  127. }
  128. }
  129. /// <summary>
  130. /// Adds the forwarded port.
  131. /// </summary>
  132. /// <param name="port">The port.</param>
  133. /// <example>
  134. /// <code source="..\..\Renci.SshNet.Tests\Classes\ForwardedPortRemoteTest.cs" region="Example SshClient AddForwardedPort Start Stop ForwardedPortRemote" language="C#" title="Remote port forwarding" />
  135. /// <code source="..\..\Renci.SshNet.Tests\Classes\ForwardedPortLocalTest.cs" region="Example SshClient AddForwardedPort Start Stop ForwardedPortLocal" language="C#" title="Local port forwarding" />
  136. /// </example>
  137. /// <exception cref="InvalidOperationException">Forwarded port is already added to a different client.</exception>
  138. /// <exception cref="ArgumentNullException"><paramref name="port"/> is null.</exception>
  139. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  140. public void AddForwardedPort(ForwardedPort port)
  141. {
  142. if (port == null)
  143. throw new ArgumentNullException("port");
  144. // Ensure that connection is established.
  145. this.EnsureConnection();
  146. if (port.Session != null && port.Session != this.Session)
  147. throw new InvalidOperationException("Forwarded port is already added to a different client.");
  148. port.Session = this.Session;
  149. this._forwardedPorts.Add(port);
  150. }
  151. /// <summary>
  152. /// Stops and removes the forwarded port from the list.
  153. /// </summary>
  154. /// <param name="port">Forwarded port.</param>
  155. /// <exception cref="ArgumentNullException"><paramref name="port"/> is null.</exception>
  156. public void RemoveForwardedPort(ForwardedPort port)
  157. {
  158. if (port == null)
  159. throw new ArgumentNullException("port");
  160. // Stop port forwarding before removing it
  161. port.Stop();
  162. port.Session = null;
  163. this._forwardedPorts.Remove(port);
  164. }
  165. /// <summary>
  166. /// Creates the command to be executed.
  167. /// </summary>
  168. /// <param name="commandText">The command text.</param>
  169. /// <returns><see cref="SshCommand"/> object.</returns>
  170. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  171. public SshCommand CreateCommand(string commandText)
  172. {
  173. return this.CreateCommand(commandText, Encoding.UTF8);
  174. }
  175. /// <summary>
  176. /// Creates the command to be executed with specified encoding.
  177. /// </summary>
  178. /// <param name="commandText">The command text.</param>
  179. /// <param name="encoding">The encoding to use for results.</param>
  180. /// <returns><see cref="SshCommand"/> object which uses specified encoding.</returns>
  181. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  182. /// <exception cref="ArgumentNullException"><paramref name="commandText"/> or <paramref name="encoding"/> is null.</exception>
  183. public SshCommand CreateCommand(string commandText, Encoding encoding)
  184. {
  185. // Ensure that connection is established.
  186. this.EnsureConnection();
  187. return new SshCommand(this.Session, commandText, encoding);
  188. }
  189. /// <summary>
  190. /// Creates and executes the command.
  191. /// </summary>
  192. /// <param name="commandText">The command text.</param>
  193. /// <returns>Returns an instance of <see cref="SshCommand"/> with execution results.</returns>
  194. /// <remarks>This method internally uses asynchronous calls.</remarks>
  195. /// <example>
  196. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand RunCommand Result" language="C#" title="Running simple command" />
  197. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.NET40.cs" region="Example SshCommand RunCommand Parallel" language="C#" title="Run many commands in parallel" />
  198. /// </example>
  199. /// <exception cref="ArgumentException">CommandText property is empty.</exception>
  200. /// <exception cref="T:Renci.SshNet.Common.SshException">Invalid Operation - An existing channel was used to execute this command.</exception>
  201. /// <exception cref="InvalidOperationException">Asynchronous operation is already in progress.</exception>
  202. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  203. /// <exception cref="ArgumentNullException"><paramref name="commandText"/> is null.</exception>
  204. public SshCommand RunCommand(string commandText)
  205. {
  206. var cmd = this.CreateCommand(commandText);
  207. cmd.Execute();
  208. return cmd;
  209. }
  210. /// <summary>
  211. /// Creates the shell.
  212. /// </summary>
  213. /// <param name="input">The input.</param>
  214. /// <param name="output">The output.</param>
  215. /// <param name="extendedOutput">The extended output.</param>
  216. /// <param name="terminalName">Name of the terminal.</param>
  217. /// <param name="columns">The columns.</param>
  218. /// <param name="rows">The rows.</param>
  219. /// <param name="width">The width.</param>
  220. /// <param name="height">The height.</param>
  221. /// <param name="terminalModes">The terminal mode.</param>
  222. /// <param name="bufferSize">Size of the internal read buffer.</param>
  223. /// <returns>
  224. /// Returns a representation of a <see cref="Shell" /> object.
  225. /// </returns>
  226. public Shell CreateShell(Stream input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModes, int bufferSize)
  227. {
  228. // Ensure that connection is established.
  229. this.EnsureConnection();
  230. return new Shell(this.Session, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
  231. }
  232. /// <summary>
  233. /// Creates the shell.
  234. /// </summary>
  235. /// <param name="input">The input.</param>
  236. /// <param name="output">The output.</param>
  237. /// <param name="extendedOutput">The extended output.</param>
  238. /// <param name="terminalName">Name of the terminal.</param>
  239. /// <param name="columns">The columns.</param>
  240. /// <param name="rows">The rows.</param>
  241. /// <param name="width">The width.</param>
  242. /// <param name="height">The height.</param>
  243. /// <param name="terminalModes">The terminal mode.</param>
  244. /// <returns>
  245. /// Returns a representation of a <see cref="Shell" /> object.
  246. /// </returns>
  247. public Shell CreateShell(Stream input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModes)
  248. {
  249. return this.CreateShell(input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, 1024);
  250. }
  251. /// <summary>
  252. /// Creates the shell.
  253. /// </summary>
  254. /// <param name="input">The input.</param>
  255. /// <param name="output">The output.</param>
  256. /// <param name="extendedOutput">The extended output.</param>
  257. /// <returns>
  258. /// Returns a representation of a <see cref="Shell" /> object.
  259. /// </returns>
  260. public Shell CreateShell(Stream input, Stream output, Stream extendedOutput)
  261. {
  262. return this.CreateShell(input, output, extendedOutput, string.Empty, 0, 0, 0, 0, null, 1024);
  263. }
  264. /// <summary>
  265. /// Creates the shell.
  266. /// </summary>
  267. /// <param name="encoding">The encoding to use to send the input.</param>
  268. /// <param name="input">The input.</param>
  269. /// <param name="output">The output.</param>
  270. /// <param name="extendedOutput">The extended output.</param>
  271. /// <param name="terminalName">Name of the terminal.</param>
  272. /// <param name="columns">The columns.</param>
  273. /// <param name="rows">The rows.</param>
  274. /// <param name="width">The width.</param>
  275. /// <param name="height">The height.</param>
  276. /// <param name="terminalModes">The terminal mode.</param>
  277. /// <param name="bufferSize">Size of the internal read buffer.</param>
  278. /// <returns>
  279. /// Returns a representation of a <see cref="Shell" /> object.
  280. /// </returns>
  281. public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModes, int bufferSize)
  282. {
  283. this._inputStream = new MemoryStream();
  284. var writer = new StreamWriter(this._inputStream, encoding);
  285. writer.Write(input);
  286. writer.Flush();
  287. this._inputStream.Seek(0, SeekOrigin.Begin);
  288. return this.CreateShell(this._inputStream, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
  289. }
  290. /// <summary>
  291. /// Creates the shell.
  292. /// </summary>
  293. /// <param name="encoding">The encoding.</param>
  294. /// <param name="input">The input.</param>
  295. /// <param name="output">The output.</param>
  296. /// <param name="extendedOutput">The extended output.</param>
  297. /// <param name="terminalName">Name of the terminal.</param>
  298. /// <param name="columns">The columns.</param>
  299. /// <param name="rows">The rows.</param>
  300. /// <param name="width">The width.</param>
  301. /// <param name="height">The height.</param>
  302. /// <param name="terminalModes">The terminal modes.</param>
  303. /// <returns>
  304. /// Returns a representation of a <see cref="Shell" /> object.
  305. /// </returns>
  306. public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModes)
  307. {
  308. return this.CreateShell(encoding, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, 1024);
  309. }
  310. /// <summary>
  311. /// Creates the shell.
  312. /// </summary>
  313. /// <param name="encoding">The encoding.</param>
  314. /// <param name="input">The input.</param>
  315. /// <param name="output">The output.</param>
  316. /// <param name="extendedOutput">The extended output.</param>
  317. /// <returns>
  318. /// Returns a representation of a <see cref="Shell" /> object.
  319. /// </returns>
  320. public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput)
  321. {
  322. return this.CreateShell(encoding, input, output, extendedOutput, string.Empty, 0, 0, 0, 0, null, 1024);
  323. }
  324. /// <summary>
  325. /// Creates the shell stream.
  326. /// </summary>
  327. /// <param name="terminalName">Name of the terminal.</param>
  328. /// <param name="columns">The columns.</param>
  329. /// <param name="rows">The rows.</param>
  330. /// <param name="width">The width.</param>
  331. /// <param name="height">The height.</param>
  332. /// <param name="bufferSize">Size of the buffer.</param>
  333. /// <returns>
  334. /// Reference to Created ShellStream object.
  335. /// </returns>
  336. public ShellStream CreateShellStream(string terminalName, uint columns, uint rows, uint width, uint height, int bufferSize)
  337. {
  338. return this.CreateShellStream(terminalName, columns, rows, width, height, bufferSize, null);
  339. }
  340. /// <summary>
  341. /// Creates the shell stream.
  342. /// </summary>
  343. /// <param name="terminalName">Name of the terminal.</param>
  344. /// <param name="columns">The columns.</param>
  345. /// <param name="rows">The rows.</param>
  346. /// <param name="width">The width.</param>
  347. /// <param name="height">The height.</param>
  348. /// <param name="bufferSize">Size of the buffer.</param>
  349. /// <param name="terminalModeValues">The terminal mode values.</param>
  350. /// <returns>
  351. /// Reference to Created ShellStream object.
  352. /// </returns>
  353. public ShellStream CreateShellStream(string terminalName, uint columns, uint rows, uint width, uint height, int bufferSize, IDictionary<TerminalModes, uint> terminalModeValues)
  354. {
  355. // Ensure that connection is established.
  356. this.EnsureConnection();
  357. return new ShellStream(this.Session, terminalName, columns, rows, width, height, bufferSize, terminalModeValues);
  358. }
  359. /// <summary>
  360. /// Releases unmanaged and - optionally - managed resources
  361. /// </summary>
  362. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  363. protected override void Dispose(bool disposing)
  364. {
  365. base.Dispose(disposing);
  366. if (this._disposeConnectionInfo)
  367. ((IDisposable)this.ConnectionInfo).Dispose();
  368. if (this._inputStream != null)
  369. {
  370. this._inputStream.Dispose();
  371. this._inputStream = null;
  372. }
  373. }
  374. }
  375. }