Linux run command as system user

Linux Run Command As Another User

Dear nixCraft,
I just want to know how to run Linux commands as another user or as the root user?
–Sincerely,
Confused About Linux commands.

Dear Confused,
You can use the following commands to run as another user or as root user on Linux.

1. Using Linux runuser command as another user

Only session PAM hooks are run, and there is no password prompt. If run as a non-root user without privilege to set user ID, the command will fail as the binary is not setuid. As runuser doesn’t run auth and account PAM hooks, it runs with lower overhead than su.

For example, as a root user you may want to check shell resource limits for oracle user, enter:
# runuser -l oracle -c ‘ulimit -SHa’
Check nginx or lighttpd web server limitations:
# runuser -l nginx -c ‘ulimit -SHa’
# runuser -l lighttpd -c ‘ulimit -SHa’
Sometime, a root user can not browse NFS mounted share due to permission (security) issue:
# ls -l /nfs/wwwroot/cyberciti.biz/http
OR
# cd /nfs/wwwroot/cyberciti.biz/http
Sample outputs:

However, apache user is allowed to browse or access nfs based system mouted at /nfs/wwwroot/cyberciti.biz/http/:
# runuser -l apache -c ‘ls -l /nfs/wwwroot/cyberciti.biz/http/’
# runuser -l apache -c ‘cd /nfs/wwwroot/cyberciti.biz/http/; vi index.php’
No password is required to use runuser command and it must be run by root user only. Sometimes sudo or su will give following error:

To get around this try the following syntax:
# runuser -u www-data — command
## Run commands as www-data user ##
# runuser -u www-data — composer update —no-dev
# runuser -u www-data — php7 /app/maintenance/update.php

The runuser command options

  1. -l user_login_name : Make the shell a login shell, uses runuser-l PAM file instead of default one.
  2. -g group : Specify the primary group.
  3. -G group : Specify a supplemental group.
  4. -c COMMAND : Pass a single COMMAND to the shell with -c.
  5. —session-command=COMMAND : Pass a single COMMAND to the shell with -c and do not create a new session.
  6. -m : Do not reset environment variables.
  7. -u username : Run command as given username to get around ‘su -‘ or ‘sudo’ limit.

2. Run a Linux command with substitute user and group ID using ‘su command’

The su command allows you to become a super user or substitute user, spoof user, set user or switch user. It allows a Linux user to change the current user account associated with the running console or shell provided that you know the target user’s password. The syntax is as follows:

Источник

Linux Run Commands As Another User

Linux is the best and most-used open source operating system. The Linux users have a large number of options to choose operating system. You have options to choose desktop for your Linux systems. But still Linux professionals love the command line to work. Mainly the Linux server editions comes with command line option only, which create them lighter and faster.

The Linux users uses shell to interact with operating systems. In which the Bash (Born Shell) is the most used shell and available default on most systems. Now a days Zsh (Z Shell) is also getting popularity between the users due to its features.

In this tutorial you will learn how to run command as another user in Linux/Unix systems.

Running Command As Another User with Su

su (Switch User) command is used to run shell as another user. This command switches to the new user and load their environment.

The basic su command looks like below:

The above command which you to another user, where you can run commands with that user. But our aim is to run Linux command as another user without switching to them. To do this, check below example.

I am currently logged in as root user. You can pass your command with -c parameter. Now, the below example will run “ls” command as user rahul without switching to the user.

You can also run multiple commands as another user in Linux, like:

In the above command, first prints present working directory with pwd, then create and switches to new directory named “hello”. Again prints the present working directory. All commands are separated with semicolon (;) as we do in general.

Run Command As Another User with Sudo

This is generally used to run command as root user, but you can also use it with other users. Here you don’t need to use any command line switches. Enter the name of user to which you want to run command. After that specificy the command to run as defined user.

Читайте также:  Файл windows operating system

Syntax:

For example, you are writing a shell script, which required to run as non-root user. But you need to restart apache2 service. In that case you can use sudo to run command as root user. Like:

Run Command As Another User with Runuser

You can also use runuser to run commands as another user in Linux systems. This is lesser known commands by the Linux users. Use runuser command to execute commands with the effective user ID and group ID of the defined user.

Syntax:

Example – for example, run a command as user “rahul” and create directory in his home directory.

Then list files under home directory of user ‘rahul’.

You can also execute booth commands in a single command. Just add multiple commands wit semicolon separated.

Conclusion

In this tutorial, you have learned to run commands as another user in Linux system. You have learned running commands as another user with the help of su, sudo and runuser Linux commands.

Источник

Allow A Normal User To Run Commands As root Under Linux / UNIX Operating Systems

From my mail bag:

I would like to run few commands such as stop or start web server as a root user. How do I allow a normal user to run these commands as root?

