SshCommand.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Renci.SshNet.Channels;
  8. using Renci.SshNet.Common;
  9. using Renci.SshNet.Messages;
  10. using Renci.SshNet.Messages.Connection;
  11. using Renci.SshNet.Messages.Transport;
  12. using System.Globalization;
  13. namespace Renci.SshNet
  14. {
  15. /// <summary>
  16. /// Represents SSH command that can be executed.
  17. /// </summary>
  18. public class SshCommand : IDisposable
  19. {
  20. private Encoding _encoding;
  21. private Session _session;
  22. private ChannelSession _channel;
  23. private CommandAsyncResult _asyncResult;
  24. private AsyncCallback _callback;
  25. private EventWaitHandle _sessionErrorOccuredWaitHandle = new AutoResetEvent(false);
  26. private Exception _exception;
  27. private bool _hasError;
  28. private object _endExecuteLock = new object();
  29. /// <summary>
  30. /// Gets the command text.
  31. /// </summary>
  32. public string CommandText { get; private set; }
  33. /// <summary>
  34. /// Gets or sets the command timeout.
  35. /// </summary>
  36. /// <value>
  37. /// The command timeout.
  38. /// </value>
  39. public TimeSpan CommandTimeout { get; set; }
  40. /// <summary>
  41. /// Gets the command exit status.
  42. /// </summary>
  43. public int ExitStatus { get; private set; }
  44. /// <summary>
  45. /// Gets the output stream.
  46. /// </summary>
  47. public Stream OutputStream { get; private set; }
  48. /// <summary>
  49. /// Gets the extended output stream.
  50. /// </summary>
  51. public Stream ExtendedOutputStream { get; private set; }
  52. private StringBuilder _result;
  53. /// <summary>
  54. /// Gets the command execution result.
  55. /// </summary>
  56. public string Result
  57. {
  58. get
  59. {
  60. if (this._result == null)
  61. {
  62. this._result = new StringBuilder();
  63. }
  64. if (this.OutputStream != null && this.OutputStream.Length > 0)
  65. {
  66. using (var sr = new StreamReader(this.OutputStream, this._encoding))
  67. {
  68. this._result.Append(sr.ReadToEnd());
  69. }
  70. }
  71. return this._result.ToString();
  72. }
  73. }
  74. private StringBuilder _error;
  75. /// <summary>
  76. /// Gets the command execution error.
  77. /// </summary>
  78. public string Error
  79. {
  80. get
  81. {
  82. if (this._hasError)
  83. {
  84. if (this._error == null)
  85. {
  86. this._error = new StringBuilder();
  87. }
  88. if (this.ExtendedOutputStream != null && this.ExtendedOutputStream.Length > 0)
  89. {
  90. using (var sr = new StreamReader(this.ExtendedOutputStream, this._encoding))
  91. {
  92. this._error.Append(sr.ReadToEnd());
  93. }
  94. }
  95. return this._error.ToString();
  96. }
  97. else
  98. return string.Empty;
  99. }
  100. }
  101. /// <summary>
  102. /// Initializes a new instance of the <see cref="SshCommand"/> class.
  103. /// </summary>
  104. /// <param name="session">The session.</param>
  105. /// <param name="commandText">The command text.</param>
  106. /// <param name="encoding">The encoding.</param>
  107. internal SshCommand(Session session, string commandText, Encoding encoding)
  108. {
  109. if (session == null)
  110. throw new ArgumentNullException("session");
  111. this._encoding = encoding;
  112. this._session = session;
  113. this.CommandText = commandText;
  114. this.CommandTimeout = new TimeSpan(0, 0, 0, 0, -1);
  115. this._session.Disconnected += Session_Disconnected;
  116. this._session.ErrorOccured += Session_ErrorOccured;
  117. }
  118. /// <summary>
  119. /// Begins an asynchronous command execution.
  120. /// </summary>
  121. /// <param name="callback">An optional asynchronous callback, to be called when the command execution is complete.</param>
  122. /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param>
  123. /// <returns>An <see cref="System.IAsyncResult"/> that represents the asynchronous command execution, which could still be pending.</returns>
  124. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  125. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  126. public IAsyncResult BeginExecute(AsyncCallback callback, object state)
  127. {
  128. // Prevent from executing BeginExecute before calling EndExecute
  129. if (this._asyncResult != null)
  130. {
  131. throw new InvalidOperationException("Asynchronous operation is already in progress.");
  132. }
  133. // Create new AsyncResult object
  134. this._asyncResult = new CommandAsyncResult(this)
  135. {
  136. AsyncWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset),
  137. IsCompleted = false,
  138. AsyncState = state,
  139. };
  140. // When command re-executed again, create a new channel
  141. if (this._channel != null)
  142. {
  143. throw new SshException("Invalid operation.");
  144. }
  145. this.CreateChannel();
  146. if (string.IsNullOrEmpty(this.CommandText))
  147. throw new ArgumentException("CommandText property is empty.");
  148. this._callback = callback;
  149. this._channel.Open();
  150. // Send channel command request
  151. this._channel.SendExecRequest(this.CommandText);
  152. return _asyncResult;
  153. }
  154. /// <summary>
  155. /// Begins an asynchronous command execution.
  156. /// </summary>
  157. /// <param name="commandText">The command text.</param>
  158. /// <param name="callback">An optional asynchronous callback, to be called when the command execution is complete.</param>
  159. /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param>
  160. /// <returns>An <see cref="System.IAsyncResult"/> that represents the asynchronous command execution, which could still be pending.</returns>
  161. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  162. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  163. public IAsyncResult BeginExecute(string commandText, AsyncCallback callback, object state)
  164. {
  165. this.CommandText = commandText;
  166. return BeginExecute(callback, state);
  167. }
  168. /// <summary>
  169. /// Waits for the pending asynchronous command execution to complete.
  170. /// </summary>
  171. /// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param>
  172. /// <returns></returns>
  173. public string EndExecute(IAsyncResult asyncResult)
  174. {
  175. if (this._asyncResult == asyncResult && this._asyncResult != null)
  176. {
  177. lock (this._endExecuteLock)
  178. {
  179. if (this._asyncResult != null)
  180. {
  181. // Make sure that operation completed if not wait for it to finish
  182. this.WaitHandle(this._asyncResult.AsyncWaitHandle);
  183. this._channel.Close();
  184. this._channel = null;
  185. this._asyncResult = null;
  186. return this.Result;
  187. }
  188. }
  189. }
  190. 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.");
  191. }
  192. /// <summary>
  193. /// Executes command specified by <see cref="CommandText"/> property.
  194. /// </summary>
  195. /// <returns>Command execution result</returns>
  196. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  197. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  198. public string Execute()
  199. {
  200. return this.EndExecute(this.BeginExecute(null, null));
  201. }
  202. /// <summary>
  203. /// Cancels command execution in asynchronous scenarios. CURRENTLY NOT IMPLEMENTED.
  204. /// </summary>
  205. //public void Cancel()
  206. //{
  207. // if (this._channel != null && this._channel.IsOpen)
  208. // {
  209. // //this._channel.SendData(Encoding.ASCII.GetBytes("~."));
  210. // this._channel.SendExecRequest("\0x03");
  211. // //this._channel.SendSignalRequest("ABRT");
  212. // //this._channel.SendSignalRequest("ALRM");
  213. // //this._channel.SendSignalRequest("FPE");
  214. // //this._channel.SendSignalRequest("HUP");
  215. // //this._channel.SendSignalRequest("ILL");
  216. // //this._channel.SendSignalRequest("INT");
  217. // //this._channel.SendSignalRequest("PIPE");
  218. // //this._channel.SendSignalRequest("QUIT");
  219. // //this._channel.SendSignalRequest("SEGV");
  220. // //this._channel.SendSignalRequest("TERM");
  221. // //this._channel.SendSignalRequest("SEGV");
  222. // //this._channel.SendSignalRequest("USR1");
  223. // //this._channel.SendSignalRequest("USR2");
  224. // }
  225. //}
  226. /// <summary>
  227. /// Executes the specified command text.
  228. /// </summary>
  229. /// <param name="commandText">The command text.</param>
  230. /// <returns>Command execution result</returns>
  231. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  232. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  233. public string Execute(string commandText)
  234. {
  235. this.CommandText = commandText;
  236. return this.Execute();
  237. }
  238. private void CreateChannel()
  239. {
  240. this._channel = this._session.CreateChannel<ChannelSession>();
  241. this._channel.DataReceived += Channel_DataReceived;
  242. this._channel.ExtendedDataReceived += Channel_ExtendedDataReceived;
  243. this._channel.RequestReceived += Channel_RequestReceived;
  244. this._channel.Closed += Channel_Closed;
  245. // Dispose of streams if already exists
  246. if (this.OutputStream != null)
  247. {
  248. this.OutputStream.Dispose();
  249. this.OutputStream = null;
  250. }
  251. if (this.ExtendedOutputStream != null)
  252. {
  253. this.ExtendedOutputStream.Dispose();
  254. this.ExtendedOutputStream = null;
  255. }
  256. // Initialize output streams and StringBuilders
  257. this.OutputStream = new PipeStream();
  258. this.ExtendedOutputStream = new PipeStream();
  259. this._result = null;
  260. this._error = null;
  261. }
  262. private void Session_Disconnected(object sender, EventArgs e)
  263. {
  264. this._exception = new SshConnectionException("An established connection was aborted by the software in your host machine.", DisconnectReason.ConnectionLost);
  265. this._sessionErrorOccuredWaitHandle.Set();
  266. }
  267. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  268. {
  269. this._exception = e.Exception;
  270. this._sessionErrorOccuredWaitHandle.Set();
  271. }
  272. private void Channel_Closed(object sender, Common.ChannelEventArgs e)
  273. {
  274. if (this.OutputStream != null)
  275. {
  276. this.OutputStream.Flush();
  277. }
  278. if (this.ExtendedOutputStream != null)
  279. {
  280. this.ExtendedOutputStream.Flush();
  281. }
  282. this._asyncResult.IsCompleted = true;
  283. if (this._callback != null)
  284. {
  285. // Execute callback on different thread
  286. Task.Factory.StartNew(() => { this._callback(this._asyncResult); });
  287. }
  288. ((EventWaitHandle)this._asyncResult.AsyncWaitHandle).Set();
  289. }
  290. private void Channel_RequestReceived(object sender, Common.ChannelRequestEventArgs e)
  291. {
  292. Message replyMessage = new ChannelFailureMessage(this._channel.LocalChannelNumber);
  293. if (e.Info is ExitStatusRequestInfo)
  294. {
  295. ExitStatusRequestInfo exitStatusInfo = e.Info as ExitStatusRequestInfo;
  296. this.ExitStatus = (int)exitStatusInfo.ExitStatus;
  297. replyMessage = new ChannelSuccessMessage(this._channel.LocalChannelNumber);
  298. }
  299. if (e.Info.WantReply)
  300. {
  301. this._session.SendMessage(replyMessage);
  302. }
  303. }
  304. private void Channel_ExtendedDataReceived(object sender, Common.ChannelDataEventArgs e)
  305. {
  306. if (this.ExtendedOutputStream != null)
  307. {
  308. this.ExtendedOutputStream.Write(e.Data, 0, e.Data.Length);
  309. this.ExtendedOutputStream.Flush();
  310. }
  311. if (e.DataTypeCode == 1)
  312. {
  313. this._hasError = true;
  314. }
  315. }
  316. private void Channel_DataReceived(object sender, Common.ChannelDataEventArgs e)
  317. {
  318. if (this.OutputStream != null)
  319. {
  320. this.OutputStream.Write(e.Data, 0, e.Data.Length);
  321. //this._outputSteamWriter.Write(this._encoding.GetString(e.Data, 0, e.Data.Length));
  322. this.OutputStream.Flush();
  323. }
  324. if (this._asyncResult != null)
  325. {
  326. lock (this._asyncResult)
  327. {
  328. this._asyncResult.BytesReceived += e.Data.Length;
  329. }
  330. }
  331. }
  332. private void WaitHandle(WaitHandle waitHandle)
  333. {
  334. var waitHandles = new WaitHandle[]
  335. {
  336. this._sessionErrorOccuredWaitHandle,
  337. waitHandle,
  338. };
  339. var index = EventWaitHandle.WaitAny(waitHandles, this.CommandTimeout);
  340. if (index < 1)
  341. {
  342. throw this._exception;
  343. }
  344. else if (index > 1)
  345. {
  346. // throw time out error
  347. throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Command '{0}' has timed out.", this.CommandText));
  348. }
  349. }
  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. }