0

I need to run these two commands :

ulimit -s 1024

echo 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. I want to write a bash script that let me run these two commands. The first one is OK. For the second one, I need to su (change user to root), run the command, and then exit. Actually, I want to run the second command in su mode using a bash script. Any idea?

Community
  • 1
  • 1
moorara
  • 3,897
  • 10
  • 47
  • 60
  • Did you know you can run the entire script with su (root) privileges to run all the commands it contains with the same privileges? If you did, any reason you're avoiding doing this? – ffledgling Nov 29 '13 at 18:58

2 Answers2

2

If your user has permission to use "sudo tee", then one solution is:

echo 120000 | sudo tee /proc/sys/kernel/threads-max
John1024
  • 109,961
  • 14
  • 137
  • 171
  • I think you want a pipe instead of `>`. – Gordon Davisson Nov 29 '13 at 22:51
  • I feel the answers too specific. The question is more "I have some commands to launch, maybe with spaces, maybe with pipe, maybe with indirections" How can I `su user -c` without parsing problem... – Sandburg Jan 31 '19 at 09:36
1

As a security measure, you cannot run scripts as a superuser without prepending 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.

The other way is to use the setuid bit on compiled code. 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. This will cause execution of this program to be ran with permissions of its owner, which is 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.

micromoses
  • 6,747
  • 2
  • 20
  • 29
  • see wikipedia entry http://en.wikipedia.org/wiki/Setuid. It says "many operating systems ignore the setuid attribute when applied to executable shell scripts.". I've experienced it to be the case on my system (Ubuntu 14.04) – tivoni Jun 16 '14 at 07:41
  • This is not only true for Ubuntu, this is how most (if not all) linux distribution behave. This is true for other UNIX operating systems as well. For that reason, as I have written in the answer, you have to *compile* a program. Writing a shell script and compiling a program are two different things. – micromoses Jun 16 '14 at 10:06