Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can we write a shell script to become root? That is I donot want to input the password at prompt it should be within the script itself. I was trying to make but failed to do so.Is it possible, if Yes please Explain.

share|improve this question
    
Does it need to be a shell script? I don't see how that would be possible, but you could set it up so sudo su or sudo bash works without a password –  Michael Mrozek Oct 19 '12 at 17:36
    
@MichaelMrozek sudo -i is preferred. It requires permissions to run sudo bash. –  jordanm Oct 19 '12 at 19:16
add comment

3 Answers

up vote 1 down vote accepted

You can write a script using expect tool.

In Redhat, expect package comes by default. But in Ubuntu you need to install it separately.

You can check this by using commands:

$ rpm -qa | grep expect for Redhat

$ dpkg -l expect for Ubuntu

The following script will do your work:

#!/usr/bin/expect

spawn su -
expect "Password: "
send "password\r"
interact
share|improve this answer
add comment

The simplest way is to make a suid copy of the shell:

cp /bin/bash $HOME/bin/becomeroot
sudo chown root $HOME/bin/becomeroot
sudo chmod 4750 $HOME/bin/becomeroot
hash -r

Then, running becomeroot will start a bash subshell running as root.

However, I would be remiss if I didn't give you this advice: don't do that. It's unwise to make it so easy for malware to escalate its privileges to root. Instead, just install sudo and learn to use it whenever you need to run something as root.

share|improve this answer
add comment

You can set the SUID sticky bit:

chmod 2664 your-file

That will cause the software to run as the owner of the file. So of course, you'll have to change ownership to root:

sudo chown root your-file

(assuming you are found in the sudoers file, and you've installed sudo)

share|improve this answer
    
setuid does not work on shell scripts unless you setuid the shell binary (not recommended). –  jordanm Oct 19 '12 at 19:17
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.