C# 以root用户身份运行时以用户身份启动外部进程
一、 我正在编写一个mono应用程序,它打算在启动时以root(upstart+mono服务)身份运行,并侦听用户登录/注销事件。当用户登录时,我启动另一个mono服务来监听会话事件。但是它不应该作为根用户运行,而是作为会话所有者运行。我有权访问会话所有者的名称、uid和gid 我的问题类似于linux,但适用于linux 那么,如何在从根目录正常运行时,以指定用户的身份运行外部进程呢 编辑: 以下是我的解决方案: 据我所知,我已经尝试在启动过程中模拟用户,现在我可以看到它工作得很好C# 以root用户身份运行时以用户身份启动外部进程,c#,linux,mono,C#,Linux,Mono,一、 我正在编写一个mono应用程序,它打算在启动时以root(upstart+mono服务)身份运行,并侦听用户登录/注销事件。当用户登录时,我启动另一个mono服务来监听会话事件。但是它不应该作为根用户运行,而是作为会话所有者运行。我有权访问会话所有者的名称、uid和gid 我的问题类似于linux,但适用于linux 那么,如何在从根目录正常运行时,以指定用户的身份运行外部进程呢 编辑: 以下是我的解决方案: 据我所知,我已经尝试在启动过程中模拟用户,现在我可以看到它工作得很好 publi
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;
}
这是可靠的方法吗?或者有更好的吗?这将以用户
alice
的身份运行echo hello
:
sudo su alice -c 'echo hello'
这将以用户身份运行
echo hello
:
sudo su alice -c 'echo hello'
这可以通过将
-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 someuser someuser 0 Oct 6 22:22 mynewfile这可以通过使用
-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 someuser someuser 0 Oct 6 22:22 mynewfile这真是一个选项,谢谢!但我不太确定
System.Diagnostics.Process
是否能很好地处理这样的链:sudo su username-c mono service/home/username/App.exe
。据我所知,它的语法是(“应用程序”、“参数”)process(“sudo”、“su用户名-c mono服务/home/username/App.exe”)
也许?或者可能/usr/bin/sudo
。顺便问一下,你确定你在运行linux吗?.exe
文件扩展名通常仅在windows中使用。这确实是一个选项,谢谢!但我不太确定System.Diagnostics.Process
是否能很好地处理这样的链:sudo su username-c mono service/home/username/App.exe
。据我所知,它的语法是(“应用程序”、“参数”)process(“sudo”、“su用户名-c mono服务/home/username/App.exe”)
也许?或者可能/usr/bin/sudo
。顺便问一下,你确定你在运行linux吗?.exe
文件扩展名通常仅在windows中使用。