Linux start process as user

Launch external process as user while running as root

I,m writing a mono application which is intended to run at startup as root (upstart + mono-service) and listen to user login/logout events. When user loggs in I start another mono service to listen to session events. But it should not run as root, but as session owner. I have access to session owner’s name, uid, gid. My problem is someow similar to Start a process as user from an process running as admin , but for linux. So how to run external process as specified user while running from root properly? Edit: Here’s my solution: According to http://pages.infinit.net/ctech/20040405-1133.html I’ve tried to impersonate to user while starting process, and it works well as I can see for now.

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 , ", 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; > 

Источник

How to run a command as a specific user in an init script?

I’m writing an init script which is supposed to execute a single command as a user different than root. This is how I’m doing it currently:
sudo -u username command This generally works as expected on Ubuntu/Debian, but on RHEL the script which is executed as the command hangs.
Is there another way to run the command as another user?
(Note that I can’t use lsb init functions as they’re not available on RHEL/Centos 5.x.)

Notice that this question is about something set up exclusively by the administrator (typically, a daemon that runs as some user for security). A slightly different case is users setting up on their own commands to run at boot, with their user crontab. See askubuntu.com/questions/260845/…

6 Answers 6

On RHEL systems, the /etc/rc.d/init.d/functions script is intended to provide similar to what you want. If you source that at the top of your init script, all of it’s functions become available.

The specific function provided to help with this is daemon . If you are intending to use it to start a daemon-like program, a simple usage would be:

daemon --user=username command 

If that is too heavy-handed for what you need, there is runuser (see man runuser for full info; some versions may need -u prior to the username):

/sbin/runuser username -s /bin/bash -c "command(s) to run as user username" 

Источник

Читайте также:  Создать папку linux centos

Starting a script as another user

I’ve created a script in /etc/init.d/ which has to run several other scripts from other (non-root privileged) users from their home directories, as if they started them. I launch these scripts with: sudo -b -u And it works. But for every user script that continues running(for example some watchdog) I see a corresponding parent sudo process, still alive and running as root. This creates a mess in the active processes list. So my question is: How can I launch(fork) another script from existing bash script as another user and leave it as an orphaned(stand alone) process? More detailed explanation:
I’m basically trying to provide to other users on the machine a mean to run stuff upon system start or system shutdown by running executable files found in respective subdirectories found in their home directory, named .startUp and .shutDown. Since I did not find any other means to do that I wrote my bash script that does exactly that and I’ve configured it as a service script (by following the skeleton example) in /etc/init.d/ so when it is run with start argument it launches everything from .startUp directories and when it is run with stop argument it launches everything from .shutDown directories of all users as them. Alternatively I’m also interested if I could have used some existing solution to solve this problem. UPDATE
I’ve looked around a bit and I found this question: https://unix.stackexchange.com/questions/22478/detach-a-daemon-using-sudo Accepted answer there, to use: sudo -u user sh -c «daemon & disown %1» , works for me to. But I also tried without disown %1 and it is the same. So this is what works for me as I expected:

My additional question now is, why is it working without disown? should I still leave the disown call, regardless, for some potential special case? UPDATE 2 Apparently this works too:

Is there any difference between this call and the sudo call? I know this is potentially an entire different question. But since I’m finding the answers here myself maybe for the sake of this topic someone could clarify this here. UPDATE 3
Both of these methods with either su or sudo now produce a new startpar process (single process that runs as root) after I boot the machine. Visible in process list as:

Why is this process spawned? Obviously I’m doing something wrong since no other init.d script has this process running. UPDATE 4
The issue with startpar is resolved. I’ve started another question for that:
startpar process left hanging when starting processes from rc.local or init.d And another question to further discuss launching mechanisms for non privileged users:
Providing normal users(non-root) with initialization and shutdown auto-run capabilities

Источник

Background

I’m trying to restart some programs ( mail-notification and stalonetray ) regularly, as they appear to die frequently. I want to set restart them whenever NetworkManager reconnects. Hence, I have them triggered by a script in /etc/NetworkManager/dispatcher.d/ .

Scripting

#!/bin/bash sudo -u foo_user pkill mail-notificati -x sudo -u foo_user DISPLAY=:0 mail-notification & 

This works fine if I run it directly as a user. However, if I call it from root’s script, it fails. I am prompted to enter the passwords for mail-notification ; it cannot read Gnome Keyring. How can I run this program as foo_user in every way?

Читайте также:  User list from linux