You need to use the sudo command which is use to execute a command as another user. It allows a permitted user to execute a command as the superuser or another user, as specified in the /etc/sudoers (config file that defines or list of who can run what) file. The sudo command allows users to do tasks on a Linux system as another user.

sudo command

sudo is more more secure than su command. By default it logs sudo usage, command and arguments in /var/log/secure (Red Hat/Fedora / CentOS Linux) or /var/log/auth.log (Ubuntu / Debian Linux).

If the invoking user is root or if the target user is the same as the invoking user, no password is required. Otherwise, sudo requires that users authenticate themselves with a password by default. Once a user has been authenticated, a timestamp is updated and the user may then use sudo without a password for a short period of time (15 minutes unless overridden in sudoers).

/etc/sudoers Syntax

Following is general syntax used by /etc/sudoers file:
USER HOSTNAME=COMMAND
Where,

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

  • USER: Name of normal user
  • HOSTNAME: Where command is allowed to run. It is the hostname of the system where this rule applies. sudo is designed so you can use one sudoers file on all of your systems. This space allows you to set per-host rules.
  • COMMAND: A simple filename allows the user to run the command with any arguments he/she wishes. However, you may also specify command line arguments (including wildcards). Alternately, you can specify “” to indicate that the command may only be run without command line arguments.

How do I use sudo?

Give user rokcy access to halt/shutdown command and restart Apache web server. First, Login as root user. Use visudo command edit the config file:
# visudo
Append the following lines to file:
rokcy localhost=/sbin/halt
rokcy dbserver=/etc/init.d/apache-perl restart
Save and close file . Now rokcy user can restart Apache web server by typing the following command:
$ sudo /etc/init.d/apache-perl restart
Output:

The sudo command has logged the attempt to the log file /var/log/secure or /var/log/auth.log file:
# tail -f /var/log/auth.log
Sample outputs:

If rokcy want to shutdown computer he needs to type command:
$ sudo /sbin/halt
Output:

Before running a command with sudo, users usually supply their password. Once authenticated, and if the /etc/sudoers configuration file permits the user access, then the command is run. sudo logs each command run.

Источник

How to run systemd service as specific user and group in Linux

Table of Contents

By default most of the systemd services are configured to run by root user but there is also an option to create a custom systemd service unit file and run it as a speciic user or group or both. So in this article we will check and verify the steps to run systemd service as specific user and group using CentOS/RHEL 7/8 Linux environment.

I have installed Oracle VirtualBox on a Linux server, where I will use a Virtual Machine with RHEL/CentOS 7/8 to verify the steps from this article.

Some more articles on similar topic:

Читайте также:  Как обновить windows server 2016 standard

Step 1: Overview on systemd

I hope you are already familiar with below topics

Step 2: Create user and Group

Now this is an optional steps assuming you already have your user and group ready for next steps. But if you do not then you can follow this article to create a new user and assign a custom group (primary or secondary) to the respective user.

Here I have already created a user deepak who is part of deepak and admin group

To verify the groups of any user

So we wish to create a systemd service unit file and run systemd service as specific user and group which for us will be deepak user part of admin group

Step 3: Create Sample Script

We will use our startup script from old articles with some tweaks to check and run systemd service as specific user and group in Linux

So in this script we have added an explicit check for user, so unless the user executing the script is » deepak «, the script will fail to execute. If successful the script will continue to write in /tmp/file for 3 minutes with 1 minute interval. This will also help us make sure that the script does not exits before completing it’s defined task

Change the ownership of the script file to deepak

Provide executable permission to the script

We will execute the script manually to make sure it works as expected

Step 4: Create unit file to run systemd service as specific user and group

Now as highlighted under step 1, I have already written another article with the steps to create a new systemd unit file. Here we will name our systemd unit file as run-as-user.service under /etc/systemd/system . Below is the content of run-as-user.service

Here we have defined User=deepak and Group=admin to make sure the script will be executed only as user deepak which is part of admin group.
You can also use many other directives if required in your environment such as WorkingDirectory , EnvironmentFile etc. For more information check man page of systemd.exec

Refresh the systemd configuration files

Next enable the service (if required) to start automatically at boot

Step 5: Verify the systemd unit file configuration

Now since we are done with the setting up of systemd. Let us verify our configuration. Before starting I have cleared the content of /tmp/file which is where our script /tmp/startup_script.sh will place dummy content every minutes for 3 minutes.

We will only start the run-as-user.service runtime as a reboot is not required to validate the configuration here:

Next check the status of the service

Well looks like everything was good as we were able to run systemd service as specific user and group, you can check the ps status to make sure our script is running using below command:

Now you can monitor the content of /tmp/file for couple of minutes as configured in the script

Lastly I hope the steps from the article to run systemd service as specific user and group in CentOS/RHEL 7/8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Related Searches: run service as user linux. systemd allow user to start service. systemd start service as user on boot. linux systemd service run as root. Restarting systemd service only as a specific user? systemd services fail with User= in service file. Start process as a specific user. how to run a service a non-root user completely?

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

