Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute linux command on Centos using dotnet core

I'm running a .NET Core Console Application on CentOS box. The below code is executing for normal command like uptime, but not executing for lz4 -dc --no-sparse vnp.tar.lz4 | tar xf - Logs.pdf:

try
{
    var connectionInfo = new ConnectionInfo("server", "username", new PasswordAuthenticationMethod("username", "pwd"));
    using (var client = new SshClient(connectionInfo))
    {
        client.Connect();

        Console.WriteLine("Hello World!");
        var command = client.CreateCommand("lz4 -dc --no-sparse vnp.tar | tar xf - Logs.pdf");
        var result = command.Execute();
        Console.WriteLine("yup ! UNIX Commands Executed from C#.net Application");
        Console.WriteLine("Response came form UNIX Shell" + result);

        client.Disconnect();
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

Expected output is Logs.pdf file needs to be extracted and saved in the current location. Can someone correct me where im

like image 797
Itniv Avatar asked Dec 24 '22 13:12

Itniv


1 Answers

If application is running on Linux machine then you can try this also:

string command = "write your command here";
string result = "";
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
    proc.StartInfo.FileName = "/bin/bash";
    proc.StartInfo.Arguments = "-c \" " + command + " \"";
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.StartInfo.RedirectStandardError = true;
    proc.Start();

    result += proc.StandardOutput.ReadToEnd();
    result += proc.StandardError.ReadToEnd();

    proc.WaitForExit();
}
return result;
like image 105
Harit Kumar Avatar answered Jan 11 '23 16:01

Harit Kumar