Home > Software design >  How to pass values to shell script executed using the SSH.NET library in C#?
How to pass values to shell script executed using the SSH.NET library in C#?

Time:12-16

Is it possible to use the SSH.NET library to run a script that is saved on the device, that I would make the SSH connection with?

My script would need me to input some variables. Is that also possible through the C# code?

My code here lets me connect to the device and run commands. I just don't know how to make it so that I can interact with the script.

// Execute a (SHELL) Command - prepare upload directory
using (var sshclient = new SshClient(ConnNfo))
{
    sshclient.Connect();
    using (var cmd = sshclient.CreateCommand("cd /data/scripts/ && sh funk1.sh"))
    {
        cmd.Execute();
        Console.WriteLine("Command>"   cmd.CommandText);
        Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
    }
    sshclient.Disconnect();
}

CodePudding user response:

Yes, it is possible to use the SSH.NET library to run a script on a remote device using C#. The code you provided creates a SshClient instance and connects to the remote device using the Connect() method. To run a script on the remote device, you can use the CreateCommand() method to create a command that invokes the script, and then call the Execute() method to run the command.

For example, if your script is named myscript.sh and is located in the /data/scripts/ directory on the remote device, you can use the following code to run the script:

using (var cmd = sshclient.CreateCommand("cd /data/scripts/ && sh myscript.sh"))
{
    cmd.Execute();
    Console.WriteLine("Command>"   cmd.CommandText);
    Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
}

If your script requires input variables, you can pass them as arguments to the sh command, like this:

using (var cmd = sshclient.CreateCommand("cd /data/scripts/ && sh myscript.sh arg1 arg2 arg3"))
{
    cmd.Execute();
    Console.WriteLine("Command>"   cmd.CommandText);
    Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
}

You can then access the input variables in your script using the $1, $2, and $3 variables, which correspond to the first, second, and third arguments passed to the script, respectively.

  • Related