【问题标题】:Execute linux command on Centos using dotnet core使用 dotnet core 在 Centos 上执行 linux 命令
【发布时间】:2018-03-07 06:00:40
【问题描述】:

我在 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 文件需要提取并保存在当前位置。有人能纠正我在哪里吗

【问题讨论】:

    标签: centos .net-core tar lz4


    【解决方案1】:

    如果应用程序在 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("\"", "\\\"");一样转义它
    • 如果我需要文件夹 /opt/myFile 中命令 ls 的输出,FileName 和 Arguments 的值应该是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    相关资源
    最近更新 更多