SSH.NET RunCommand To Save Command Output to File - c#

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;
}

Related

Getting SSH output into StreamReader from long running SSH commands

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);
}

Parallel read of SQL Server FileStream not working

I am trying to read the same SQL Server file stream in parallel threads, but am having no success.
Mostly I get the following exception (although from time to time I get a other errors):
System.InvalidOperationException: "The process cannot access the file specified because it has been opened in another transaction."
I have searched the internet, and found just a few posts, but as I understand this is supposed to work. I'm using SQL Server 2008 R2.
I've simplified the code to the following: the main code opens a main transaction, and then runs 2 threads in parallel, each thread using a DependentTransaction and copies the SQL Server file stream to a temporary file on the disk.
If I change threadCount to 1, then the code works.
Any idea why this fails?
The code:
class Program
{
private static void Main(string[] args)
{
string path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(path);
try
{
using (var transactionScope = new TransactionScope(TransactionScopeOption.Required))
{
TransactionInterop.GetTransmitterPropagationToken(Transaction.Current);
const int threadCount = 2;
var transaction = Transaction.Current;
// Create dependent transactions, one for each thread
var dependentTransactions = Enumerable
.Repeat(transaction.DependentClone(DependentCloneOption.BlockCommitUntilComplete), threadCount)
.ToList();
// Copy the file from the DB to a temporary files, in parallel (each thread will use a different temporary file).
Parallel.For(0, threadCount, i =>
{
using (dependentTransactions[i])
{
CopyFile(path, dependentTransactions[i]);
dependentTransactions[i].Complete();
}
});
transactionScope.Complete();
}
}
finally
{
if (Directory.Exists(path))
Directory.Delete(path, true);
}
}
private static void CopyFile(string path, DependentTransaction dependentTransaction)
{
string tempFilePath = Path.Combine(path, Path.GetRandomFileName());
// Open a transaction scope for the dependent transaction
using (var transactionScope = new TransactionScope(dependentTransaction, TransactionScopeAsyncFlowOption.Enabled))
{
using (Stream stream = GetStream())
{
// Copy the SQL stream to a temporary file
using (var tempFileStream = File.OpenWrite(tempFilePath))
stream.CopyTo(tempFileStream);
}
transactionScope.Complete();
}
}
// Gets a SQL file stream from the DB
private static Stream GetStream()
{
var sqlConnection = new SqlConnection("Integrated Security=true;server=(local);initial catalog=DBName");
var sqlCommand = new SqlCommand {Connection = sqlConnection};
sqlConnection.Open();
sqlCommand.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";
Object obj = sqlCommand.ExecuteScalar();
byte[] txContext = (byte[])obj;
const string path = "\\\\MyMachineName\\MSSQLSERVER\\v1\\DBName\\dbo\\TableName\\TableName\\FF1444E6-6CD3-4AFF-82BE-9B5FCEB5FC96";
var sqlFileStream = new SqlFileStream(path, txContext, FileAccess.Read, FileOptions.SequentialScan, 0);
return sqlFileStream;
}
}
kk

ssh.net c# runcommand issue

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;
}

SSH terminal in a webapp using ASP.NET

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;
}

Executing unix scripts using sshnet

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;

Categories