Saturday, November 2, 2013

How to login as root in your shell using bash script ?

Whenever I need to login as root in bash I use su command.
What if I need to login as root using a bash script?? After the command bash prompts for password.
I tried to write a bash script for the same but could not. I did some googling again got no solution. Then I remembered about a shell utility Expect. I installed it and wrote some simple scripts.
spawn su
expect "Password: "
send "rootpassword\r"
expect "#"
interact
With this script we are left logged into the root and we can run any bash commands there after.
I wrote the next one by mixing bash and expect.
#!/bin/bash
/usr/bin/expect << EOD
set timeout 120
spawn su
expect "Password: "
send "rootpassword\r"
expect "#"
EOD
echo "\r"
ls
But with this we are logged out (we can't interact in the shell as root) after completion of the script.

1 comment:

  1. Nice code, but I have been doing it in a much easier way:

    echo "yourPassword" | sudo -S your-command

    after that you can just put sudo infront of other commands.

    ReplyDelete