我正在编写一个mono应用程序,它的目的是在启动时以root方式运行(upstart + mono-service)并侦听用户登录/注销事件。当用户登录时,我启动另一个mono服务来侦听会话事件。但是,它不应该以根用户的身份运行,而应该作为会话所有者运行。我可以访问会话所有者的名字,uid,gid。
我的问题有点类似于Start a process as user from an process running as admin,但对于linux。
那么,如何以指定的用户身份运行外部进程,同时正确地从根运行?
编辑:
这是我的解决方案:
根据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;
}
这是一个可靠的方法吗?还是有更好的?
发布于 2015-10-07 03:20:16
这将以用户echo hello
的身份运行alice
。
sudo su alice -c 'echo hello'
发布于 2015-10-07 03:23:09
这可以通过使用-c
参数到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
ls -la
的输出应该如下所示:-rw-r--r-1某人某个用户0,10月6日22:22 mynewfile
https://stackoverflow.com/questions/32983050
复制相似问题