使用dotnet core在Centos上执行Linux命令

8

我正在CentOS服务器上运行一个.NET Core控制台应用程序。下面的代码对于普通命令(如uptime)可以执行,但无法执行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);
}

期望的输出是将Logs.pdf文件提取并保存在当前位置。有人能帮我纠正一下吗?

1个回答

15

如果应用程序正在 Linux 机器上运行,您也可以尝试这样做:

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;

如果命令包含引号,你应该像这样转义它:command = command.Replace("\"", "\\\""); - tom.maruska
如果我需要在文件夹/opt/myFile中使用ls命令的输出,FileName和Arguments应该是什么值? - Michel El Hajj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接