I’m attempting to capture output from a long running SSH command that may take a few seconds to initially produce any text output once called and may take up to a minute to fully complete.
The below code snippet works fine if I issue a simple command to execute such as ls that produces immediate output into the output stream.
However, I get nothing returned and SSH disconnects if I run a command that doesn’t instantly produce any output.
using (var sshClient = new SshClient(target, 22, userName, password))
{
sshClient.Connect();
var cmd = sshClient.CreateCommand(command);
var result = cmd.BeginExecute();
using (var reader = new StreamReader(cmd.OutputStream))
{
while (!reader.EndOfStream || !result.IsCompleted)
{
string line = reader.ReadLine();
if (line != null)
{
Console.WriteLine(line);
}
}
sshClient.Disconnect();
}
}
BeginExecute begins an asynchronous command execution. You need to wait and keep reading the output stream until it completes.
In a simple way,
using (var sshClient = new SshClient(host, 22, username, password)) {
sshClient.Connect();
var cmd = sshClient.CreateCommand("for i in `seq 1 10`; do sleep 1; echo $i; done");
var asyncResult = cmd.BeginExecute();
var outputReader = new StreamReader(cmd.OutputStream);
string output;
while (!asyncResult.IsCompleted) {
output = outputReader.ReadToEnd();
Console.Out.Write(output);
}
output = outputReader.ReadToEnd();
Console.Out.Write(output);
}
Related
I am trying to run a python script as a process to which I pass a couple of parameters and then read standard output. I have a little console app and a dummy script that works fine, but when I do the same thing in my WebApi project, Standard Output is always blank, and I cannot figure out why. My code follows:
Console App
class Program
{
private static string Foo(string inputString)
{
string result = String.Empty;
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "python";
start.Arguments = string.Format(" {0} {1} {2}", #"*path*\runner.py", #"*path*\test2.py", inputString);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
result = reader.ReadToEnd();
}
}
return result;
}
static void Main(string[] args)
{
var result = Foo("flibble");
Console.Write(result);
Console.ReadKey();
}
}
runner.py (for the console app)
import sys, imp
test = imp.load_source('test',sys.argv[1])
result = test.hello(sys.argv[2])
test2.py (from the console app)
import sys
def hello(inputString):
sys.stdout.write(inputString)
return
That is the end of what I have that works, now onto the code where the issue is:
ApiEndpoint
[HttpPost]
public IHttpActionResult TestEndpoint()
{
string postedJson = ReadRawBuffer().Result;
if (postedJson == null) throw new ArgumentException("Request is null");
var result = _pythonOperations.Foo(postedJson);
// Deal with result
return Ok();
}
_pythonOperations.Foo()
public string Foo(string inputString)
{
string result;
var start = new ProcessStartInfo
{
FileName = _pathToPythonExecutable,
Arguments = string.Format(" {0} {1} {2}", _pathToPythonRunnerScript, _pathToPythonFooScript, inputString),
UseShellExecute = false,
RedirectStandardOutput = true
};
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
result = reader.ReadToEnd();
}
}
return result;
}
pythonRunnerScript
import sys, imp
module = imp.load_source('foo', sys.argv[1])
module.Foo(sys.argv[2])
Foo script
import sys
def Foo(inputString)
outputString = "output"
sys.stdout.write(outputString)
return
This is quite possibly one of the longest posts I have made, so thanks for taking the time to read it, and hopefully I can get a solution to this.
Cheers
Turns out the format I was passing in was wrong. I was using Postman REST Api client, and pasting the huge amounts of data into their request content window truncated it, leaving me with half a line. Once this was sorted, everything ran through ok.
I am using Renci.SshNet in c# on framework 3.5 and running a command on 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();
}
every thing works well, my question here is that "Is there a way that it should not wait for client.RunCommand to be finish" My prog doesn't need a output from unix and hence I don't want to wait for the RunCommand to finish. This command took 2 hours to execute so wanted to avoid that wait time on my application.
As i assume SSH.NET doesn't expose a true asynchronous 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 if you use this inside WPF or WinForms then you will need to txtResult.Text = terminal.Result with Dispatcher.Invoke or Control.Invoke, respectively.
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;
}
Hello I creating a webapp that has a working SSH terminal similar to Putty. I'm using SSH Library as a means of handling the ssh stream. However there is a problem. I can log into a Cisco 2950 and type in commands but it comes out jumbled and in one line.
Also when I try "conf t" it gets into the configuration terminal but then you can't do anything and this pops up "Line has invalid autocommand "?".
Here is the code I have so far:
This is the SSH.cs that interacts with the library.
public class SSH
{
public string cmdInput { get; set; }
public string SSHConnect()
{
var PasswordConnection = new PasswordAuthenticationMethod("username", "password");
var KeyboardInteractive = new KeyboardInteractiveAuthenticationMethod("username");
// jmccarthy is the username
var connectionInfo = new ConnectionInfo("10.56.1.2", 22, "username", PasswordConnection, KeyboardInteractive);
var ssh = new SshClient(connectionInfo);
ssh.Connect();
var cmd = ssh.CreateCommand(cmdInput);
var asynch = cmd.BeginExecute(delegate(IAsyncResult ar)
{
//Console.WriteLine("Finished.");
}, null);
var reader = new StreamReader(cmd.OutputStream);
var myData = "";
while (!asynch.IsCompleted)
{
var result = reader.ReadToEnd();
if (string.IsNullOrEmpty(result))
continue;
myData = result;
}
cmd.EndExecute(asynch);
return myData;
}
}
This the code in the .aspx.cs that displays the code on the web page.
protected void CMD(object sender, EventArgs e)
{
SSH s = new SSH();
s.cmdInput = input.Text;
output.Text = s.SSHConnect();
}
Any help would be appreciated.
From looking through the test cases in the code for the SSH.NET library, you can use the RunCommand method instead of CreateCommand, which will synchronously process the command. I also added a using block for the SshClient ssh object since it implements iDisposable. Remember to call Disconnect as well so you don't get stuck with open connections.
Also the SshCommand.Result property (used in the command.Result call below), encapsulates the logic to pull the results from the OutputSteam, and uses this._session.ConnectionInfo.Encoding to read the OutputStream using the proper encoding. This should help with the jumbled lines you were receiving.
Here is an example:
public string SSHConnect() {
var PasswordConnection = new PasswordAuthenticationMethod("username", "password");
var KeyboardInteractive = new KeyboardInteractiveAuthenticationMethod("username");
string myData = null;
var connectionInfo = new ConnectionInfo("10.56.1.2", 22, "username", PasswordConnection, KeyboardInteractive);
using (SshClient ssh = new SshClient(connectionInfo)){
ssh.Connect();
var command = ssh.RunCommand(cmdInput);
myData = command.Result;
ssh.Disconnect();
}
return myData;
}
I am trying to execute perl scripts on my UNIX machine, through SSH.
I have managed to connect to the machine and execute "ls" and "man chmod", but when I am trying "perl /test/temp.pl" or "perl a", I don't get anything back.
The code I am using is the following
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(host, user,pass);
using (var client = new SshClient(connectionInfo))
{
client.Connect();
var cmd = client.CreateCommand(script);
string result = cmd.Execute(script);
var reader = new StreamReader(cmd.OutputStream);
var output = reader.ReadToEnd();
Console.Out.WriteLine(result + "_output:" + output);
}
Anybody having the same or similar issues?
Try:
client.Connect();
SshCommand cmd = client.RunCommand(message);
var output =cmd.Result;
I'm trying to run a command on a remote server via SSH.
I need the output of the command that is run to be saved in a file on that remote server.
I've been attempting to this the following way
// ssh is the SshClient which is already set up
ssh.Connect();
ssh.RunCommand("echo 1 > C:\test.csv"); //Doesn't create a file
ssh.Disconnect();
Why doesn't this work with SSH.NET? If I run this via putty using the same credentials it works perfectly fine.
EDIT (Working Code):
I did some more playing around and have found the following to work:
// ssh is the SshClient which is already set up
ssh.Connect();
var shell = ssh.CreateShellStream("cmd.exe", 80, 24, 800, 600, 1024);
var reader = new StreamReader(shell);
var writer = new StreamWriter(shell);
writer.AutoFlush = true;
while (!shell.DataAvailable)
System.Threading.Thread.Sleep(1000); //This wait period seems required
writer.WriteLine("echo 1 > C:\test.csv");
while (!shell.DataAvailable)
System.Threading.Thread.Sleep(1000); //This wait period seems required
ssh.Disconnect();
While that works I still don't understand what's really happening here. Could someone explain?
Try this function:
Just save the result to a variable or write the result using StreamWriter
private void writeMe()
{
using (StreamWriter sw = new StreamWriter(filename)
{
string result = eSshCom(command);
sw.WriteLine(result);
}
}
private string eSshCom(string getCommand)
{
this.res = "";
var connectionInfo = new KeyboardInteractiveConnectionInfo(ipaddress, 22, username);
connectionInfo.AuthenticationPrompt += delegate(object asender, AuthenticationPromptEventArgs xe)
{
foreach (var prompt in xe.Prompts)
{
if (prompt.Request.Equals("Password: ", StringComparison.InvariantCultureIgnoreCase))
{
prompt.Response = password;
}
}
};
using (var ssh = new SshClient(connectionInfo))
{
ssh.Connect();
var cmd = ssh.RunCommand(getCommand);
this.res = cmd.Result;
ssh.Disconnect();
}
return this.res;
}