Executing command with another user inside a shell script

6

I have a shell script that I need to execute some commands with a linux user, and some other commands with another user.

Something like this:


#!/bin/bash

  echo 'rodando com usuário A'
  comando1
  comando2
  comando3

  echo 'Rodando com Usuário B'
  sudo su comando4

The problem is that I would like to perform all the commands in the same script. But as soon as the command with the second user is started, a new session bash is started. Is it possible to run commands with 2 different users in the same script?

    
asked by anonymous 23.05.2014 / 21:54

3 answers

4

You can use su as follows to do this in shell script in>:

  
su -c "comando" -s /bin/sh nomedoUsuario

Where the -c parameter specifies to pass a single command to the shell and -s is used to specify what shell will call the command.

Another way to do this is to use sudo as follows:

sudo -H -u nomedoUsuario bash -c "comando" 

The -h parameter is a security policy that allows you to set the environment variable $HOME to the specified user ( root is by default ). -u specifies the user to execute the command.

 
  #!/bin/bash

  echo 'rodando com usuário A'
  sudo -H -u nomedoUsuario bash -c "Foo" 
  sudo -H -u nomedoUsuario bash -c "Bar" 

  echo 'Rodando com Usuário B'
  sudo -H -u nomedoUsuario bash -c "Baz" 
    
23.05.2014 / 22:23
1

I use the runuser command. Basic syntax: runuser -l usuario -c comando .

The commands below serve as a test, showing the current user and bash PID:

whoami && echo $$
sleep 2
runuser -l usuario1 -c "whoami && echo $$"
sleep 2
runuser -l usuario2 -c "whoami && echo $$"

For more information, run the command man runuser .

    
29.08.2014 / 01:04
-2

I was able to resolve with this command:

su otrs /opt/otrs/bin/otrs.Daemon.pl start -s /usr/bin/perl
    
23.03.2016 / 15:38