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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…