Ssh.net c # runcommand problem
I am using Renci.SshNet in C # in 3.5 framework and run command in unix box like below.
string host = "localhost";
string user = "user";
string pass = "1234";
SshClient ssh = new SshClient(host, user, pass);
using (var client = new SshClient(host, user, pass))
{
client.Connect();
var terminal = client.RunCommand("/bin/run.sh");
var output = terminal.Result;
txtResult.Text = output;
client.Disconnect();
}
everything works well, my question here is "Is there a way it shouldn't wait for the client. RunCommand should be finished." My program doesn't need to exit unix, and so I don't want to wait for RunCommand to finish. This command took 2 hours to complete, so I wanted to avoid this timeout in my application.
source to share
As I suppose SSH.NET doesn't detect the true async api, you can queue RunCommand
on the threadpool:
public void ExecuteCommandOnThreadPool()
{
string host = "localhost";
string user = "user";
string pass = "1234";
Action runCommand = () =>
{
SshClient client = new SshClient(host, user, pass);
try
{
client.Connect();
var terminal = client.RunCommand("/bin/run.sh");
txtResult.Text = terminal.Result;
}
finally
{
client.Disconnect();
client.Dispose();
}
};
ThreadPool.QueueUserWorkItem(x => runCommand());
}
}
Note that if you are using this inside WPF or WinForms, you need txtResult.Text = terminal.Result
with Dispatcher.Invoke
or Control.Invoke
respectively.
source to share
What about
public static string Command(string command)
{
var cmd = CurrentTunnel.CreateCommand(command); // very long list
var asynch = cmd.BeginExecute(
//delegate { if (Core.IsDeveloper) Console.WriteLine("Command executed: {0}", command); }, null
);
cmd.EndExecute(asynch);
if (cmd.Error.HasValue())
{
switch (cmd.Error) {
//case "warning: screen width 0 suboptimal.\n" => add "export COLUMNS=300;" to command
default: MessageBox.Show(cmd.Error); break;
}
}
return cmd.Result;
}
source to share