2
0

SshClient.cs 22 KB

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