0

I'm trying to run a command on a remote server via SSH.

I need the output of the command that is run to be saved in a file on that remote server.

I've been attempting to this the following way

// ssh is the SshClient which is already set up
ssh.Connect();
ssh.RunCommand("echo 1 > C:\test.csv"); //Doesn't create a file
ssh.Disconnect();

Why doesn't this work with SSH.NET? If I run this via putty using the same credentials it works perfectly fine.

EDIT (Working Code):

I did some more playing around and have found the following to work:

// ssh is the SshClient which is already set up
ssh.Connect();
var shell = ssh.CreateShellStream("cmd.exe", 80, 24, 800, 600, 1024);
var reader = new StreamReader(shell);
var writer = new StreamWriter(shell);
writer.AutoFlush = true;

while (!shell.DataAvailable)
    System.Threading.Thread.Sleep(1000); //This wait period seems required

writer.WriteLine("echo 1 > C:\test.csv");

while (!shell.DataAvailable)
    System.Threading.Thread.Sleep(1000); //This wait period seems required

ssh.Disconnect();

While that works I still don't understand what's really happening here. Could someone explain?

1 Answer 1

4

Try this function: Just save the result to a variable or write the result using StreamWriter

private void writeMe()
{
    using (StreamWriter sw = new StreamWriter(filename)
    {
        string result = eSshCom(command);
        sw.WriteLine(result);
    } 
} 



private string eSshCom(string getCommand)
            {
            this.res = "";

            var connectionInfo = new KeyboardInteractiveConnectionInfo(ipaddress, 22, username);

            connectionInfo.AuthenticationPrompt += delegate(object asender, AuthenticationPromptEventArgs xe)
            {
                foreach (var prompt in xe.Prompts)
                    {
                    if (prompt.Request.Equals("Password: ", StringComparison.InvariantCultureIgnoreCase))
                        {
                        prompt.Response = password;
                        }
                    }
            };

            using (var ssh = new SshClient(connectionInfo))
                {
                    ssh.Connect();
                    var cmd = ssh.RunCommand(getCommand);
                    this.res = cmd.Result;
                    ssh.Disconnect();

                }
            return this.res;
            }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the input, I took bits of it and made it work for my code. I still don't really understand why it doesn't work though.
If it helps kindly give the answers an upvote for appreciation. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.