19 thoughts on “How to run systemd service as specific user and group in Linux”

what is the “admin” group? I have a “root” group, but not an admin group.

admin group used here is an example

Shouldn’t systemd’s “–user” feature be used to allow non-root accounts run their own services — without bothering the root-wielding admin every time they want to change something?

I’d love an actual example of that…

Any application level service is executed by normal user such as apache

Man you really helped me thanks a lot dude!

Loved! Very well explained!

This is really helpful, thank you. It is also rather timely as I’m trying to get a service to work with a little twist and maybe you have some insight to this.

I’m running VirtualBox with a Ubuntu 20.04 guest and a Windows 10 host. The VM is defined with a shared folder on the host.
I need to run the service as my user and it has to create some files and directories in the shared folder.
There are some really weird things happening.
– I am unable to write anything to the shared folder when I run the script as a service. I always get “Permission Denied” errors.
No problem if I run the service as “sudo service xxx start”, only when it is started on system init. I specifically have an
“After=.mount” in the Init section.

Читайте также:  What is file locking in linux

– If I run using “+” before the script name on ExecStart, it runs as root and creates files, but then they just disappear. Actually,
they show up only in the script (e.g. if I issue an “ls” command) but by the time I get to log in, they are gone.

Anyway, I’m tearing what little hair I have out on this and can’t get anywhere. Any insight would be greatly appreciated.

Sorry, I didn’t realize I couldn’t use angle brackets. My “After=.mount” should have been “After=shared-folder-dir.mount”, copied from the systemctl list-units list.

Hi Alan,
If there is a requirement for a certain file system then instead of After= you should use RequiresMountsFor=/path/to/fs .
Few questions:
If you just run the script as the user, is the script able to perform write operations in the shared folder? – I assume yes?
Because if this works, there is no reason it will fail as systemctl service.
Or do you see problems writing at reboot stage?
If I have more information, I may try to replicate the behaviour in my environment.

I see there are lot of comments. Can you please consolidate and send me a mail

Thanks for the response and for taking a look at this, to answer your questions:

– Just running the service after I log in, everything works, I can write to the shared folder with the service.
– the really weird thing is that I have echo statements showing that when I run as root:
– I can write to the shared folder
– the script sees the files and directories via ls right after creation
– they go away at some point. there is no delete for these files anywhere, but some of them are accessed
by a java program that the script is calling. some are not. but they all disappear by the time I can log in
and look.

Thanks for sharing the additional information, I will not approve the script as that may be confidential.
Give me time till tomorrow, let me try to replicate this and come back. I am also little occupied with my office work.
I assume you are using samba for file sharing.
We can further communicate using your mail address. You can send mail to admin@golinuxcloud.com

First, Thanks a lot for this nice tutorial. This is what i am looking for.

But I faced a problem. In my one test VM, it works fine and then I have tried to do the same procedure in another machine (important vm) but the service has not started. I have tried to start the application manually it works fine (owner of statsup.sh is non-root user).

Then I commented out the User and Group in a Unit file under systemd and it works again. So I guess the problem is with the systemd service file. Kindly give me some idea what to do?

Thank you for your feedback.
Does if work if you try to start the application using the systemd service manually?
Did you checked “journalctl -b” logs for any hint?

One hint from Journalctl >> catalina.sh said permission denied (as my application call catalina.sh)
In my VM no tomcat service and owner of catalina.sh is root
but in my target machine (where i have problem) there is a tomcat service and its stopped and owner of catalina.sh is tomcat
And What does it mean to start the application using the systemd service manually? (i am a newbie)
Can you please give me any idea what to do?

I am not sure if I understand the scenario completely. On your target VM if your service is supposed to be started as root then you can remove the User and Group argument in the systemd unit file. The idea is to understand the requirement first, you mentioned that systemd service fails to start the service automatically so does that mean the service ends up being ‘dead’ or the service is not started at all.

Can the service use a domain user instead of the local user when running.
E.g We have a domain user that will have access to the MSSQL DB on some server
Our client machine is redhat linux on which tomcat is running as a service.
Our client machine is already added to the same domain as the MSSQL DB
The servlet in our tomcat needs to access the MSSQL DB
Instead of SQL Authentication, we want to use windows authentication for this purpose
Now how can we run the tomcat as the same domain user that has access to the MSSQL DB ?

You can just place the username in the User=USERNAME field without any domain details. For ex if your mysqldb user is dbadmin then just place User=dbadmin and it should work. Unless you also have a local user names dbadmin in which case there can be conflict so you will have to delete the local user.

How can I check whether we have systemd privileges or not ?

By default non root users don’t have privilege to use systemd to restart/start/stop services but they should have permission to check the status. You may try to restart any service such as sshd and if you don’t have privilege then the same should fail

Источник

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