SshCommand.cs 24 KB

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