SshCommand.cs 19 KB

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