0

I tried the below code to execute command in Task.Run.

SshClient ssh;
    public Form1()
    {
    InitializeComponent();

//BackGround Login is needed.
ConnectionInfo info = new ConnectionInfo(hostNameOrIpAddr, portNo, userName,
    new AuthenticationMethod[] {
    new PasswordAuthenticationMethod(userName, passWord)
ssh = new SshClient(info);
ssh.Connect();
cmd = ssh.CreateCommand(commandString);
    }

private void button1_Click(object sender, EventArgs e)
{
Task.Run(()=>{
SshCommand cmd = ssh.CreateCommand(commandString);
cmd.Execute();
Console.WriteLine(cmd.Result.ToString());
;});
}

But it doesn't work well. The reason is probably to Dispose the stream immediatly after starting the task.

Yur
  • 11
  • 2
  • 3
  • 2
    Hey @yur and welcome to StackOverflow. Please format your code to improve readability which will in turn improve the chance that someone will answer your question :) Also please be more specific about "...it doesn't work well." What are you expecting to happen and what is happening? – Francois du Plessis Jun 22 '20 at 13:32
  • You want to Asynchronous Receive to capture data. See following : https://stackoverflow.com/questions/48808074/c-sharp-ssh-net-asynchronous-command-read-and-write – jdweng Jun 22 '20 at 13:37
  • your code does not compile – Mike Jun 22 '20 at 13:56
  • my bet is maybe your server is requiring a captcha of sorts about press a key or something and its stopping automated connections from finishing normally. So you might have to first interact with it as a shell stream and then send your commands. – Carter Jun 22 '20 at 15:40

1 Answers1

0

One of the ways to use async/await is as following:

Note: The async keyword turns a method into an async method, which allows you to use the await keyword in its body.

private async void button1_Click(object sender, EventArgs e) {
    var result = await Task.Run(() => RunSshCmd());
    Console.WriteLine(result);
}

Let's say running ssh command will take 5 seconds to finish, just example.

private string RunSshCmd() {       
    Thread.Sleep(5000);
    return "Done.";
}

Note: await can only be used inside an async method.

Abdulrazzaq Alzayed
  • 1,613
  • 1
  • 11
  • 15