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?
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;
}