What does «in every way» mean? Every program that a user runs can have different environment, so saying that (for example) DISPLAY should be set for it to be «in every way» doesn’t make much sense. You’d need to define this question more for it to make sense.

@ChrisDown I mean I want it to work when running the script as root as it does when running the script as foo_user . I appreciate that DISPLAY isn’t necessarily relevant here, but included it as an example of what I was doing.

That still doesn’t clarify, because «doing the same thing when run as root as when run as a user» doesn’t make sense — an environment is per-process, not per-user.

@ChrisDown Sorry, I’m afraid I don’t understand the distinction in this case. Here, I’m asking to run the mail-notification process as in foo_user ‘s environment.

How do you know foo_user is logged in, and on which display? On a single-user system it’s perhaps reasonable to assume that it’s always :0.0 but it is not reasonable to assume that the user is logged in at all times. Anyway, this makes more sense to run within the X session script of foo_user , which will remove both your original problem and the complications it caused you to want to try to solve.

4 Answers 4

In 2021

In short:

To run a command as another user you can use this commands:

runuser -u user — command
can be used only by root to run commands as another user.
do not require authentication.
do not create log messages.
has permission limitations and issues.

su — user -c command
can be used by any user.
require authentication as target user.
create message in /var/log/auth.log or /var/log/secure .

sudo -u user command
can be used by the user with root privileges or the user from the sudoers file.
require authentication as current user (you).
create message in /var/log/auth.log or /var/log/secure .

pkexec —user user command
can be used by any user.
require authentication as target user.
create message in /var/log/auth.log or /var/log/secure .
replacement for GUI tools such as gksu or gksudo .

More info:

Run a GUI application as another user:

If you want to run a GUI application as another user, you need first allow to the target user connecting to your display:
xhost +si:localuser:user
then use runuser / su / sudo / pkexec to run the application,
and then use xhost to prevent the subsequent connections:
xhost -si:localuser:user

Excellent answer! I tried to use this to run spotify as a non-privileged system user. Your answers, especially for running a GUI app, worked for me. However, I did neet to pass in my DISPLAY var through sudo using the -E flag. Also, I was ignorant and didn’t realize localuser is that literal string. Finally, a gui app may fail to various other issues with expecting a normal user’s profile. HTH

Regarding GUI: Is this safe though? Can user send arbitrary input after having been given access to the display?

You can always use good old su :

This command opens a sub-shell as the user you want to impersonate. As root you can use it without being prompted for a password.

Читайте также:  Просмотр системного журнала linux

su foo_user -c whatevercommandyouwant

I’m not sure what -x is (I get su: invalid option — ‘x’ ), but after removing that, it still fails as per the question.

Hi, sorry for the confusion, but my aim is not to provide a one shot solution but to tell you how the command su works. If you did a direct cut and paste you may have got an error. But, that’s exactly why I added a link to the su man page as the first thing. Please cut and paste this into the shell and see what it says 😉

Sorry, I still don’t understand. Are you suggesting that su will provide a different env to sudo that should fix my problem? If so, then that doesn’t seem to be the case.

Yes. Again: man7.org/linux/man-pages/man1/su.1.html » su allows to run commands with a substitute user and group ID. When called without arguments, su defaults to running an interactive shell as root. For backward compatibility, su defaults to not change the current directory and to only set the environment variables HOME and SHELL (plus USER and LOGNAME if the target user is not root). » anyway sudo has nothing to do with that, sudo su does. sudo grants permissions to run commands that require specific privileges to your user.

If you want to interact with a GUI from a process that isn’t started from that GUI, you need to set a few environment variables: at least DISPLAY , possibly also XAUTHORITY if it isn’t in the default location, and for many modern programs you need to set DBUS_SESSION_BUS_ADDRESS .

But a more reliable approach for your problem would be to not restart those programs from NetworkManager. In addition to the difficulty of successfully launching them, you also need to worry about whether you’re logged in at all, and if there might be other users and other displays to consider, and so on. Instead, kill those programs, but don’t restart them. In your normal session, instead of starting them directly, start them from a supervisor that restarts them if they die. I think systemd includes this functionality (but I don’t know how to use it); or you can use dedicated supervisor programs such as monit, supervise, …

Read, copy and install run-as , a Bash and a Python script which wrap up usage of machinectl , xhost and of managing running dbus and setting variables to run a graphical application for you:

To run a graphical application do

References

You must log in to answer this question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.13.43531

Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group.
This site is not affiliated with Linus Torvalds or The Open Group in any way.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью
Adblock
detector