在Linux中以更高权限和密码运行c#进程

问题描述 投票:0回答:1

我尝试在 Linux 中使用包含美元符号 ($) 的密码运行具有更高权限的 C# (.net6) 进程,但它总是失败。 我试过:

var stInfo = new ProcessStartInfo
{
    FileName = "echo",
    Arguments = " 'pas$word' | sudo -S ping 127.0.0.1"
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
};

但是我收到的所有内容都是 echo 的一部分,标准输出是:

'pas$word' | sudo -S ping 127.0.0.1

然后我尝试以与从终端运行的方式类似的方式使用参数调用 bash

/bin/bash -c "echo 'pas\$word' | sudo -S ping 127.0.0.1"

var stInfo = new ProcessStartInfo
{
    FileName = "/bin/bash",
    Arguments = "-c \"echo 'pas\$word' | sudo -S ping 127.0.0.1\""
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
};

但这不起作用并通过 stderr 报告此情况:

[sudo] password for user: Sorry, try again.
[sudo] password for user: 
sudo: no password was provided
sudo: 1 incorrect password attempt

我尝试过不同的参数,例如:

Arguments = "-c \"echo pas$word | sudo -S ping 127.0.0.1\""
Arguments = "-c \"echo 'pas$word' | sudo -S ping 127.0.0.1\""
Arguments = "-c \"echo pas\\$word | sudo -S ping 127.0.0.1\""
Arguments = "-c \"echo 'pas\\$word' | sudo -S ping 127.0.0.1\""
Arguments = "-c \"echo pas\\\\$word | sudo -S ping 127.0.0.1\""
Arguments = "-c \"echo 'pas\\\\$word' | sudo -S ping 127.0.0.1\""

所有这些都具有相同的结果。 我也尝试过使用

ArgumentList
而不是
Arguments
,但结果相同。

有什么办法让它发挥作用吗?

更新: 我已将密码更改为不带美元符号的密码,以避免对其进行转义,并且我仍然遇到相同的问题,因此问题不是转义美元符号,而是将密码注入到进程中

c# .net linux process
1个回答
0
投票

请尝试这个:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        var password    = ""; // Replace with your actual password
        var command     = "/bin/bash";
        var sudoCommand = "ping 127.0.0.1";
        var arguments   = $"-c \"echo '{password}' | sudo -S -p '' {sudoCommand}\"";

        ExecuteCommand(command, arguments);
    }

    static void ExecuteCommand(string command, string arguments)
    {
        var process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName               = command,
                Arguments              = arguments,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                UseShellExecute        = false,
                CreateNoWindow         = true
            }
        };

        process.Start();

        // Read the output and error streams
        var output = process.StandardOutput.ReadToEnd();
        var error  = process.StandardError.ReadToEnd();

        process.WaitForExit();

        // Display the output and error
        Console.WriteLine("Output:");
        Console.WriteLine(output);

        Console.WriteLine("Error:");
        Console.WriteLine(error);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.