Executing unix scripts using sshnet - c#

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;

Related

Getting wrong file path when generating file route in C# Console App

I'm trying to read in a SQL script in a C# console app. I'm having issues as the file route that it's generating always starts in the bin folder of the project.
public static void ApiResources(IConfiguration config, string testUrlExtension)
{
try
{
var azureDatabaseUrl = String.Format(config["SqlDatabase:BaseUrl"], $"test{testUrlExtension}");
SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();
connBuilder.DataSource = azureDatabaseUrl;
connBuilder.UserID = config["SqlDatabase:ZupaKeyReleaseUserName"];
connBuilder.Password = config["SqlDatabase:ZupaKeyReleasePassword"];
connBuilder.InitialCatalog = "zupaauthentication";
using (SqlConnection connection = new SqlConnection(connBuilder.ConnectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
connection.Open();
var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];
var routeToApiResourseSqlScript = $"{GetLocalPathToProject}Zupa.ReleaseDeploymentAutoConfigure\\Zupa.ReleaseDeploymentAutoConfigure\\Sql\\Scripts\\";
var apiResourcesFileName = "AddApiResorces.sql";
var fullPathToSqlScript = $"{routeToApiResourseSqlScript}{apiResourcesFileName}";
command.CommandText = File.ReadAllText(fullPathToSqlScript);
command.ExecuteNonQuery();
connection.Close();
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.InnerException);
}
}
The error I'm receiving is as follows:
Something went wrong try configuring the release again.
System.IO.IOException: The filename, directory name, or volume label syntax is incorrect. :
'C:\Zupa_Source_Code\Zupa.ReleaseDeploymentAutoConfigure\Zupa.ReleaseDeploymentAutoConfigure\bin\Debug\netcoreapp3.1\file:\C:\Zupa_Source_Code\Zupa.ReleaseDeploymentAutoConfigure\Zupa.ReleaseDeploymentAutoConfigure\Sql\Scripts\AddApiResorces.sql'
The correct path is being added to the end of the bin directory which is
file:\C:\Zupa_Source_Code\Zupa.ReleaseDeploymentAutoConfigure\Zupa.ReleaseDeploymentAutoConfigure\Sql\Scripts\AddApiResorces.sql
Change "CodeBase" in this line
var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];
to be Location:
var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];

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

Connect to OrientDB via C#.net

I am using Orient-db 2.2.13 and a VisualStudio2015 and I am trying to perform a simple "test connection" method from c#.net to an existing orientDB I have.
In java it is very simple to perform:
OrientGraphFactory factory = new OrientGraphFactory(remoteUrl, user, password, false);
result = factory.getNoTx().command(new OCommandSQL("select....")).execute();
But in C#.Net it seems to be a less easy.
All I got so far is this (and it is NOT working)
OServer _server = new OServer(_hostname, _port, _rootUserName, _rootUserPassword);
ODatabase odb = new ODatabase(_hostname, _port, _DBname, ODatabaseType.Graph, _rootUserName, _rootUserPassword);
can you help me please?
Just tried today using OrientDB 2.2.16
ConnectionOptions opts = new ConnectionOptions();
opts.HostName = "localhost";
opts.UserName = "root";
opts.Password = "mypassword";
opts.Port = 2424;
opts.DatabaseName = "mydatabasename";
opts.DatabaseType = ODatabaseType.Graph;
database = new ODatabase(opts);
Console.Write(database.Size);
Try staarting using this template and then execute command using
database.execute(..);
this works for me (VS2015, Orient 2.2.5, OrientDB-Net.binary.Innov8tive 0.1.12)
using (ODatabase db = new ODatabase(server, port, dbname, ODatabaseType.Graph, user, pw))
{
string rid="#12:0";
OVertex v1 = db.Query<OVertex>($"select * from {rid}")[0];
var myfield = v1.GetField<string>("string_field_name");
}

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

SSH.NET RunCommand To Save Command Output to File

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

Categories