SshClient.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  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 readonly List<ForwardedPort> _forwardedPorts;
  19. /// <summary>
  20. /// Holds a value indicating whether the current instance is disposed.
  21. /// </summary>
  22. /// <value>
  23. /// <see langword="true"/> if the current instance is disposed; otherwise, <see langword="false"/>.
  24. /// </value>
  25. private bool _isDisposed;
  26. private MemoryStream _inputStream;
  27. /// <summary>
  28. /// Gets the list of forwarded ports.
  29. /// </summary>
  30. public IEnumerable<ForwardedPort> ForwardedPorts
  31. {
  32. get
  33. {
  34. return _forwardedPorts.AsReadOnly();
  35. }
  36. }
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="SshClient" /> class.
  39. /// </summary>
  40. /// <param name="connectionInfo">The connection info.</param>
  41. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</exception>
  42. public SshClient(ConnectionInfo connectionInfo)
  43. : this(connectionInfo, ownsConnectionInfo: false)
  44. {
  45. }
  46. /// <summary>
  47. /// Initializes a new instance of the <see cref="SshClient"/> class.
  48. /// </summary>
  49. /// <param name="host">Connection host.</param>
  50. /// <param name="port">Connection port.</param>
  51. /// <param name="username">Authentication username.</param>
  52. /// <param name="password">Authentication password.</param>
  53. /// <exception cref="ArgumentNullException"><paramref name="password"/> is <see langword="null"/>.</exception>
  54. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  55. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="IPEndPoint.MaxPort"/>.</exception>
  56. public SshClient(string host, int port, string username, string password)
  57. #pragma warning disable CA2000 // Dispose objects before losing scope
  58. : this(new PasswordConnectionInfo(host, port, username, password), ownsConnectionInfo: true)
  59. #pragma warning restore CA2000 // Dispose objects before losing scope
  60. {
  61. }
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="SshClient"/> class.
  64. /// </summary>
  65. /// <param name="host">Connection host.</param>
  66. /// <param name="username">Authentication username.</param>
  67. /// <param name="password">Authentication password.</param>
  68. /// <exception cref="ArgumentNullException"><paramref name="password"/> is <see langword="null"/>.</exception>
  69. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  70. public SshClient(string host, string username, string password)
  71. : this(host, ConnectionInfo.DefaultPort, username, password)
  72. {
  73. }
  74. /// <summary>
  75. /// Initializes a new instance of the <see cref="SshClient"/> class.
  76. /// </summary>
  77. /// <param name="host">Connection host.</param>
  78. /// <param name="port">Connection port.</param>
  79. /// <param name="username">Authentication username.</param>
  80. /// <param name="keyFiles">Authentication private key file(s) .</param>
  81. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <see langword="null"/>.</exception>
  82. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  83. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="IPEndPoint.MaxPort"/>.</exception>
  84. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
  85. public SshClient(string host, int port, string username, params IPrivateKeySource[] keyFiles)
  86. : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), ownsConnectionInfo: true)
  87. {
  88. }
  89. /// <summary>
  90. /// Initializes a new instance of the <see cref="SshClient"/> class.
  91. /// </summary>
  92. /// <param name="host">Connection host.</param>
  93. /// <param name="username">Authentication username.</param>
  94. /// <param name="keyFiles">Authentication private key file(s) .</param>
  95. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <see langword="null"/>.</exception>
  96. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  97. public SshClient(string host, string username, params IPrivateKeySource[] keyFiles)
  98. : this(host, ConnectionInfo.DefaultPort, username, keyFiles)
  99. {
  100. }
  101. /// <summary>
  102. /// Initializes a new instance of the <see cref="SshClient"/> class.
  103. /// </summary>
  104. /// <param name="connectionInfo">The connection info.</param>
  105. /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
  106. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</exception>
  107. /// <remarks>
  108. /// If <paramref name="ownsConnectionInfo"/> is <see langword="true"/>, then the
  109. /// connection info will be disposed when this instance is disposed.
  110. /// </remarks>
  111. private SshClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
  112. : this(connectionInfo, ownsConnectionInfo, new ServiceFactory())
  113. {
  114. }
  115. /// <summary>
  116. /// Initializes a new instance of the <see cref="SshClient"/> class.
  117. /// </summary>
  118. /// <param name="connectionInfo">The connection info.</param>
  119. /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
  120. /// <param name="serviceFactory">The factory to use for creating new services.</param>
  121. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</exception>
  122. /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is <see langword="null"/>.</exception>
  123. /// <remarks>
  124. /// If <paramref name="ownsConnectionInfo"/> is <see langword="true"/>, then the
  125. /// connection info will be disposed when this instance is disposed.
  126. /// </remarks>
  127. internal SshClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
  128. : base(connectionInfo, ownsConnectionInfo, serviceFactory)
  129. {
  130. _forwardedPorts = new List<ForwardedPort>();
  131. }
  132. /// <summary>
  133. /// Called when client is disconnecting from the server.
  134. /// </summary>
  135. protected override void OnDisconnecting()
  136. {
  137. base.OnDisconnecting();
  138. foreach (var port in _forwardedPorts)
  139. {
  140. port.Stop();
  141. }
  142. }
  143. /// <summary>
  144. /// Adds the forwarded port.
  145. /// </summary>
  146. /// <param name="port">The port.</param>
  147. /// <exception cref="InvalidOperationException">Forwarded port is already added to a different client.</exception>
  148. /// <exception cref="ArgumentNullException"><paramref name="port"/> is <see langword="null"/>.</exception>
  149. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  150. public void AddForwardedPort(ForwardedPort port)
  151. {
  152. if (port is null)
  153. {
  154. throw new ArgumentNullException(nameof(port));
  155. }
  156. EnsureSessionIsOpen();
  157. AttachForwardedPort(port);
  158. _forwardedPorts.Add(port);
  159. }
  160. /// <summary>
  161. /// Stops and removes the forwarded port from the list.
  162. /// </summary>
  163. /// <param name="port">Forwarded port.</param>
  164. /// <exception cref="ArgumentNullException"><paramref name="port"/> is <see langword="null"/>.</exception>
  165. public void RemoveForwardedPort(ForwardedPort port)
  166. {
  167. if (port is null)
  168. {
  169. throw new ArgumentNullException(nameof(port));
  170. }
  171. // Stop port forwarding before removing it
  172. port.Stop();
  173. DetachForwardedPort(port);
  174. _ = _forwardedPorts.Remove(port);
  175. }
  176. private void AttachForwardedPort(ForwardedPort port)
  177. {
  178. if (port.Session != null && port.Session != Session)
  179. {
  180. throw new InvalidOperationException("Forwarded port is already added to a different client.");
  181. }
  182. port.Session = Session;
  183. }
  184. private static void DetachForwardedPort(ForwardedPort port)
  185. {
  186. port.Session = null;
  187. }
  188. /// <summary>
  189. /// Creates the command to be executed.
  190. /// </summary>
  191. /// <param name="commandText">The command text.</param>
  192. /// <returns><see cref="SshCommand"/> object.</returns>
  193. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  194. public SshCommand CreateCommand(string commandText)
  195. {
  196. return CreateCommand(commandText, ConnectionInfo.Encoding);
  197. }
  198. /// <summary>
  199. /// Creates the command to be executed with specified encoding.
  200. /// </summary>
  201. /// <param name="commandText">The command text.</param>
  202. /// <param name="encoding">The encoding to use for results.</param>
  203. /// <returns><see cref="SshCommand"/> object which uses specified encoding.</returns>
  204. /// <remarks>This method will change current default encoding.</remarks>
  205. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  206. /// <exception cref="ArgumentNullException"><paramref name="commandText"/> or <paramref name="encoding"/> is <see langword="null"/>.</exception>
  207. public SshCommand CreateCommand(string commandText, Encoding encoding)
  208. {
  209. EnsureSessionIsOpen();
  210. ConnectionInfo.Encoding = encoding;
  211. return new SshCommand(Session, commandText, encoding);
  212. }
  213. /// <summary>
  214. /// Creates and executes the command.
  215. /// </summary>
  216. /// <param name="commandText">The command text.</param>
  217. /// <returns>Returns an instance of <see cref="SshCommand"/> with execution results.</returns>
  218. /// <remarks>This method internally uses asynchronous calls.</remarks>
  219. /// <exception cref="ArgumentException">CommandText property is empty.</exception>
  220. /// <exception cref="SshException">Invalid Operation - An existing channel was used to execute this command.</exception>
  221. /// <exception cref="InvalidOperationException">Asynchronous operation is already in progress.</exception>
  222. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  223. /// <exception cref="ArgumentNullException"><paramref name="commandText"/> is <see langword="null"/>.</exception>
  224. public SshCommand RunCommand(string commandText)
  225. {
  226. var cmd = CreateCommand(commandText);
  227. _ = cmd.Execute();
  228. return cmd;
  229. }
  230. /// <summary>
  231. /// Creates the shell.
  232. /// </summary>
  233. /// <param name="input">The input.</param>
  234. /// <param name="output">The output.</param>
  235. /// <param name="extendedOutput">The extended output.</param>
  236. /// <param name="terminalName">Name of the terminal.</param>
  237. /// <param name="columns">The columns.</param>
  238. /// <param name="rows">The rows.</param>
  239. /// <param name="width">The width.</param>
  240. /// <param name="height">The height.</param>
  241. /// <param name="terminalModes">The terminal mode.</param>
  242. /// <param name="bufferSize">Size of the internal read buffer.</param>
  243. /// <returns>
  244. /// Returns a representation of a <see cref="Shell" /> object.
  245. /// </returns>
  246. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  247. 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)
  248. {
  249. EnsureSessionIsOpen();
  250. return new Shell(Session, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
  251. }
  252. /// <summary>
  253. /// Creates the shell.
  254. /// </summary>
  255. /// <param name="input">The input.</param>
  256. /// <param name="output">The output.</param>
  257. /// <param name="extendedOutput">The extended output.</param>
  258. /// <param name="terminalName">Name of the terminal.</param>
  259. /// <param name="columns">The columns.</param>
  260. /// <param name="rows">The rows.</param>
  261. /// <param name="width">The width.</param>
  262. /// <param name="height">The height.</param>
  263. /// <param name="terminalModes">The terminal mode.</param>
  264. /// <returns>
  265. /// Returns a representation of a <see cref="Shell" /> object.
  266. /// </returns>
  267. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  268. public Shell CreateShell(Stream input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModes)
  269. {
  270. return CreateShell(input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, 1024);
  271. }
  272. /// <summary>
  273. /// Creates the shell.
  274. /// </summary>
  275. /// <param name="input">The input.</param>
  276. /// <param name="output">The output.</param>
  277. /// <param name="extendedOutput">The extended output.</param>
  278. /// <returns>
  279. /// Returns a representation of a <see cref="Shell" /> object.
  280. /// </returns>
  281. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  282. public Shell CreateShell(Stream input, Stream output, Stream extendedOutput)
  283. {
  284. return CreateShell(input, output, extendedOutput, string.Empty, 0, 0, 0, 0, terminalModes: null, 1024);
  285. }
  286. /// <summary>
  287. /// Creates the shell.
  288. /// </summary>
  289. /// <param name="encoding">The encoding to use to send the input.</param>
  290. /// <param name="input">The input.</param>
  291. /// <param name="output">The output.</param>
  292. /// <param name="extendedOutput">The extended output.</param>
  293. /// <param name="terminalName">Name of the terminal.</param>
  294. /// <param name="columns">The columns.</param>
  295. /// <param name="rows">The rows.</param>
  296. /// <param name="width">The width.</param>
  297. /// <param name="height">The height.</param>
  298. /// <param name="terminalModes">The terminal mode.</param>
  299. /// <param name="bufferSize">Size of the internal read buffer.</param>
  300. /// <returns>
  301. /// Returns a representation of a <see cref="Shell" /> object.
  302. /// </returns>
  303. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  304. 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)
  305. {
  306. /*
  307. * TODO Issue #1224: let shell dispose of input stream when we own the stream!
  308. */
  309. _inputStream = new MemoryStream();
  310. using (var writer = new StreamWriter(_inputStream, encoding, bufferSize: 1024, leaveOpen: true))
  311. {
  312. writer.Write(input);
  313. writer.Flush();
  314. }
  315. _ = _inputStream.Seek(0, SeekOrigin.Begin);
  316. return CreateShell(_inputStream, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
  317. }
  318. /// <summary>
  319. /// Creates the shell.
  320. /// </summary>
  321. /// <param name="encoding">The encoding.</param>
  322. /// <param name="input">The input.</param>
  323. /// <param name="output">The output.</param>
  324. /// <param name="extendedOutput">The extended output.</param>
  325. /// <param name="terminalName">Name of the terminal.</param>
  326. /// <param name="columns">The columns.</param>
  327. /// <param name="rows">The rows.</param>
  328. /// <param name="width">The width.</param>
  329. /// <param name="height">The height.</param>
  330. /// <param name="terminalModes">The terminal modes.</param>
  331. /// <returns>
  332. /// Returns a representation of a <see cref="Shell" /> object.
  333. /// </returns>
  334. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  335. 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)
  336. {
  337. return CreateShell(encoding, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, 1024);
  338. }
  339. /// <summary>
  340. /// Creates the shell.
  341. /// </summary>
  342. /// <param name="encoding">The encoding.</param>
  343. /// <param name="input">The input.</param>
  344. /// <param name="output">The output.</param>
  345. /// <param name="extendedOutput">The extended output.</param>
  346. /// <returns>
  347. /// Returns a representation of a <see cref="Shell" /> object.
  348. /// </returns>
  349. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  350. public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput)
  351. {
  352. return CreateShell(encoding, input, output, extendedOutput, string.Empty, 0, 0, 0, 0, terminalModes: null, 1024);
  353. }
  354. /// <summary>
  355. /// Creates the shell stream.
  356. /// </summary>
  357. /// <param name="terminalName">The <c>TERM</c> environment variable.</param>
  358. /// <param name="columns">The terminal width in columns.</param>
  359. /// <param name="rows">The terminal width in rows.</param>
  360. /// <param name="width">The terminal width in pixels.</param>
  361. /// <param name="height">The terminal height in pixels.</param>
  362. /// <param name="bufferSize">The size of the buffer.</param>
  363. /// <returns>
  364. /// The created <see cref="ShellStream"/> instance.
  365. /// </returns>
  366. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  367. /// <remarks>
  368. /// <para>
  369. /// The <c>TERM</c> environment variable contains an identifier for the text window's capabilities.
  370. /// You can get a detailed list of these capabilities by using the ‘infocmp’ command.
  371. /// </para>
  372. /// <para>
  373. /// The column/row dimensions override the pixel dimensions(when nonzero). Pixel dimensions refer
  374. /// to the drawable area of the window.
  375. /// </para>
  376. /// </remarks>
  377. public ShellStream CreateShellStream(string terminalName, uint columns, uint rows, uint width, uint height, int bufferSize)
  378. {
  379. return CreateShellStream(terminalName, columns, rows, width, height, bufferSize, terminalModeValues: null);
  380. }
  381. /// <summary>
  382. /// Creates the shell stream.
  383. /// </summary>
  384. /// <param name="terminalName">The <c>TERM</c> environment variable.</param>
  385. /// <param name="columns">The terminal width in columns.</param>
  386. /// <param name="rows">The terminal width in rows.</param>
  387. /// <param name="width">The terminal width in pixels.</param>
  388. /// <param name="height">The terminal height in pixels.</param>
  389. /// <param name="bufferSize">The size of the buffer.</param>
  390. /// <param name="terminalModeValues">The terminal mode values.</param>
  391. /// <returns>
  392. /// The created <see cref="ShellStream"/> instance.
  393. /// </returns>
  394. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  395. /// <remarks>
  396. /// <para>
  397. /// The <c>TERM</c> environment variable contains an identifier for the text window's capabilities.
  398. /// You can get a detailed list of these capabilities by using the ‘infocmp’ command.
  399. /// </para>
  400. /// <para>
  401. /// The column/row dimensions override the pixel dimensions(when non-zero). Pixel dimensions refer
  402. /// to the drawable area of the window.
  403. /// </para>
  404. /// </remarks>
  405. public ShellStream CreateShellStream(string terminalName, uint columns, uint rows, uint width, uint height, int bufferSize, IDictionary<TerminalModes, uint> terminalModeValues)
  406. {
  407. EnsureSessionIsOpen();
  408. return ServiceFactory.CreateShellStream(Session, terminalName, columns, rows, width, height, terminalModeValues, bufferSize);
  409. }
  410. /// <summary>
  411. /// Stops forwarded ports.
  412. /// </summary>
  413. protected override void OnDisconnected()
  414. {
  415. base.OnDisconnected();
  416. for (var i = _forwardedPorts.Count - 1; i >= 0; i--)
  417. {
  418. var port = _forwardedPorts[i];
  419. DetachForwardedPort(port);
  420. _forwardedPorts.RemoveAt(i);
  421. }
  422. }
  423. /// <summary>
  424. /// Releases unmanaged and - optionally - managed resources.
  425. /// </summary>
  426. /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
  427. protected override void Dispose(bool disposing)
  428. {
  429. base.Dispose(disposing);
  430. if (_isDisposed)
  431. {
  432. return;
  433. }
  434. if (disposing)
  435. {
  436. if (_inputStream != null)
  437. {
  438. _inputStream.Dispose();
  439. _inputStream = null;
  440. }
  441. _isDisposed = true;
  442. }
  443. }
  444. private void EnsureSessionIsOpen()
  445. {
  446. if (Session is null)
  447. {
  448. throw new SshConnectionException("Client not connected.");
  449. }
  450. }
  451. }
  452. }