SSH login expect shell script to supply username and password

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.
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics via:
Category List of Unix and Linux commands
File Management cat
Firewall Alpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN Alpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
88 comments… add one
  • Sabarish Jul 8, 2016 @ 10:17



    set password “xxxxXxx”

    if [ -n “${SOURCE_FILES}” ]


    for f in ${SOURCE_FILES}


    cp -prf ${f} ${DESTINATION}


    spawn sftp ${USER}@${HOST}:${CHANGEDIRECTORY} << ${SFTPLOGS}/sftplogs_${LOG_DATE}.log

    expect “Password”

    send “$Passwordr”




    Is the above script okay?

  • LearningExpect Jul 3, 2014 @ 14:10

    I have a problem with Expect. I am supposed to do the following task which involves running a command script in Solaris. This command then asks the user two passwords (one after another). I am using Expect to do this task. However, I am unable to get the desired output and the script is failing. It is unable to send the password values

    set pri_user_password [lindex $argv 0]
    set sec_user_password [lindex $argv 1]

    spawn -f
    expect “Password for property local_service_password : ” {
    send “$pri_user_passwordr” }
    expect “Password for property remote_service_password: ” {
    send “$sec_user_passwordr” }

    Can you tell me what the problem might be?

  • sporo Jul 16, 2013 @ 12:15

    Hi Guys, can someone help with this:

    set user “touch”;

    set password “1touch@1”;

    set gateway “”;

    spawn /usr/bin/ssh -L 22:localhost:22 $user@$gateway

    But this doesn’t work and i seem to be getting no result but this:

    usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]

    [-D [bind_address:]port] [-e escape_char] [-F configfile]

    [-i identity_file] [-L [bind_address:]port:host:hostport]

    [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]

    [-R [bind_address:]port:host:hostport] [-S ctl_path]

    [-w tunnel:tunnel] [user@]hostname [command]

  • Raghava Oct 18, 2012 @ 13:54

    I installed sshdpass tool in RHEL and trying to connect another RHEL machine where sshd is running. I am able to connect when I run $ sshpass -p” ssh root@IP but not connecting to that IP when I tried by placing the same line in a file and called it through sudo command. It thrown error.. line 4: sshpass: command not found

    Please guide me the solution if any one know.

    • Abhinav Chittora Jan 9, 2013 @ 1:38

      Hi Raghava,

      You should try full path to sshpass i.e. /usr/bin/sshpass. Since it may be the reason that the shell, which is running your script is not looking for the directory in which sshpass is located. Using absolute path is always prefered way to use any such command.

      Abhinav Chittora

  • Michelle Kelly Sep 25, 2012 @ 17:39

    I am new to autoexpect and I am having issues with the script that I have created. The process does not complete fully and I am not sure how to fix this. It will not move the database files into the appropriate location.

    spawn /bin/bash
    [root@hp36ed01 bin]# ./installdb_unc
    logname: no login name

    — Universal Addressing Module Installation —

    The environment for Database Installation is currently set to:

    Distribution type: cd
    Mounted CD directory: /holding/UNC/db

    Press enter to continue.

    CDQ Platform – Universal Addressing Module Installation Menu

    1. US Subscription
    2. Canadian Subscription
    3. International Subscription

    99. Exit

    Enter the number of the product that you want to load
    the subscription database for and then press enter: 1

    US Postal Database Menu
    Database Installation

    1. Subscription Database
    2. Delivery Point Validation
    3. Residential Delivery Indicator
    4. Early Warning System
    5. LACSLink Database
    6. SuiteLink Database

    99. Exit

    Enter the number of the type of data you want to load
    and then press enter: 1

    The database load environment is currently set to:

    Database input file location: /holding/UNC/db
    Database output location: /opt/UNC

    Enter c to (c)ontinue
    or m to (m)odify database input/output locations
    or q to (q)uit

    ===> m

    Which do you want to change?

    Enter 1 to change the input file location
    or 2 to change the database output location
    or 3 to change both

    ===> 2

    Please enter full path where you would like to install
    the CODE-1 Plus database ==> /usr/UNC/db/test12012

    The new CODE-1 Plus database location will be: /usr/UNC/db/test12012
    Is this correct?

    Enter (y)es to continue.
    (n)o to try again.

    ===> y
    /opt/UNC/server/bin/setup is updated.
    /opt/UNC/server/bin/setup is updated.

    Do you wish to load the optional ELOT file?
    Enter (y)es

    ===> n

    Installed on Tue Sep 25 12:23:01 CDT 2012

    Creating CODE-1 Plus Database
    Which do you want to change?\r
    Enter 1 to change the input file location\r
    or 2 to change the database output location\r
    or 3 to change both\r
    ===> ”
    send — “2\r”
    expect -exact “2\r
    Please enter full path where you would like to install\r
    the CODE-1 Plus database ==> ”
    send — “/usr/UNC/db/test12012\r”
    expect -exact “/usr/UNC/db/test12012\r
    The new CODE-1 Plus database location will be: /usr/UNC/db/test12012\r
    Is this correct?\r
    Enter (y)es to continue.\r
    (n)o to try again.\r
    ===> ”
    send — “y\r”
    expect -exact “y\r
    /opt/UNC/server/bin/setup is updated.\r
    /opt/UNC/server/bin/setup is updated.\r
    Do you wish to load the optional ELOT file?\r
    Enter (y)es\r
    ===> ”
    send — “n\r”
    expect -exact “n\r
    Installed on Tue Sep 25 12:21:28 CDT 2012\r
    Creating CODE-1 Plus Database\r
    [?47h[r[m[2J[H[?7h[?1;3;4;6l[?1h[m[H[2J[24;1H[H[2JPlease press Enter to continue…..\r

    send — “\r”
    expect -exact “\r
    Database loading. Please wait….\r
    [1;1H \r
    Tue Sep 25 12:22:19 CDT 2012\r
    ]0;root@hp36ed01:/opt/UNC/server/bin\[root@hp36ed01 bin\]# ”
    send — “”
    expect eof

    I should see several files in the /usr/UNC/db/test12012 location. After the script runs I dont see the files. Any help will be appreciated. Thanks in advance!

  • Piviul Sep 11, 2012 @ 8:41

    …oops I’ve found that doesn’t work if used with scp like “./bin/pwd_cmd.exp password scp root@host:/path /ptah/to/dest” because I can’t write : in a argument… :(((


Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.