How to Use Expect In Bash Script

In this bash script we will use expect scripting. Expect is known primarily as an indispensable application for system administrators. We use expect generally in case where input from user is required , for eg. ssh, ftp, telnet, sudo etc.

Given below is sample bash script which will first ssh the remote host and then get command output from remote host (here, we used uname -a command at Step )

Step 1 : Create a new file.

vi expectcmd

Step 2 : Copy and paste below given content in file.
Change the value as per your information in variables –

HOST=Give Remote Hostname
USER=Give Remote Host user name
PASS=Give user’s password

#!/bin/bash
HOST="localhost"
USER="chitti"
PASS="123"
CMD=$@
XYZ=$(expect -c "
spawn ssh $USER@$HOST
expect \"password:\"
send \"$PASS\r\"
expect \"\\\\$\"
send \"$CMD\r\"
expect -re \"$USER.*\"
send \"logout\"
")

echo "$XYZ"

And at the end, save the file.

Step 3: Make your file executable by owner of file , run the given below command.

chmod 750 expectcmd

Step 4: Give commands as argument along with expectcmd script. See below given example.
Note: (Try this command to get kernel info of Remote machine)

sh expectcmd "uname -a"

See the below given screenshot for reference.

expect command

10 thoughts on “How to Use Expect In Bash Script”

  1. help:
    I have servers hostname with 2 different domain suffix
    like :
    test12345.servera.com
    test12345.serverb.com
    how to diclare the domain variable on expect script; if server.com not login then login to server.com

    help needed urgent

    Reply
  2. Hi thanks for this tutorial, however, I am getting this error, could you please help me here?
    ran command like this: sh expectcmd “uname -a”
    output:
    usage: send [args] string
    while executing
    “send ”
    spawn ssh hadoop[at]some-ip
    hadoop[at]some-ip’s password:

    Reply
    • The “r” characters in the variables usage fields of the “send” portions of the script need to be preceeded by the “\” character. Please see the “cat expectcmd” example for exact syntax that bash is expecting. I also had same issue as I’m relatively new with bash scripting…hope this helps.

      Reply
  3. hi,
    this isfine to run 1 command uname -a, but if i want to 5 commands and in 50> servers, ho to do it..I tried different ways, but not working….

    Reply
  4. You either made a bunch of mistakes in the code you wrote above or your code was screwed by the webpage, first of all

    send “$PASSr” -> send “$PASSr” given that your password is $PASS and you want to do enter “r” after it

    Second all the commands inside the main quotation marks are escaped (ie ” -> “). For instace

    expect -c “spawn ssh -Y user@service.server.domain
    expect “Password:”
    send “$PSSWDr”
    interact”

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.