SshCommand.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. }
  187. else
  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. }
  192. }
  193. else
  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. return this.Result;
  198. }
  199. /// <summary>
  200. /// Executes command specified by <see cref="CommandText"/> property.
  201. /// </summary>
  202. /// <returns>Command execution result</returns>
  203. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  204. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  205. public string Execute()
  206. {
  207. return this.EndExecute(this.BeginExecute(null, null));
  208. }
  209. /// <summary>
  210. /// Cancels command execution in asynchronous scenarios. CURRENTLY NOT IMPLEMENTED.
  211. /// </summary>
  212. //public void Cancel()
  213. //{
  214. // if (this._channel != null && this._channel.IsOpen)
  215. // {
  216. // //this._channel.SendData(Encoding.ASCII.GetBytes("~."));
  217. // this._channel.SendExecRequest("\0x03");
  218. // //this._channel.SendSignalRequest("ABRT");
  219. // //this._channel.SendSignalRequest("ALRM");
  220. // //this._channel.SendSignalRequest("FPE");
  221. // //this._channel.SendSignalRequest("HUP");
  222. // //this._channel.SendSignalRequest("ILL");
  223. // //this._channel.SendSignalRequest("INT");
  224. // //this._channel.SendSignalRequest("PIPE");
  225. // //this._channel.SendSignalRequest("QUIT");
  226. // //this._channel.SendSignalRequest("SEGV");
  227. // //this._channel.SendSignalRequest("TERM");
  228. // //this._channel.SendSignalRequest("SEGV");
  229. // //this._channel.SendSignalRequest("USR1");
  230. // //this._channel.SendSignalRequest("USR2");
  231. // }
  232. //}
  233. /// <summary>
  234. /// Executes the specified command text.
  235. /// </summary>
  236. /// <param name="commandText">The command text.</param>
  237. /// <returns>Command execution result</returns>
  238. /// <exception cref="Renci.SshNet.Common.SshConnectionException">Client is not connected.</exception>
  239. /// <exception cref="Renci.SshNet.Common.SshOperationTimeoutException">Operation has timed out.</exception>
  240. public string Execute(string commandText)
  241. {
  242. this.CommandText = commandText;
  243. return this.Execute();
  244. }
  245. private void CreateChannel()
  246. {
  247. this._channel = this._session.CreateChannel<ChannelSession>();
  248. this._channel.DataReceived += Channel_DataReceived;
  249. this._channel.ExtendedDataReceived += Channel_ExtendedDataReceived;
  250. this._channel.RequestReceived += Channel_RequestReceived;
  251. this._channel.Closed += Channel_Closed;
  252. // Dispose of streams if already exists
  253. if (this.OutputStream != null)
  254. {
  255. this.OutputStream.Dispose();
  256. this.OutputStream = null;
  257. }
  258. if (this.ExtendedOutputStream != null)
  259. {
  260. this.ExtendedOutputStream.Dispose();
  261. this.ExtendedOutputStream = null;
  262. }
  263. // Initialize output streams and StringBuilders
  264. this.OutputStream = new PipeStream();
  265. this.ExtendedOutputStream = new PipeStream();
  266. this._result = null;
  267. this._error = null;
  268. }
  269. private void Session_Disconnected(object sender, EventArgs e)
  270. {
  271. this._exception = new SshConnectionException("An established connection was aborted by the software in your host machine.", DisconnectReason.ConnectionLost);
  272. this._sessionErrorOccuredWaitHandle.Set();
  273. }
  274. private void Session_ErrorOccured(object sender, ErrorEventArgs e)
  275. {
  276. this._exception = e.GetException();
  277. this._sessionErrorOccuredWaitHandle.Set();
  278. }
  279. private void Channel_Closed(object sender, Common.ChannelEventArgs e)
  280. {
  281. if (this.OutputStream != null)
  282. {
  283. this.OutputStream.Flush();
  284. }
  285. if (this.ExtendedOutputStream != null)
  286. {
  287. this.ExtendedOutputStream.Flush();
  288. }
  289. this._asyncResult.IsCompleted = true;
  290. if (this._callback != null)
  291. {
  292. // Execute callback on different thread
  293. Task.Factory.StartNew(() => { this._callback(this._asyncResult); });
  294. }
  295. ((EventWaitHandle)this._asyncResult.AsyncWaitHandle).Set();
  296. }
  297. private void Channel_RequestReceived(object sender, Common.ChannelRequestEventArgs e)
  298. {
  299. Message replyMessage = new ChannelFailureMessage(this._channel.LocalChannelNumber);
  300. if (e.Info is ExitStatusRequestInfo)
  301. {
  302. ExitStatusRequestInfo exitStatusInfo = e.Info as ExitStatusRequestInfo;
  303. this.ExitStatus = (int)exitStatusInfo.ExitStatus;
  304. replyMessage = new ChannelSuccessMessage(this._channel.LocalChannelNumber);
  305. }
  306. if (e.Info.WantReply)
  307. {
  308. this._session.SendMessage(replyMessage);
  309. }
  310. }
  311. private void Channel_ExtendedDataReceived(object sender, Common.ChannelDataEventArgs e)
  312. {
  313. if (this.ExtendedOutputStream != null)
  314. {
  315. this.ExtendedOutputStream.Write(e.Data, 0, e.Data.Length);
  316. this.ExtendedOutputStream.Flush();
  317. }
  318. if (e.DataTypeCode == 1)
  319. {
  320. this._hasError = true;
  321. }
  322. }
  323. private void Channel_DataReceived(object sender, Common.ChannelDataEventArgs e)
  324. {
  325. if (this.OutputStream != null)
  326. {
  327. this.OutputStream.Write(e.Data, 0, e.Data.Length);
  328. //this._outputSteamWriter.Write(this._encoding.GetString(e.Data, 0, e.Data.Length));
  329. this.OutputStream.Flush();
  330. }
  331. if (this._asyncResult != null)
  332. {
  333. lock (this._asyncResult)
  334. {
  335. this._asyncResult.BytesReceived += e.Data.Length;
  336. }
  337. }
  338. }
  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. #region IDisposable Members
  358. private bool _isDisposed = false;
  359. /// <summary>
  360. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged ResourceMessages.
  361. /// </summary>
  362. public void Dispose()
  363. {
  364. Dispose(true);
  365. GC.SuppressFinalize(this);
  366. }
  367. /// <summary>
  368. /// Releases unmanaged and - optionally - managed resources
  369. /// </summary>
  370. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  371. protected virtual void Dispose(bool disposing)
  372. {
  373. // Check to see if Dispose has already been called.
  374. if (!this._isDisposed)
  375. {
  376. // If disposing equals true, dispose all managed
  377. // and unmanaged ResourceMessages.
  378. if (disposing)
  379. {
  380. this._session.Disconnected -= Session_Disconnected;
  381. this._session.ErrorOccured -= Session_ErrorOccured;
  382. // Dispose managed ResourceMessages.
  383. if (this.OutputStream != null)
  384. {
  385. this.OutputStream.Dispose();
  386. this.OutputStream = null;
  387. }
  388. // Dispose managed ResourceMessages.
  389. if (this.ExtendedOutputStream != null)
  390. {
  391. this.ExtendedOutputStream.Dispose();
  392. this.ExtendedOutputStream = null;
  393. }
  394. // Dispose managed ResourceMessages.
  395. if (this._sessionErrorOccuredWaitHandle != null)
  396. {
  397. this._sessionErrorOccuredWaitHandle.Dispose();
  398. this._sessionErrorOccuredWaitHandle = null;
  399. }
  400. // Dispose managed ResourceMessages.
  401. if (this._channel != null)
  402. {
  403. this._channel.DataReceived -= Channel_DataReceived;
  404. this._channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
  405. this._channel.RequestReceived -= Channel_RequestReceived;
  406. this._channel.Closed -= Channel_Closed;
  407. this._channel.Dispose();
  408. this._channel = null;
  409. }
  410. }
  411. // Note disposing has been done.
  412. this._isDisposed = true;
  413. }
  414. }
  415. /// <summary>
  416. /// Releases unmanaged resources and performs other cleanup operations before the
  417. /// <see cref="SshCommand"/> is reclaimed by garbage collection.
  418. /// </summary>
  419. ~SshCommand()
  420. {
  421. // Do not re-create Dispose clean-up code here.
  422. // Calling Dispose(false) is optimal in terms of
  423. // readability and maintainability.
  424. Dispose(false);
  425. }
  426. #endregion
  427. }
  428. }