简体   繁体   中英

How to switch users with script to run another script

I have a script that will be executed as root, part way through the script I would like to switch to a user (say, bob) and execute another script using that user's environment. At the end of the script I want to switch back to root and execute more commands. I would like to run this script without having to enter the password for bob.

This script will be provided to my AWS EC2 instance via the user-data feature at first time bootup.

I thought the way to do this was to use either sudo or su. However, I don't appear to have access to bob's environment with either of these methods.

In the stdout echo below, you'll see that the environment variable myvar is initialized to Inara but when this script is executed with sudo, that value is unset....

dave@bugbear:~/workspaces/sandbox$ su --login bob
Password: 
bob@bugbear:~$ cat bin/echo.sh
#!/bin/bash

echo "In echo.sh.. myvar is {$myvar}"

echo "Now executing the ruby script"
. ~/.bashrc
~/bin/echo.rb
bob@bugbear:~$ cat bin/echo.rb
#!/usr/bin/env ruby
puts "$myvar is: #{ENV['myvar']}"

bob@bugbear:~$ bin/echo.sh
In echo.sh.. myvar is {Inara}
Now executing the ruby script
$myvar is: Inara
bob@bugbear:~$ exit
logout

dave@bugbear:~/workspaces/sandbox$ cat test.sh 
#!/bin/bash
stty echo
sudo --login -u bob bin/echo.sh

dave@bugbear:~/workspaces/sandbox$ ./test.sh
In echo.sh.. myvar is {}
Now executing the ruby script
$myvar is: 

You are probably looking for one of these:

Simulate the -i initial environment of -u user bob:

sudo -i -u bob [command]

Or, use sudo to gain the required privilege to use su and ask it to - start a login shell as bob (without the bare - you're not doing that) and -c run a command:

sudo su - bob -c [command]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM