SshCommand.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using Renci.SshNet.Channels;
  7. using Renci.SshNet.Common;
  8. using Renci.SshNet.Messages;
  9. using Renci.SshNet.Messages.Connection;
  10. using Renci.SshNet.Messages.Transport;
  11. using System.Globalization;
  12. namespace Renci.SshNet
  13. {
  14. /// <summary>
  15. /// Represents SSH command that can be executed.
  16. /// </summary>
  17. public partial class SshCommand : IDisposable
  18. {
  19. private Encoding _encoding;
  20. private Session _session;
  21. private ChannelSession _channel;
  22. private CommandAsyncResult _asyncResult;
  23. private AsyncCallback _callback;
  24. private EventWaitHandle _sessionErrorOccuredWaitHandle = new AutoResetEvent(false);
  25. private Exception _exception;
  26. private bool _hasError;
  27. private object _endExecuteLock = new object();
  28. /// <summary>
  29. /// Gets the command text.
  30. /// </summary>
  31. public string CommandText { get; private set; }
  32. /// <summary>
  33. /// Gets or sets the command timeout.
  34. /// </summary>
  35. /// <value>
  36. /// The command timeout.
  37. /// </value>
  38. /// <example>
  39. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Execute CommandTimeout" language="C#" title="Specify command execution timeout" />
  40. /// </example>
  41. public TimeSpan CommandTimeout { get; set; }
  42. /// <summary>
  43. /// Gets the command exit status.
  44. /// </summary>
  45. /// <example>
  46. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand RunCommand ExitStatus" language="C#" title="Get command execution exit status" />
  47. /// </example>
  48. public int ExitStatus { get; private set; }
  49. /// <summary>
  50. /// Gets the output stream.
  51. /// </summary>
  52. /// <example>
  53. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Execute OutputStream" language="C#" title="Use OutputStream to get command execution output" />
  54. /// </example>
  55. public Stream OutputStream { get; private set; }
  56. /// <summary>
  57. /// Gets the extended output stream.
  58. /// </summary>
  59. /// <example>
  60. /// <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" />
  61. /// </example>
  62. public Stream ExtendedOutputStream { get; private set; }
  63. private StringBuilder _result;
  64. /// <summary>
  65. /// Gets the command execution result.
  66. /// </summary>
  67. /// <example>
  68. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand RunCommand Result" language="C#" title="Running simple command" />
  69. /// </example>
  70. public string Result
  71. {
  72. get
  73. {
  74. if (this._result == null)
  75. {
  76. this._result = new StringBuilder();
  77. }
  78. if (this.OutputStream != null && this.OutputStream.Length > 0)
  79. {
  80. using (var sr = new StreamReader(this.OutputStream, this._encoding))
  81. {
  82. this._result.Append(sr.ReadToEnd());
  83. }
  84. }
  85. return this._result.ToString();
  86. }
  87. }
  88. private StringBuilder _error;
  89. /// <summary>
  90. /// Gets the command execution error.
  91. /// </summary>
  92. /// <example>
  93. /// <code source="..\..\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand CreateCommand Error" language="C#" title="Display command execution error" />
  94. /// </example>
  95. public string Error
  96. {
  97. get
  98. {
  99. if (this._hasError)
  100. {
  101. if (this._error == null)
  102. {
  103. this._error = new StringBuilder();
  104. }
  105. if (this.ExtendedOutputStream != null && this.ExtendedOutputStream.Length > 0)
  106. {
  107. using (var sr = new StreamReader(this.ExtendedOutputStream, this._encoding))
  108. {
  109. this._error.Append(sr.ReadToEnd());
  110. }
  111. }
  112. return this._error.ToString();
  113. }
  114. else
  115. return string.Empty;
  116. }
  117. }
  118. /// <summary>
  119. /// Initializes a new instance of the <see cref="SshCommand"/> class.
  120. /// </summary>
  121. /// <param name="session">The session.</param>
  122. /// <param name="commandText">The command text.</param>
  123. /// <param name="encoding">The encoding.</param>
  124. /// <exception cref="ArgumentNullException">Either <paramref name="session"/>, <paramref name="commandText"/> or <paramref name="encoding"/> is null.</exception>
  125. internal SshCommand(Session session, string commandText, Encoding encoding)
  126. {
  127. if (session == null)
  128. throw new ArgumentNullException("session");
  129. if (commandText == null)
  130. throw new ArgumentNullException("commandText");
  131. this._encoding = encoding;
  132. this._session = session;
  133. this.CommandText = commandText;
  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(this)
  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. 22
  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="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>
  244. /// <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>
  245. public string EndExecute(IAsyncResult asyncResult)
  246. {
  247. if (this._asyncResult == asyncResult && this._asyncResult != null)
  248. {
  249. lock (this._endExecuteLock)
  250. {
  251. if (this._asyncResult != null)
  252. {
  253. // Make sure that operation completed if not wait for it to finish
  254. this.WaitHandle(this._asyncResult.AsyncWaitHandle);
  255. if (this._channel.IsOpen)
  256. {
  257. this._channel.SendEof();
  258. this._channel.Close();
  259. }
  260. this._channel = null;
  261. this._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. 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.CreateChannel<ChannelSession>();
  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, Common.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, Common.ChannelRequestEventArgs e)
  364. {
  365. Message replyMessage = new ChannelFailureMessage(this._channel.LocalChannelNumber);
  366. if (e.Info is ExitStatusRequestInfo)
  367. {
  368. ExitStatusRequestInfo exitStatusInfo = e.Info as ExitStatusRequestInfo;
  369. this.ExitStatus = (int)exitStatusInfo.ExitStatus;
  370. replyMessage = new ChannelSuccessMessage(this._channel.LocalChannelNumber);
  371. }
  372. if (e.Info.WantReply)
  373. {
  374. this._session.SendMessage(replyMessage);
  375. }
  376. }
  377. private void Channel_ExtendedDataReceived(object sender, Common.ChannelDataEventArgs e)
  378. {
  379. if (this.ExtendedOutputStream != null)
  380. {
  381. this.ExtendedOutputStream.Write(e.Data, 0, e.Data.Length);
  382. this.ExtendedOutputStream.Flush();
  383. }
  384. if (e.DataTypeCode == 1)
  385. {
  386. this._hasError = true;
  387. }
  388. }
  389. private void Channel_DataReceived(object sender, Common.ChannelDataEventArgs e)
  390. {
  391. if (this.OutputStream != null)
  392. {
  393. this.OutputStream.Write(e.Data, 0, e.Data.Length);
  394. this.OutputStream.Flush();
  395. }
  396. if (this._asyncResult != null)
  397. {
  398. lock (this._asyncResult)
  399. {
  400. this._asyncResult.BytesReceived += e.Data.Length;
  401. }
  402. }
  403. }
  404. /// <exception cref="SshOperationTimeoutException">Command '{0}' has timed out.</exception>
  405. /// <remarks>The actual command will be included in the exception message.</remarks>
  406. private void WaitHandle(WaitHandle waitHandle)
  407. {
  408. var waitHandles = new WaitHandle[]
  409. {
  410. this._sessionErrorOccuredWaitHandle,
  411. waitHandle,
  412. };
  413. switch (EventWaitHandle.WaitAny(waitHandles, this.CommandTimeout))
  414. {
  415. case 0:
  416. throw this._exception;
  417. case System.Threading.WaitHandle.WaitTimeout:
  418. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Command '{0}' has timed out.", this.CommandText));
  419. default:
  420. break;
  421. }
  422. }
  423. partial void ExecuteThread(Action action);
  424. #region IDisposable Members
  425. private bool _isDisposed = false;
  426. /// <summary>
  427. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  428. /// </summary>
  429. public void Dispose()
  430. {
  431. Dispose(true);
  432. GC.SuppressFinalize(this);
  433. }
  434. /// <summary>
  435. /// Releases unmanaged and - optionally - managed resources
  436. /// </summary>
  437. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  438. protected virtual void Dispose(bool disposing)
  439. {
  440. // Check to see if Dispose has already been called.
  441. if (!this._isDisposed)
  442. {
  443. // If disposing equals true, dispose all managed
  444. // and unmanaged ResourceMessages.
  445. if (disposing)
  446. {
  447. this._session.Disconnected -= Session_Disconnected;
  448. this._session.ErrorOccured -= Session_ErrorOccured;
  449. // Dispose managed ResourceMessages.
  450. if (this.OutputStream != null)
  451. {
  452. this.OutputStream.Dispose();
  453. this.OutputStream = null;
  454. }
  455. // Dispose managed ResourceMessages.
  456. if (this.ExtendedOutputStream != null)
  457. {
  458. this.ExtendedOutputStream.Dispose();
  459. this.ExtendedOutputStream = null;
  460. }
  461. // Dispose managed ResourceMessages.
  462. if (this._sessionErrorOccuredWaitHandle != null)
  463. {
  464. this._sessionErrorOccuredWaitHandle.Dispose();
  465. this._sessionErrorOccuredWaitHandle = null;
  466. }
  467. // Dispose managed ResourceMessages.
  468. if (this._channel != null)
  469. {
  470. this._channel.DataReceived -= Channel_DataReceived;
  471. this._channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
  472. this._channel.RequestReceived -= Channel_RequestReceived;
  473. this._channel.Closed -= Channel_Closed;
  474. this._channel.Dispose();
  475. this._channel = null;
  476. }
  477. }
  478. // Note disposing has been done.
  479. this._isDisposed = true;
  480. }
  481. }
  482. /// <summary>
  483. /// Releases unmanaged resources and performs other cleanup operations before the
  484. /// <see cref="SshCommand"/> is reclaimed by garbage collection.
  485. /// </summary>
  486. ~SshCommand()
  487. {
  488. // Do not re-create Dispose clean-up code here.
  489. // Calling Dispose(false) is optimal in terms of
  490. // readability and maintainability.
  491. Dispose(false);
  492. }
  493. #endregion
  494. }
  495. }