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.
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
Storing the cleartext of the root password in a file is inherently dangerous - there are lots of routes by which it can be recovered.
This appears to be an XY problem.
The unixy way of delegating permissions is via the setuid bit - but this can only be applied to binary executables, not shell scripts. As jordanm states, applying setuid to the shell itself is very dangerous - that's why sudo exists - it has a setuid bit and validates user requests against the sudoers file to give a fine-grained control over access. But sudo also has some gotchas.
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
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.
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)