Log into root from script?

hey! I use pm-suspend [aliased as “ram”] quite a lot on my laptop. It’s annoying to have to type


every time I want to do so. So, is there a way to give su or sudo the password via a parameter? like maybe

su --password=********** -c "ram"

that would be nice, but it doesn’t work. I even tried

echo "********" | su

but that also doesn’t work :frowning:
I’d appreciate any help, thanks!

Use sudo to give yourself permission to execute that command (and only that commnad) as root. You can then make a one word alias for the command. Look at some previous posts re sudo on this forum for examples. Also the man page for sudoers.

hmm, I’m not sure how to do that, I typed visudo,
and put in
%users ALL=/usr/sbin/pm-suspend
but that doesn’t seem to work. So, is there no way to log into root from a script? I mean, it has to be possible! (?)

That should work unless you forgot to add your userid to the %users

# User alias specification
User_Alias    USERS = your_userid
# or 
your_userid ALL = /usr/sbin/pm-suspend  
# also with caution 
your_userid ALL =  NOPASSWD: /usr/sbin/pm-suspend  
# preferred with caution 
your_userid localhost =  NOPASSWD: /usr/sbin/pm-suspend  


And remember you have to prefix the command with sudo, i.e.

sudo pm-suspend

But you can make an alias of that so that you can forget typing sudo.

Thanks! That works.
But, ok, so there’s no way to switch to root from a script? [Without prompting the user to type the password]? hm… I thought there would be a way, Somehow…

I think most would run script pm_suspend_alias, or sudo runscript.sh as ken_yap suggested.

The NOPASSWD should have allowed execution without being asked for a password.


IIUC, OP still wanted to know how to invoke a su command from within his script, which is simply adding that command into his script correct?

If you mean if there is a command that you put in the middle of a script and then all lines after that are executed as root, no it doesn’t work that way. Rootness is an attribute of the process. So you have to start another process whose owner id is root. So it would be a different script that you run. (Roughly speaking. One can think up of tricks to fold the commands into one script, but let’s not complicate things.)

But it’s not a good idea to give carte blanche to run a whole bunch of commands as root. The best practice is that the minimum of root privileged commands should be used.

That’s why I wrote, I thought most use sudo script.sh, sudo pm_suspend_alias or su -c “script.sh”.