Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - Providing subcommands to a command (sudo/su) executed with SSH.NET SshClient.CreateShellStream

I am trying to use Renci SSH.NET to connect to a remote Linux server from a C# web application and execute shell scripts. I want to run the scripts one after another. But not getting how to run the scripts and read the output and store it in a label. I have tried the below code, but not able to pass multiple commands one line after another.

SshClient sshclient = new SshClient("host", UserName, Password);
sshclient.Connect();
ShellStream stream = sshclient.CreateShellStream("commands", 80, 24, 800, 600, 1024);
public StringBuilder sendCommand(string customCMD)
{
    StringBuilder answer;

    var reader = new StreamReader(stream);
    var writer = new StreamWriter(stream);
    writer.AutoFlush = true;
    WriteStream(customCMD, writer, stream);
    answer = ReadStream(reader);
    return answer;
}

private void WriteStream(string cmd, StreamWriter writer, ShellStream stream)
{
    writer.WriteLine(cmd);
    while (stream.Length == 0)
    {
        Thread.Sleep(500);
    }
}

private StringBuilder ReadStream(StreamReader reader)
{
    StringBuilder result = new StringBuilder();

    string line;
    while ((line = reader.ReadLine()) != null)
    {
        result.AppendLine(line);
    }
    return result;
}

I am trying to run the below commands

sudo su - wwabc11
whoami
cd /wwabc11/batch/bin/
pwd

How to run the commands one after another and read the output information? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just write the "commands" to the StreamWriter.

writer.WriteLine("sudo su - wwabc11");
writer.WriteLine("whoami");
// etc

See also C# send Ctrl+Y over SSH.NET.


Though note that using CreateShellStream ("shell" channel) is not the correct way to automate a commands execution. You should use CreateCommand/RunCommand ("exec" channel). Though SSH.NET limited API to the "exec" channel does not support providing an input to commands executed this way. And whoami and the others are actually inputs to sudo/su command.

A solution would be to provide the commands to su on its command-line, like:

sudo su - wwabc11 -c "whoami ; cd /wwabc11/batch/bin/ ; pwd"

For an example of code that uses CreateCommand to execute a command and reads its output, see see SSH.NET real-time command output monitoring.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...