以root身份运行时以用户身份启动外部进程

时间:2015-10-07 02:55:43

标签: c# linux mono

我正在编写一个单声道应用程序,它打算在启动时以root身份运行(upstart + mono-service)并监听用户登录/注销事件。当用户登录时,我启动另一个单声道服务来收听会话事件。但它不应该以root身份运行,而应作为会话所有者运行。我可以访问会话所有者的名字,uid,gid。

我的问题类似于Start a process as user from an process running as admin,但对于linux。

那么如何在从root运行时正确运行外部进程作为指定用户?

修改

这是我的解决方案:

根据http://pages.infinit.net/ctech/20040405-1133.html我试图在启动过程时冒充用户,而且我现在可以看到效果很好。

public class SpawnerService : ServiceBase
{
    public SpawnerService ()
    {
        logger = new StreamWriter (new FileStream("/home/username/Log.txt", FileMode.Append));

        info = new ProcessStartInfo {
            FileName = "/usr/bin/mono-service",
            Arguments = "/home/username/SlaveService.exe",
            UseShellExecute = false,
            CreateNoWindow = true
        };
    }

    protected override void OnStart (string[] args)
    {
        logger.WriteLine ("Spawner service started");
        logger.Flush ();

        var user = new WindowsIdentity ("username");
        logger.WriteLine ("Trying to mimc to {0}, {1}", user.Name,user.Token.ToString());
        logger.Flush ();

        WindowsImpersonationContext wic = null;
        try {
            wic = user.Impersonate ();
            Process.Start (info);
            logger.WriteLine ("Seems allright");
            logger.Flush ();
        }
        catch (Exception) {
            logger.WriteLine ("Seems failed");
            logger.Flush ();
        }
        finally {
            if (wic != null) {
                wic.Undo ();
                wic = null;
            }
        }
    }

    protected override void OnStop ()
    {
        logger.WriteLine ("Spawner service stopped");
        logger.Flush ();
    }

    private ProcessStartInfo info;
    private StreamWriter logger;
}

这是一种可靠的方法吗?还是有一些更好的?

2 个答案:

答案 0 :(得分:0)

这将以用户echo hello

运行alice
sudo su alice -c 'echo hello'

答案 1 :(得分:0)

这可以通过使用-c的{​​{1}}参数并指定您希望用户运行的命令来实现。

su

"-c, --command COMMAND Specify a command that will be invoked by the shell using its -c." su someuser -c "touch someusersfile" ls -la someusersfile 的输出应如下所示:        -rw-r - r-- 1 someuser someuser 0 Oct 6 22:22 mynewfile