SshCommand.cs 19 KB

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