Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I Have created a shell script as given below.This script will login to a remote server as a normal user then switch to root user for creating a directory.The script is as given below.

ssh -t qbadmin@ '
su root -c "
echo \"Give Directory name :\";
read dir;
mkdir \$dir;

Here the script will ask Password for normal user first.Then again it will ask for root Password.How could I automate this using expect command.I want to supply the password automatically for the root user only.I think it can be done with expect.

Please do help me.

share|improve this question
What about authorized keys? More security! – prophecy201 Mar 19 '13 at 10:52

A better/easier way than using expect is SSHPASS, which sends a password through with an SSH request:

sshpass -p <PASSWORD> ssh <USER>@<SERVER> <SSH Command>

PASSWORD is the password to be entered when prompted, USER is the username, SERVER is the server IP Address (eg. and SSH Command is the command you want to execute.

For your example:

sshpass -p <PASSWORD> ssh qbadmin@ mkdir <full path for new dir>

To install SSHPASS

sudo apt-get install sshpass

If you are wanting the SSH session to remain afterwards than youc an use expect with the following,

##Enter Username and Password Details:

expect -c "
    spawn ssh ${useName}@ ##put your own IP here
    expect "password: " ##or whatever password prompt you get
    send "$password\r"
    epxect -re "Last Login: " ##or whatever the end of your welcome message is
    send "su -i"
    expect "password for <UserName>"
    send "$password\r"

This will leave the root access logged in, however until the script sends a return statement it will hold control until you hit "ctrl-c". But this should answer your question

share|improve this answer

If you want to pass only the root password, you have to

  • either configure a password-less login into the user account, e.g. using public key authentication and an ssh agent on the client side,
  • or configure the server (i.e. to allow login as root, and then do ssh -t root@ …
share|improve this answer

Your Answer


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.