【问题标题】:How to launch a process with sudo by ProcessStartInfo?如何通过 ProcessStartInfo 使用 sudo 启动进程?
【发布时间】:2014-05-12 12:44:36
【问题描述】:

我在 Debian 中有一个需要 root 权限的程序,myuser 必须运行它,但我必须从以单声道运行的 .NET 应用程序 (C#) 进行调用。 在 /etc/sudoers 中,我添加了以下行:

myuser ALL = NOPASSWD: /myprogram

所以sudo ./myprogram 适用于 myuser。

在。 NET 我在我的代码中使用

string fileName = "/myprogram";
ProcessStartInfo info = new ProcessStartInfo (fileName);
...

如何调用“sudo fileName”?到时候就不行了... 谢谢你,莫妮克。

【问题讨论】:

    标签: c# mono debian processstartinfo


    【解决方案1】:

    以下内容在类似情况下对我有用,并演示了传递多个参数:

    var psi = new ProcessStartInfo
    {
        FileName = "/bin/bash",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        Arguments = string.Format("-c \"sudo {0} {1} {2}\"", "/path/to/script", "arg1", arg2)
    };
    
    using (var p = Process.Start(psi))
    {
        if (p != null)
        {
            var strOutput = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
        }
    }
    

    【讨论】:

    • 捕获标准输出的好方法 - RedirectStandardOutput = true 不适用于 Jariq 的答案。
    【解决方案2】:

    您只需将程序作为参数传递给 sudo 命令,如下所示:

    ProcessStartInfo info = new ProcessStartInfo("sudo", "/myprogram");
    Process.Start(info);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      相关资源
      最近更新 更多