SSH login expect shell script to supply username and password

in Categories Security last updated May 21, 2012

Expect is a Unix and Linux automation and testing tool. It works with interactive applications such as telnet, ftp, passwd, fsck, rlogin, tip, ssh, and many others. It uses Unix pseudo terminals to wrap up subprocesses transparently, allowing the automation of arbitrary applications that are accessed over a terminal. A simple expect script to supply OpenSSH root/admin password for remote ssh server and execute the Unix / Linux / BSD commands. First, you need to install expect tool by following these instructions.

#!/usr/bin/expect -f
# Expect script to supply root/admin password for remote ssh server 
# and execute command.
# This script needs three argument to(s) connect to remote server:
# password = Password of remote UNIX server, for root user.
# ipaddr = IP Addreess of remote UNIX server, no hostname
# scriptname = Path to remote script which will execute on remote server
# For example:
#  ./sshlogin.exp password who 
# ------------------------------------------------------------------------
# Copyright (c) 2004 nixCraft project <>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit for more information.
# ----------------------------------------------------------------------
# set Variables
set password [lrange $argv 0 0] 
set ipaddr [lrange $argv 1 1]   
set scriptname [lrange $argv 2 2] 
set arg1 [lrange $argv 3 3] 
set timeout -1   
# now connect to remote UNIX box (ipaddr) with given script to execute
spawn ssh root@$ipaddr $scriptname $arg1
match_max 100000
# Look for passwod prompt
expect "*?assword:*"
# Send password aka $password 
send -- "$password\r"
# send blank line (\r) to make sure we get back to gui
send -- "\r"
expect eof

Other options

  • Use sshpass command provide the password and username for ssh based login using the mode referred to as “keyboard-interactive” password authentication, but in non-interactive mode.
  • OpenSSH offers RSA and DSA authentication to remote systems without supplying a password. keychain is a special bash script designed to make key-based authentication incredibly convenient and flexible.

Share this on:

88 comment

  1. Hi,

    Im trying to connect to remote server through shell script..
    the script should connect to remote server “” with username and password automated and execute few commands. once job is done the script should exit from remote server….

    Please help me out….plz tell me the script to connect and exit…

    thanx in advance

  2. Sidh, connects to a remote machine but exits and comes back to my local directory. Any ideas on what I should be playing arnd with?

  3. Actually, I have written scripts that do similar things to this…usually though, I am trying to automate a task that needs to be done on several machines. A few comments:

    1. Passing a password on the command line is insecure. On most systems anyone can do a “ps” and get your password. I prefer to prompt once for the password, and then use it many times:
    stty -echo
    send_user “Password:\n”
    expect_user -re “(.*)\n”
    send_user “\n”
    set password $expect_out(1,string)
    stty echo

    2. ssh is a bit picky about whether its connected to a machine before. When you want your script to connect to tens or hundreds of machines… you don’t want to get bit by host keys. Try adding this ssh option:
    -o StrictHostKeyChecking=no

    3. You may need to connect multiple times. This is inefficient. Recent ssh versions (past several years) allow for control master connections, this allows you to open 1 connection and use it several times… add these ssh options:
    -o ControlPath=/tmp/autocm-%r-%h-%p -o ControlMaster=auto

    Then spawn the first ssh connection as normal, send the password, and then just leave it alone until its time to shut down the connection. Each new ssh session, that you spawn with the same options, will use that connection… with no password. Its much faster!

  4. Hi all,
    my request is to logon(telnet) large number of network hosts ( router) to capture system’s inforation.
    when the script issue the telnet session, could it read from a text file that listed all host’s IP address? what is the command of reading file?
    question 2.
    when logon to host successfully, how to export the result of command capturing to a text file?
    thanks in advance!!

  5. Hi all,

    any idea how to make the script check whether the ssh connection is already established, and when not to re-establish it? Having some problems here with servers from university with questionable reliability..

    Greetings & thanks in advance.

  6. Hello all,

    Can anyone tell me the expect command to stop displaying at the console and enable it back when needed. i did try to use “stty -echo” assuming that it would help me, but in vain.

    For ex: when i use the below
    spawn ssh $host1
    in the script, it does display and i want to filter these.

    Thanks in advance.


  7. can anyone provide script that will ask me to enter the hostname or IP address that I want to connect to the script would then connect to the host using ssh version 2 & I would then be prompt to enter my user credentials.

    please enter host or IP address.


    I want to use this server as central point to access all devices on my network I would connect to this box from this box jump to any other device on my network

  8. hello

    I have the same question as Elliott… I got a ssh command that retruns an error code and I would like to get it…
    What are the possibilities ?

  9. Is there a way to capture the return code for any of these scripts?

    for example if i ran

    lss instead of ls , on another server,

    i want it to return or be able to check to see if there was an error (non zero)

    thanks :)

    1. hi,

      on linux server you can check the process id for ssh. If the process id is not found then you can initiate the ssh process. This entire thing can be handle through (perl/bash)script.

    1. You may very well run a cron job and use ssh to exeute sar or collect sar logs . You may just need expect if you don have key based authentication .

    2. @hozifa

      if you want to do using perl then you can use the following steps in script


      @arr = `vmstat`;
      @spl = split(” “,$arr[2]);
      print $spl[3].”\n”;

      $spl[3] will give you the free memory of the system.
      To run it every 10 minutes, you can schedule the script in crontab that will run at interval of 10 minutes and output the data in a log file

      Hope this helps!

  10. Create a file named “” with below contents

    VAR=$(expect -c "
    spawn ssh -o StrictHostKeyChecking=no $USER@$HOST $CMD
    match_max 100000
    expect \"*?assword:*\"
    send -- \"$PASS\r\"
    send -- \"\r\"
    expect eof
    echo "==============="
    echo "$VAR"

    Later make it executable:

    chmod +x  

    Try this as below:

    ./ "ls -l"


    ./ 'ls -l'
    1. Absolutely spot on! Is there anyway to use an encrypted or shadow password file though, rather than just having it in plain text in the script?

      Works like a dream though – thank you.

  11. Changing set scriptname [lrange $argv 2 2] to set scriptname [lindex $argv 2] you should be able to run ssh user@host ‘ls -a’ and others commands within ‘ ‘ with no need to another variable.

  12. Does anybody know how to modify this script so that it can run a script on a remote host so that it returns a message from the script? many thanks

  13. I want to telnet to a remote m/c and enable events on that m/c.I used expect script to telnet and enable the events, but i dont see any events coming on the screen.Pls help.

    #!/usr/local/bin/expect —

    set host1 “”
    set login “user”
    set passwd “passwd”
    spawn telnet $host1
    expect “login:”
    send “$login\r”
    expect “Password:”
    send “$passwd\r”
    expect “prompt>”
    expect “TeMIP>”
    send “enable events\r”
    expect “*” ### wht shud I give here to see all events ??
    sleep 3600

    1. I want to learn about ssh in deap i want to knw about a cmand that would enable me tn knw whch user has logd on to my account in lan usng linux systems ubuntu is the ostype

  14. I ran the script. it worked for me. But after logging in when i type the command it logging out immediately. Tell me a solution..

Leave a Comment