简体   繁体   English

如何在bash脚本中以su模式运行命令?

[英]How to run command in su mode in bash script?

I need to run these two commands : 我需要运行以下两个命令:

ulimit -s 1024 ulimit -s 1024

echo 120000 > /proc/sys/kernel/threads-max 回声120000> / proc / sys / kernel / threads-max

The first one can be run just in user mode (not using sudo or su) and the second can only be run in su mode . 第一个只能在用户模式下运行(不使用sudo或su),第二个只能在su mode运行。 I want to write a bash script that let me run these two commands. 我想编写一个bash脚本,让我运行这两个命令。 The first one is OK. 第一个是好的。 For the second one, I need to su (change user to root), run the command, and then exit. 对于第二个,我需要su(将用户更改为root),运行命令,然后退出。 Actually, I want to run the second command in su mode using a bash script. 实际上,我想使用bash脚本在su模式下运行第二个命令。 Any idea? 任何想法?

如果您的用户有权使用“ sudo tee”,那么一种解决方案是:

echo 120000 | sudo tee /proc/sys/kernel/threads-max

As a security measure, you cannot run scripts as a superuser without prepending sudo . 为了安全起见,您必须先添加sudo才能以超级用户身份运行脚本。 If you want it to be passwordless, you need to run visudo and allow your (or the executing user) to run this command as a superuser without password confirmation. 如果希望它是无密码的,则需要运行visudo并允许您(或执行用户)以超级用户身份运行此命令而无需密码确认。

The other way is to use the setuid bit on compiled code. 另一种方法是在编译的代码上使用setuid位。 Compile a simple program which will execute the echo 120000 > /proc/... , then change it to be owned by root: chown 0:0 executable_name , and chmod u+s executable_name to set the setuid bit on it. 编译一个简单的程序,该程序将执行echo 120000 > /proc/... ,然后将其更改为由root拥有: chown 0:0 executable_namechmod u+s executable_name在其上设置setuid位。 This will cause execution of this program to be ran with permissions of its owner, which is root. 这将导致该程序的执行在其所有者(即root)的许可下运行。

This is the same way which allows passwd to modify a file which requires super-user privileges without actually being a super-user or sudoer. 这与允许passwd修改需要超级用户特权而不实际成为超级用户或sudoer的文件的方式相同。

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

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