This project is read-only.

SshCommand.Execute with STDIN support

Nov 25, 2014 at 12:09 PM
Hi,

I am using your library for a while already. You did it well, and for me Renci.SshNet is the best ssh library for .NET.

In one of our last projects there was a new requirement: Calling some Linux commands through ssh expecting data from stdin.

SshCommand.Execute or SshCommand.BeginExecute allow command line parameters, but no data for stdin. With a small change it was easy to add support for stdin data:
public partial class SshCommand : IDisposable
{
...

        /* [BEGIN PATCH] */
        /// <summary>
        /// Gets the command stdin data.
        /// </summary>
        public string CommandStdin { get; private set; }
        /* [END PATCH] */

...

        public IAsyncResult BeginExecute(AsyncCallback callback, object state)
        {
            //  Prevent from executing BeginExecute before calling EndExecute
            if (this._asyncResult != null)
            {
                throw new InvalidOperationException("Asynchronous operation is already in progress.");
            }

            //  Create new AsyncResult object
            this._asyncResult = new CommandAsyncResult(this)
            {
                AsyncWaitHandle = new ManualResetEvent(false),
                IsCompleted = false,
                AsyncState = state,
            };

            //  When command re-executed again, create a new channel
            if (this._channel != null)
            {
                throw new SshException("Invalid operation.");
            }

            this.CreateChannel();

            if (string.IsNullOrEmpty(this.CommandText))
                throw new ArgumentException("CommandText property is empty.");

            this._callback = callback;

            this._channel.Open();

            //  Send channel command request
            this._channel.SendExecRequest(this.CommandText);

            /* [BEGIN PATCH] */
            //  Send data to command stdin
            if (!string.IsNullOrEmpty(this.CommandStdin))
            {
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(this.CommandStdin);
                this._channel.SendData(bytes);
            }

            //  Send EOF to signal that there will be no data for stdin anymore
            this._channel.SendEof();
            /* [END PATCH] */

            return _asyncResult;
        }
}
It works already great for us, but it would be cool to have this feature in one of your official releases in the future. What do you think?

If necessary, I can upload the patch based on the version 2014.4.6-beta1. But I think you know best how to implement and integrate that feature into your interface design.

Thank you.
Dec 3, 2014 at 6:34 PM
Thanks for sharing this information.
Very useful to me.

Codeplex team,
My sincere request to add this into your next release. it will be useful to most of this library users.

Regds
Hari