SshClient.cs 25 KB

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