SshCommand.cs 19 KB

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