简体   繁体   English

使用sudo命令时是否应该首先获取文件?

[英]Is it possible that when using sudo command it should first source a file?

I need to run a bunch of scripts (with sudo) that use a single file.sh as a configuration file for all. 我需要运行一堆使用sudo的脚本(使用sudo)作为所有的配置文件。 Initially I've put the file.sh in /etc/profile.d and when I ran the scripts as root everything was ok (because when I connected to the machine it first sourced the file.sh and all vars in that file were available) but now, for security reasons, I need to run them with another user with sudo rights. 最初,我将file.sh放在/etc/profile.d中,当我以root身份运行脚本时,一切正常(因为当我连接到计算机时,它首先获取了file.sh,并且该文件中的所有var都可用),但现在出于安全原因,我需要与其他具有sudo权限的用户一起运行它们。

When running with sudo the "configuration file" in /etc/profile.d does not get sourced even if I'm root and do sudo - it's the same. 当使用sudo运行时,即使我是root并执行sudo,/ etc / profile.d中的“配置文件”也不会被获取-相同。

Using "sudo -E" is not an option, also this kind of solution "Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy"" does not work for me as the vars in the file change a lot and it's easier to throw a file, with all the vars, in a location - like /etc/profile.d/ - instead to adding options to /etc/sudoers. 不能使用“ sudo -E”,这种解决方案“ Defaults env_keep + =” ftp_proxy http_proxy https_proxy no_proxy“”对我不起作用,因为文件中的var发生了很大变化,并且更容易抛出文件,与所有var一起放置在/etc/profile.d/之类的位置,而不是在/ etc / sudoers中添加选项。

Later Edit (working): 以后编辑(工作):

Moved original sudo command to sudo.orig. 将原始sudo命令移至sudo.orig。 Created a new sudo bash script 创建了一个新的sudo bash脚本

[root@NS1 bin]# cat sudo
#!/bin/bash
source /etc/profile.d/set_env_vmdeploy.sh
sh /usr/bin/sudo.orig "$@"

and gave it permissions 并赋予它权限

[root@NS1 bin]# chmod 4111 sudo
[root@NS1 bin]# ll sudo*
---s--x--x 1 root root     78 May  7 13:42 sudo
---s--x--x 1 root root 123832 Jul 31  2014 sudo.orig

If you want sudo to execute all the profile scripts in the child shell, you can tell it to invoke the shell as a login shell: sudo -i /usr/local/bin/my_script.sh . 如果要sudo执行子外壳程序中的所有配置文件脚本,则可以告诉它调用该外壳程序作为登录外壳程序: sudo -i /usr/local/bin/my_script.sh (Note that the child shell will start with the working directory set to /root , and also that this may have other unintended side effects.) (请注意,子外壳程序将以工作目录设置为/root开头,并且还会产生其他意外的副作用。)

Alternatively, invoke bash explicitly with a command parameter: sudo /bin/bash -c "source ./config.sh; ./real_script.sh" . 或者,使用命令参数显式调用bash: sudo /bin/bash -c "source ./config.sh; ./real_script.sh"

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

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