SshCommand.cs 24 KB

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