SshCommand.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Threading;
  5. using Renci.SshNet.Channels;
  6. using Renci.SshNet.Common;
  7. using Renci.SshNet.Messages;
  8. using Renci.SshNet.Messages.Connection;
  9. using Renci.SshNet.Messages.Transport;
  10. using System.Globalization;
  11. namespace Renci.SshNet
  12. {
  13. /// <summary>
  14. /// Represents SSH command that can be executed.
  15. /// </summary>
  16. public partial class SshCommand : IDisposable
  17. {
  18. private readonly ISession _session;
  19. private readonly Encoding _encoding;
  20. private IChannelSession _channel;
  21. private CommandAsyncResult _asyncResult;
  22. private AsyncCallback _callback;
  23. private EventWaitHandle _sessionErrorOccuredWaitHandle = new AutoResetEvent(false);
  24. private Exception _exception;
  25. private bool _hasError;
  26. private readonly object _endExecuteLock = new object();
  27. /// <summary>
  28. /// Gets the command text.
  29. /// </summary>
  30. public string CommandText { get; private set; }
  31. /// <summary>
  32. /// Gets or sets the command timeout.
  33. /// </summary>
  34. /// <value>
  35. /// The command timeout.
  36. /// </value>
  37. /// <example>
  38. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Execute CommandTimeout" language="C#" title="Specify command execution timeout" />
  39. /// </example>
  40. public TimeSpan CommandTimeout { get; set; }
  41. /// <summary>
  42. /// Gets the command exit status.
  43. /// </summary>
  44. /// <example>
  45. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand RunCommand ExitStatus" language="C#" title="Get command execution exit status" />
  46. /// </example>
  47. public int ExitStatus { get; private set; }
  48. /// <summary>
  49. /// Gets the output stream.
  50. /// </summary>
  51. /// <example>
  52. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Execute OutputStream" language="C#" title="Use OutputStream to get command execution output" />
  53. /// </example>
  54. public Stream OutputStream { get; private set; }
  55. /// <summary>
  56. /// Gets the extended output stream.
  57. /// </summary>
  58. /// <example>
  59. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Execute ExtendedOutputStream" language="C#" title="Use ExtendedOutputStream to get command debug execution output" />
  60. /// </example>
  61. public Stream ExtendedOutputStream { get; private set; }
  62. private StringBuilder _result;
  63. /// <summary>
  64. /// Gets the command execution result.
  65. /// </summary>
  66. /// <example>
  67. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand RunCommand Result" language="C#" title="Running simple command" />
  68. /// </example>
  69. public string Result
  70. {
  71. get
  72. {
  73. if (this._result == null)
  74. {
  75. this._result = new StringBuilder();
  76. }
  77. if (this.OutputStream != null && this.OutputStream.Length > 0)
  78. {
  79. using (var sr = new StreamReader(this.OutputStream, _encoding))
  80. {
  81. this._result.Append(sr.ReadToEnd());
  82. }
  83. }
  84. return this._result.ToString();
  85. }
  86. }
  87. private StringBuilder _error;
  88. /// <summary>
  89. /// Gets the command execution error.
  90. /// </summary>
  91. /// <example>
  92. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Error" language="C#" title="Display command execution error" />
  93. /// </example>
  94. public string Error
  95. {
  96. get
  97. {
  98. if (this._hasError)
  99. {
  100. if (this._error == null)
  101. {
  102. this._error = new StringBuilder();
  103. }
  104. if (this.ExtendedOutputStream != null && this.ExtendedOutputStream.Length > 0)
  105. {
  106. using (var sr = new StreamReader(this.ExtendedOutputStream, _encoding))
  107. {
  108. this._error.Append(sr.ReadToEnd());
  109. }
  110. }
  111. return this._error.ToString();
  112. }
  113. return string.Empty;
  114. }
  115. }
  116. /// <summary>
  117. /// Initializes a new instance of the <see cref="SshCommand"/> class.
  118. /// </summary>
  119. /// <param name="session">The session.</param>
  120. /// <param name="commandText">The command text.</param>
  121. /// <param name="encoding">The encoding to use for the results.</param>
  122. /// <exception cref="ArgumentNullException">Either <paramref name="session"/>, <paramref name="commandText"/> is null.</exception>
  123. internal SshCommand(ISession session, string commandText, Encoding encoding)
  124. {
  125. if (session == null)
  126. throw new ArgumentNullException("session");
  127. if (commandText == null)
  128. throw new ArgumentNullException("commandText");
  129. if (encoding == null)
  130. throw new ArgumentNullException("encoding");
  131. this._session = session;
  132. this.CommandText = commandText;
  133. this._encoding = encoding;
  134. this.CommandTimeout = new TimeSpan(0, 0, 0, 0, -1);
  135. this._session.Disconnected += Session_Disconnected;
  136. this._session.ErrorOccured += Session_ErrorOccured;
  137. }
  138. /// <summary>
  139. /// Begins an asynchronous command execution.
  140. /// </summary>
  141. /// <returns>
  142. /// An <see cref="System.IAsyncResult" /> that represents the asynchronous command execution, which could still be pending.
  143. /// </returns>
  144. /// <example>
  145. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand BeginExecute IsCompleted EndExecute" language="C#" title="Asynchronous Command Execution" />
  146. /// </example>
  147. /// <exception cref="System.InvalidOperationException">Asynchronous operation is already in progress.</exception>
  148. /// <exception cref="SshException">Invalid operation.</exception>
  149. /// <exception cref="System.ArgumentException">CommandText property is empty.</exception>
  150. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  151. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  152. /// <exception cref="InvalidOperationException">Asynchronous operation is already in progress.</exception>
  153. /// <exception cref="ArgumentException">CommandText property is empty.</exception>
  154. public IAsyncResult BeginExecute()
  155. {
  156. return this.BeginExecute(null, null);
  157. }
  158. /// <summary>
  159. /// Begins an asynchronous command execution.
  160. /// </summary>
  161. /// <param name="callback">An optional asynchronous callback, to be called when the command execution is complete.</param>
  162. /// <returns>
  163. /// An <see cref="System.IAsyncResult" /> that represents the asynchronous command execution, which could still be pending.
  164. /// </returns>
  165. /// <exception cref="System.InvalidOperationException">Asynchronous operation is already in progress.</exception>
  166. /// <exception cref="SshException">Invalid operation.</exception>
  167. /// <exception cref="System.ArgumentException">CommandText property is empty.</exception>
  168. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  169. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  170. /// <exception cref="InvalidOperationException">Asynchronous operation is already in progress.</exception>
  171. /// <exception cref="ArgumentException">CommandText property is empty.</exception>
  172. public IAsyncResult BeginExecute(AsyncCallback callback)
  173. {
  174. return this.BeginExecute(callback, null);
  175. }
  176. /// <summary>
  177. /// Begins an asynchronous command execution.
  178. /// </summary>
  179. /// <param name="callback">An optional asynchronous callback, to be called when the command execution is complete.</param>
  180. /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param>
  181. /// <returns>
  182. /// An <see cref="System.IAsyncResult" /> that represents the asynchronous command execution, which could still be pending.
  183. /// </returns>
  184. /// <exception cref="System.InvalidOperationException">Asynchronous operation is already in progress.</exception>
  185. /// <exception cref="SshException">Invalid operation.</exception>
  186. /// <exception cref="System.ArgumentException">CommandText property is empty.</exception>
  187. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  188. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  189. /// <exception cref="InvalidOperationException">Asynchronous operation is already in progress.</exception>
  190. /// <exception cref="ArgumentException">CommandText property is empty.</exception>
  191. public IAsyncResult BeginExecute(AsyncCallback callback, object state)
  192. {
  193. // Prevent from executing BeginExecute before calling EndExecute
  194. if (this._asyncResult != null)
  195. {
  196. throw new InvalidOperationException("Asynchronous operation is already in progress.");
  197. }
  198. // Create new AsyncResult object
  199. this._asyncResult = new CommandAsyncResult
  200. {
  201. AsyncWaitHandle = new ManualResetEvent(false),
  202. IsCompleted = false,
  203. AsyncState = state,
  204. };
  205. // When command re-executed again, create a new channel
  206. if (this._channel != null)
  207. {
  208. throw new SshException("Invalid operation.");
  209. }
  210. this.CreateChannel();
  211. if (string.IsNullOrEmpty(this.CommandText))
  212. throw new ArgumentException("CommandText property is empty.");
  213. this._callback = callback;
  214. this._channel.Open();
  215. // Send channel command request
  216. this._channel.SendExecRequest(this.CommandText);
  217. return _asyncResult;
  218. }
  219. /// <summary>
  220. /// Begins an asynchronous command execution.
  221. /// </summary>
  222. /// <param name="commandText">The command text.</param>
  223. /// <param name="callback">An optional asynchronous callback, to be called when the command execution is complete.</param>
  224. /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param>
  225. /// <returns>
  226. /// An <see cref="System.IAsyncResult" /> that represents the asynchronous command execution, which could still be pending.
  227. /// </returns>
  228. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  229. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  230. public IAsyncResult BeginExecute(string commandText, AsyncCallback callback, object state)
  231. {
  232. this.CommandText = commandText;
  233. return BeginExecute(callback, state);
  234. }
  235. /// <summary>
  236. /// Waits for the pending asynchronous command execution to complete.
  237. /// </summary>
  238. /// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param>
  239. /// <returns>Command execution result.</returns>
  240. /// <example>
  241. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand BeginExecute IsCompleted EndExecute" language="C#" title="Asynchronous Command Execution" />
  242. /// </example>
  243. /// <exception cref="ArgumentException">Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.</exception>
  244. public string EndExecute(IAsyncResult asyncResult)
  245. {
  246. if (this._asyncResult == asyncResult && this._asyncResult != null)
  247. {
  248. lock (this._endExecuteLock)
  249. {
  250. if (this._asyncResult != null)
  251. {
  252. // Make sure that operation completed if not wait for it to finish
  253. this.WaitOnHandle(this._asyncResult.AsyncWaitHandle);
  254. if (_channel.IsOpen)
  255. {
  256. _channel.Close();
  257. }
  258. UnsubscribeFromEventsAndDisposeChannel();
  259. _channel = null;
  260. _asyncResult = null;
  261. return this.Result;
  262. }
  263. }
  264. }
  265. throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
  266. }
  267. /// <summary>
  268. /// Executes command specified by <see cref="CommandText"/> property.
  269. /// </summary>
  270. /// <returns>Command execution result</returns>
  271. /// <example>
  272. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Execute" language="C#" title="Simple command execution" />
  273. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Error" language="C#" title="Display command execution error" />
  274. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Execute CommandTimeout" language="C#" title="Specify command execution timeout" />
  275. /// </example>
  276. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  277. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  278. public string Execute()
  279. {
  280. return this.EndExecute(this.BeginExecute(null, null));
  281. }
  282. /// <summary>
  283. /// Cancels command execution in asynchronous scenarios.
  284. /// </summary>
  285. public void CancelAsync()
  286. {
  287. if (this._channel != null && this._channel.IsOpen && this._asyncResult != null)
  288. {
  289. // TODO: check with Oleg if we shouldn't dispose the channel and uninitialize it ?
  290. this._channel.Close();
  291. }
  292. }
  293. /// <summary>
  294. /// Executes the specified command text.
  295. /// </summary>
  296. /// <param name="commandText">The command text.</param>
  297. /// <returns>Command execution result</returns>
  298. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  299. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  300. public string Execute(string commandText)
  301. {
  302. this.CommandText = commandText;
  303. return this.Execute();
  304. }
  305. private void CreateChannel()
  306. {
  307. this._channel = this._session.CreateChannelSession();
  308. this._channel.DataReceived += Channel_DataReceived;
  309. this._channel.ExtendedDataReceived += Channel_ExtendedDataReceived;
  310. this._channel.RequestReceived += Channel_RequestReceived;
  311. this._channel.Closed += Channel_Closed;
  312. // Dispose of streams if already exists
  313. if (this.OutputStream != null)
  314. {
  315. this.OutputStream.Dispose();
  316. this.OutputStream = null;
  317. }
  318. if (this.ExtendedOutputStream != null)
  319. {
  320. this.ExtendedOutputStream.Dispose();
  321. this.ExtendedOutputStream = null;
  322. }
  323. // Initialize output streams and StringBuilders
  324. this.OutputStream = new PipeStream();
  325. this.ExtendedOutputStream = new PipeStream();
  326. this._result = null;
  327. this._error = null;
  328. }
  329. private void Session_Disconnected(object sender, EventArgs e)
  330. {
  331. // If objected is disposed or being disposed don't handle this event
  332. if (this._isDisposed)
  333. return;
  334. this._exception = new SshConnectionException("An established connection was aborted by the software in your host machine.", DisconnectReason.ConnectionLost);
  335. this._sessionErrorOccuredWaitHandle.Set();
  336. }
  337. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  338. {
  339. // If objected is disposed or being disposed don't handle this event
  340. if (this._isDisposed)
  341. return;
  342. this._exception = e.Exception;
  343. this._sessionErrorOccuredWaitHandle.Set();
  344. }
  345. private void Channel_Closed(object sender, ChannelEventArgs e)
  346. {
  347. if (this.OutputStream != null)
  348. {
  349. this.OutputStream.Flush();
  350. }
  351. if (this.ExtendedOutputStream != null)
  352. {
  353. this.ExtendedOutputStream.Flush();
  354. }
  355. this._asyncResult.IsCompleted = true;
  356. if (this._callback != null)
  357. {
  358. // Execute callback on different thread
  359. this.ExecuteThread(() => this._callback(this._asyncResult));
  360. }
  361. ((EventWaitHandle)this._asyncResult.AsyncWaitHandle).Set();
  362. }
  363. private void Channel_RequestReceived(object sender, ChannelRequestEventArgs e)
  364. {
  365. Message replyMessage;
  366. if (e.Info is ExitStatusRequestInfo)
  367. {
  368. var exitStatusInfo = e.Info as ExitStatusRequestInfo;
  369. this.ExitStatus = (int) exitStatusInfo.ExitStatus;
  370. replyMessage = new ChannelSuccessMessage(this._channel.LocalChannelNumber);
  371. }
  372. else
  373. {
  374. replyMessage = new ChannelFailureMessage(this._channel.LocalChannelNumber);
  375. }
  376. if (e.Info.WantReply)
  377. {
  378. this._session.SendMessage(replyMessage);
  379. }
  380. }
  381. private void Channel_ExtendedDataReceived(object sender, ChannelExtendedDataEventArgs e)
  382. {
  383. if (this.ExtendedOutputStream != null)
  384. {
  385. this.ExtendedOutputStream.Write(e.Data, 0, e.Data.Length);
  386. this.ExtendedOutputStream.Flush();
  387. }
  388. if (e.DataTypeCode == 1)
  389. {
  390. this._hasError = true;
  391. }
  392. }
  393. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  394. {
  395. if (this.OutputStream != null)
  396. {
  397. this.OutputStream.Write(e.Data, 0, e.Data.Length);
  398. this.OutputStream.Flush();
  399. }
  400. if (this._asyncResult != null)
  401. {
  402. lock (this._asyncResult)
  403. {
  404. this._asyncResult.BytesReceived += e.Data.Length;
  405. }
  406. }
  407. }
  408. /// <exception cref="SshOperationTimeoutException">Command '{0}' has timed out.</exception>
  409. /// <remarks>The actual command will be included in the exception message.</remarks>
  410. private void WaitOnHandle(WaitHandle waitHandle)
  411. {
  412. var waitHandles = new[]
  413. {
  414. this._sessionErrorOccuredWaitHandle,
  415. waitHandle
  416. };
  417. switch (WaitHandle.WaitAny(waitHandles, this.CommandTimeout))
  418. {
  419. case 0:
  420. throw this._exception;
  421. case WaitHandle.WaitTimeout:
  422. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Command '{0}' has timed out.", this.CommandText));
  423. }
  424. }
  425. private void UnsubscribeFromEventsAndDisposeChannel()
  426. {
  427. // unsubscribe from events as we do not want to be signaled should these get fired
  428. // during the dispose of the channel
  429. _channel.DataReceived -= Channel_DataReceived;
  430. _channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
  431. _channel.RequestReceived -= Channel_RequestReceived;
  432. _channel.Closed -= Channel_Closed;
  433. // actually dispose the channel
  434. _channel.Dispose();
  435. }
  436. partial void ExecuteThread(Action action);
  437. #region IDisposable Members
  438. private bool _isDisposed;
  439. /// <summary>
  440. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  441. /// </summary>
  442. public void Dispose()
  443. {
  444. Dispose(true);
  445. GC.SuppressFinalize(this);
  446. }
  447. /// <summary>
  448. /// Releases unmanaged and - optionally - managed resources
  449. /// </summary>
  450. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  451. protected virtual void Dispose(bool disposing)
  452. {
  453. // Check to see if Dispose has already been called.
  454. if (!this._isDisposed)
  455. {
  456. // If disposing equals true, dispose all managed
  457. // and unmanaged ResourceMessages.
  458. if (disposing)
  459. {
  460. this._session.Disconnected -= Session_Disconnected;
  461. this._session.ErrorOccured -= Session_ErrorOccured;
  462. // Dispose managed ResourceMessages.
  463. if (this.OutputStream != null)
  464. {
  465. this.OutputStream.Dispose();
  466. this.OutputStream = null;
  467. }
  468. // Dispose managed ResourceMessages.
  469. if (this.ExtendedOutputStream != null)
  470. {
  471. this.ExtendedOutputStream.Dispose();
  472. this.ExtendedOutputStream = null;
  473. }
  474. // Dispose managed ResourceMessages.
  475. if (this._sessionErrorOccuredWaitHandle != null)
  476. {
  477. this._sessionErrorOccuredWaitHandle.Dispose();
  478. this._sessionErrorOccuredWaitHandle = null;
  479. }
  480. // Dispose managed ResourceMessages.
  481. if (this._channel != null)
  482. {
  483. UnsubscribeFromEventsAndDisposeChannel();
  484. this._channel = null;
  485. }
  486. }
  487. // Note disposing has been done.
  488. this._isDisposed = true;
  489. }
  490. }
  491. /// <summary>
  492. /// Releases unmanaged resources and performs other cleanup operations before the
  493. /// <see cref="SshCommand"/> is reclaimed by garbage collection.
  494. /// </summary>
  495. ~SshCommand()
  496. {
  497. // Do not re-create Dispose clean-up code here.
  498. // Calling Dispose(false) is optimal in terms of
  499. // readability and maintainability.
  500. Dispose(false);
  501. }
  502. #endregion
  503. }
  504. }