简体   繁体   English

如何使用脚本切换用户以运行另一个脚本

[英]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. 我有一个脚本,它将以root身份执行,在脚本切换过程中,我想切换到某个用户(例如bob),并使用该用户的环境执行另一个脚本。 At the end of the script I want to switch back to root and execute more commands. 在脚本末尾,我想切换回root并执行更多命令。 I would like to run this script without having to enter the password for bob. 我想运行此脚本,而不必输入bob的密码。

This script will be provided to my AWS EC2 instance via the user-data feature at first time bootup. 该脚本将在首次启动时通过用户数据功能提供给我的AWS EC2实例。

I thought the way to do this was to use either sudo or su. 我认为做到这一点的方法是使用sudo或su。 However, I don't appear to have access to bob's environment with either of these methods. 但是,我似乎无法使用这两种方法访问bob的环境。

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.... 在下面的stdout echo中,您将看到环境变量myvar被初始化为Inara,但是当使用sudo执行此脚本时,该值未设置。

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: 模拟-u用户bob的-i初始环境:

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运行命令:

sudo su - bob -c [command]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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