SshCommand.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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.SendEof();
  257. _channel.Close();
  258. }
  259. UnsubscribeFromEventsAndDisposeChannel();
  260. _channel = null;
  261. _asyncResult = null;
  262. return this.Result;
  263. }
  264. }
  265. }
  266. 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.");
  267. }
  268. /// <summary>
  269. /// Executes command specified by <see cref="CommandText"/> property.
  270. /// </summary>
  271. /// <returns>Command execution result</returns>
  272. /// <example>
  273. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Execute" language="C#" title="Simple command execution" />
  274. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Error" language="C#" title="Display command execution error" />
  275. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Execute CommandTimeout" language="C#" title="Specify command execution timeout" />
  276. /// </example>
  277. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  278. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  279. public string Execute()
  280. {
  281. return this.EndExecute(this.BeginExecute(null, null));
  282. }
  283. /// <summary>
  284. /// Cancels command execution in asynchronous scenarios.
  285. /// </summary>
  286. public void CancelAsync()
  287. {
  288. if (this._channel != null && this._channel.IsOpen && this._asyncResult != null)
  289. {
  290. // TODO: check with Oleg if we shouldn't dispose the channel and uninitialize it ?
  291. this._channel.Close();
  292. }
  293. }
  294. /// <summary>
  295. /// Executes the specified command text.
  296. /// </summary>
  297. /// <param name="commandText">The command text.</param>
  298. /// <returns>Command execution result</returns>
  299. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  300. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  301. public string Execute(string commandText)
  302. {
  303. this.CommandText = commandText;
  304. return this.Execute();
  305. }
  306. private void CreateChannel()
  307. {
  308. this._channel = this._session.CreateChannelSession();
  309. this._channel.DataReceived += Channel_DataReceived;
  310. this._channel.ExtendedDataReceived += Channel_ExtendedDataReceived;
  311. this._channel.RequestReceived += Channel_RequestReceived;
  312. this._channel.Closed += Channel_Closed;
  313. // Dispose of streams if already exists
  314. if (this.OutputStream != null)
  315. {
  316. this.OutputStream.Dispose();
  317. this.OutputStream = null;
  318. }
  319. if (this.ExtendedOutputStream != null)
  320. {
  321. this.ExtendedOutputStream.Dispose();
  322. this.ExtendedOutputStream = null;
  323. }
  324. // Initialize output streams and StringBuilders
  325. this.OutputStream = new PipeStream();
  326. this.ExtendedOutputStream = new PipeStream();
  327. this._result = null;
  328. this._error = null;
  329. }
  330. private void Session_Disconnected(object sender, EventArgs e)
  331. {
  332. // If objected is disposed or being disposed don't handle this event
  333. if (this._isDisposed)
  334. return;
  335. this._exception = new SshConnectionException("An established connection was aborted by the software in your host machine.", DisconnectReason.ConnectionLost);
  336. this._sessionErrorOccuredWaitHandle.Set();
  337. }
  338. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  339. {
  340. // If objected is disposed or being disposed don't handle this event
  341. if (this._isDisposed)
  342. return;
  343. this._exception = e.Exception;
  344. this._sessionErrorOccuredWaitHandle.Set();
  345. }
  346. private void Channel_Closed(object sender, ChannelEventArgs e)
  347. {
  348. if (this.OutputStream != null)
  349. {
  350. this.OutputStream.Flush();
  351. }
  352. if (this.ExtendedOutputStream != null)
  353. {
  354. this.ExtendedOutputStream.Flush();
  355. }
  356. this._asyncResult.IsCompleted = true;
  357. if (this._callback != null)
  358. {
  359. // Execute callback on different thread
  360. this.ExecuteThread(() => this._callback(this._asyncResult));
  361. }
  362. ((EventWaitHandle)this._asyncResult.AsyncWaitHandle).Set();
  363. }
  364. private void Channel_RequestReceived(object sender, ChannelRequestEventArgs e)
  365. {
  366. Message replyMessage;
  367. if (e.Info is ExitStatusRequestInfo)
  368. {
  369. var exitStatusInfo = e.Info as ExitStatusRequestInfo;
  370. this.ExitStatus = (int) exitStatusInfo.ExitStatus;
  371. replyMessage = new ChannelSuccessMessage(this._channel.LocalChannelNumber);
  372. }
  373. else
  374. {
  375. replyMessage = new ChannelFailureMessage(this._channel.LocalChannelNumber);
  376. }
  377. if (e.Info.WantReply)
  378. {
  379. this._session.SendMessage(replyMessage);
  380. }
  381. }
  382. private void Channel_ExtendedDataReceived(object sender, ChannelDataEventArgs e)
  383. {
  384. if (this.ExtendedOutputStream != null)
  385. {
  386. this.ExtendedOutputStream.Write(e.Data, 0, e.Data.Length);
  387. this.ExtendedOutputStream.Flush();
  388. }
  389. if (e.DataTypeCode == 1)
  390. {
  391. this._hasError = true;
  392. }
  393. }
  394. private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
  395. {
  396. if (this.OutputStream != null)
  397. {
  398. this.OutputStream.Write(e.Data, 0, e.Data.Length);
  399. this.OutputStream.Flush();
  400. }
  401. if (this._asyncResult != null)
  402. {
  403. lock (this._asyncResult)
  404. {
  405. this._asyncResult.BytesReceived += e.Data.Length;
  406. }
  407. }
  408. }
  409. /// <exception cref="SshOperationTimeoutException">Command '{0}' has timed out.</exception>
  410. /// <remarks>The actual command will be included in the exception message.</remarks>
  411. private void WaitOnHandle(WaitHandle waitHandle)
  412. {
  413. var waitHandles = new[]
  414. {
  415. this._sessionErrorOccuredWaitHandle,
  416. waitHandle
  417. };
  418. switch (WaitHandle.WaitAny(waitHandles, this.CommandTimeout))
  419. {
  420. case 0:
  421. throw this._exception;
  422. case WaitHandle.WaitTimeout:
  423. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Command '{0}' has timed out.", this.CommandText));
  424. }
  425. }
  426. private void UnsubscribeFromEventsAndDisposeChannel()
  427. {
  428. // unsubscribe from events as we do not want to be signaled should these get fired
  429. // during the dispose of the channel
  430. _channel.DataReceived += Channel_DataReceived;
  431. _channel.ExtendedDataReceived += Channel_ExtendedDataReceived;
  432. _channel.RequestReceived += Channel_RequestReceived;
  433. _channel.Closed += Channel_Closed;
  434. // actually dispose the channel
  435. _channel.Dispose();
  436. }
  437. partial void ExecuteThread(Action action);
  438. #region IDisposable Members
  439. private bool _isDisposed;
  440. /// <summary>
  441. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  442. /// </summary>
  443. public void Dispose()
  444. {
  445. Dispose(true);
  446. GC.SuppressFinalize(this);
  447. }
  448. /// <summary>
  449. /// Releases unmanaged and - optionally - managed resources
  450. /// </summary>
  451. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  452. protected virtual void Dispose(bool disposing)
  453. {
  454. // Check to see if Dispose has already been called.
  455. if (!this._isDisposed)
  456. {
  457. // If disposing equals true, dispose all managed
  458. // and unmanaged ResourceMessages.
  459. if (disposing)
  460. {
  461. this._session.Disconnected -= Session_Disconnected;
  462. this._session.ErrorOccured -= Session_ErrorOccured;
  463. // Dispose managed ResourceMessages.
  464. if (this.OutputStream != null)
  465. {
  466. this.OutputStream.Dispose();
  467. this.OutputStream = null;
  468. }
  469. // Dispose managed ResourceMessages.
  470. if (this.ExtendedOutputStream != null)
  471. {
  472. this.ExtendedOutputStream.Dispose();
  473. this.ExtendedOutputStream = null;
  474. }
  475. // Dispose managed ResourceMessages.
  476. if (this._sessionErrorOccuredWaitHandle != null)
  477. {
  478. this._sessionErrorOccuredWaitHandle.Dispose();
  479. this._sessionErrorOccuredWaitHandle = null;
  480. }
  481. // Dispose managed ResourceMessages.
  482. if (this._channel != null)
  483. {
  484. UnsubscribeFromEventsAndDisposeChannel();
  485. this._channel = null;
  486. }
  487. }
  488. // Note disposing has been done.
  489. this._isDisposed = true;
  490. }
  491. }
  492. /// <summary>
  493. /// Releases unmanaged resources and performs other cleanup operations before the
  494. /// <see cref="SshCommand"/> is reclaimed by garbage collection.
  495. /// </summary>
  496. ~SshCommand()
  497. {
  498. // Do not re-create Dispose clean-up code here.
  499. // Calling Dispose(false) is optimal in terms of
  500. // readability and maintainability.
  501. Dispose(false);
  502. }
  503. #endregion
  504. }
  505. }