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
Disk space analyzers df ncdu pydf
File Management cat tree
Firewall Alpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities NetHogs 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… :(((


  • Piviul Sep 11, 2012 @ 8:09

    Hi all, I would like to write an expect script useful every time a command ask for a password (ssh, scp, sshfs…) so I have modified the original script:

    $ cat ./bin/pwd_cmd.exp
    # set Variables
    set password [lrange $argv 0 0]
    set command [lrange $argv 1 1]
    set arg1 [lrange $argv 2 2]
    set arg2 [lrange $argv 3 3]
    set arg3 [lrange $argv 4 4]
    set arg4 [lrange $argv 5 5]
    set arg5 [lrange $argv 6 6]
    set arg6 [lrange $argv 7 7]
    set timeout -1
    # now connect to remote UNIX box (ipaddr) with given script to execute
    spawn $command $arg1 $arg2 $arg3 $arg4 $arg5 $arg6
    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

    There is no way to remove the limit of define a maximum number of arguments to pass to the command? I’ve tried to create a unique variable for all the arguments in this way “set args [lrange $argv 2 $argc]” but doesn’t works.



  • Helkar Aug 29, 2012 @ 18:18

    Hi all,

    I have the same problem as Fayiz with a very similar script. Could you please tell me how can i resolve this problem?

    Thanks in advance

    Best Regards,

  • Mangesh Jul 20, 2012 @ 14:28

    Hi All,

    I have used above code to copy file from local machine to remote machine sftp code,its worked fine Thanks
    but now I got challenge that if I provide wrong userid/pass cript not work its hang and even not give any error message , please how to solve this issue or any pointer to validate user id pass if code is expect.
    ]# ./Host_Monitoring.ksh
    spawn sftp user@
    Connecting to …
    @’s password:
    Permission denied, please try again.
    @’s password:

    Mangesh Kharade

  • CheBrian May 21, 2012 @ 12:02

    simple Ex : for expect :

    expect <<EOF
    spawn  ssh uid@server_name
    expect "uid@server_name's password:" 
    send "pwd\n"
    sleep 8
    send "logout\n"


    use sshpass option

    sshpass -p "pwd" ssh uid@server_name ls -la
  • Justin May 8, 2012 @ 17:06

    Thanks Vivek! I hard-coded my complicated passwords/usernames/server addresses and now have a one click and I’m in solution. Thanks again!

  • NITESH May 4, 2012 @ 15:13

    Hello All,
    I have an issue. It would be great if anyone could help; I need to SSH to a remote machine and execute a specific command there and capture its output.
    As per the above mentioned stuff, i should be able use the following syntax for SSH:
    ssh user@IP
    and use expect to supply the^password.
    But my remote machine is not a STANDARD unix machine and hence i can not execute the command like this in one step.
    I need to SSH to this server and then execute the command as a second step. I am new to EXPECT. Please suggest.
    Thanks in advance

  • zam Apr 14, 2012 @ 17:25

    Can any one please help me to develop a shell script for ssh login

    Here is the ssh credentials
    1)ip address

  • toto Mar 27, 2012 @ 7:23

    thank you very much for this script. this very help me to setting my network

  • Anonymous Feb 24, 2012 @ 16:26

    That worked beautifully. Thanks :)

  • Fayiz Feb 18, 2012 @ 4:14

    Hi all.

    This script works fine with most of the server .but one of the server log in password contain ‘$’ symbol (pass123$) on that server this script failed. so i did debugging i got following things.

    fayiz@testserver3’s password:
    expect: does “fayiz@testserver3’s password: ” (spawn_id exp6) match glob pattern “*?assword:*”? yes
    expect: set expect_out(0,string) “fayiz@testserver3’s password: ”
    expect: set expect_out(spawn_id) “exp6”
    expect: set expect_out(buffer) “fayiz@testserver3’s password: ”
    send: sending “{pass123$}\r” to { exp6 }
    send: sending “\r” to { exp6 }

    Permission denied, please try again.
    fayiz@testserver3’s password:

    Here you can see expect is sending {pass123$} instead of pass123$.Any body know how to resolve this issue?

  • sachin Feb 8, 2012 @ 18:36

    how can i get passwd and authorization from server on request using shell script

  • Anonymous Jan 31, 2012 @ 10:56

    Hi all!
    I have a problem:
    I need to use this script to send a command on a Windows Machine, but I also need to check errorlevel, but If I send a multiple commands, as for example:
    dirr && echo %errorlevel% I always received error 0, even if command “dirr” is wrong.
    How I can check errorlevel??

  • Suman Dec 2, 2011 @ 18:56

    hellow i want to connect my ssh server using a shell script
    usually i connect ssh -l username
    then it wants my passwrd
    and the connection is being established….

  • Sriharsha Jun 18, 2011 @ 9:32

    Need help…

    Sorry for long message/comment

    I have to connect to a remote server and run a script over there, which will generate a file. I need to copy that file back to my linux machine and delete the original one.

    This is the code I wrote to connect and run the script

    #!/usr/bin/expect -f

    set myserver root@x.x.x.x
    set pass xxxx
    set dir /home/myuser/runScripts/
    set runscript constructTextFile

    # Script in the remote machine takes an argument and uses
    # to name the generated file
    set arg1 [lrange $argv 0 0]

    # This is to find out the exact file I need to copy back
    set filename “ls .$dir | grep *$arg1*.txt”

    # Script in remote machine takesn an argument – arg1
    spawn ssh $myserver $dir$runscript $arg1
    match_max 100000
    expect “*?assword:*”
    send — “$pass\r”
    send — “\r”
    expect eof

    (1) It connects successfully and runs the script for about 10 seconds and then closes the connection. Script takes a max of 10 minutes to generate .txt file. How should I buy that time?

    Initially it worked fine. But I messed it up by adding copy and removing sections to the script.

    (2) I used scp to copy file back to my linux machine

    scp $dir$filename username@localmachine:path/to/destination

    This works fine. But I need to enter password every time. This script will be used by others also. So I can’t use ‘expect’ here and ‘send’ the password of the local machine. Is there an way to overcome this? Or should this script another argument of users password!

    Thanks a ton in advance…

    • Liam Aug 12, 2011 @ 9:47

      Hey Guys

      Can you help me out please. I am having trouble with the script below. The password isn’t being entered automatically by the script.

      I need to flush the dns cache every couple of hours and I can only do it from the root username. This script works ok when run from the root directory.

      Any help would be appreciated.

      Thank you

      # Flush DNS Cache

      set pass xxxx

      echo “Starting DNS Flush”

      su root
      expect “Password:*”

      send — “$pass\r”

      cd /etc/init.d
      ./nscd restart

      echo “DNS Flush details above”

    • Anonymous Aug 17, 2011 @ 20:30

      expect has a default timeout of 10 seconds.. set value to infinite (until the process is complete or set some value which is good for you) using below command (note: place this command after all set properties):

      set timeout -1

  • anomie May 27, 2011 @ 23:28

    Nice one, Vivek. Never thought I’d need to use expect in this fashion, but your script was so helpful for a task I worked on today.

  • tomsib May 11, 2011 @ 10:06

    I receive an error : line 11: expect: command not found

    and the same one with the command send.
    Is there some package I should load ?
    Thanks in advance

    • Jan Palach Jun 8, 2011 @ 17:52

      Put this in the first line of your script:

      #!/usr/bin/expect -f

    • Anonymous Jun 23, 2011 @ 0:20

      you have to install expect by sudo aptitude install expect

  • sam Mar 7, 2011 @ 11:08

    yes, the script logs in and logs out to local host :( plz help….. i have lot of servers to login :(

    • Norman Lund Apr 20, 2011 @ 16:52

      Someone’s not setting ipaddr correctly…

      # 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

    • Varun May 12, 2011 @ 11:51

      Change this line
      spawn ssh root@$ipaddr $scriptname $arg1
      spawn ssh root@$ipaddr

  • Sam Mar 1, 2011 @ 14:12


    Expect works great. However, I have a further question for linux gurus.

    I need to make connection to two servers

    I have created 2 .sh script. and I want to execute it within single window. By doing this I should be able to log into the second server where I exactly work. First server is route to second one so I cannot access second server directly. So, any help?

    Thanks in Advance.

  • sahil Feb 28, 2011 @ 5:21

    i want to access a web page stored on a linux server from widows machine
    kindly help

    • Vikrant Dec 21, 2011 @ 8:50

      May be you can try using Cygwin on your windows box

  • vinodkumar Feb 10, 2011 @ 21:23

    hi need some help

    I am trying to write a script which can telnet in to a server with my credentials

    and execute a command and read the out put and check for paticular set of a data and write

    it in to a file.

    Currently i am able login in to the system, execute a the command and capture all the out put of the command in to a file. Need some help in parsing specific information from the command output and write it in to file.

    Please suggest me how can i capture specific output using EXPECT ?

    Expecting some inputs from you guys… thanks

  • Praveen Feb 4, 2011 @ 7:05


    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

    • Smart Ass Feb 25, 2011 @ 22:31

      I’m sorry, Did you not read the post?

  • Katrina Nov 23, 2010 @ 22:40

    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?

  • Stephen Carpenter Oct 19, 2010 @ 19:49

    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!

  • Keyur Aug 25, 2010 @ 8:09

    Thanks Sidh! – works like a charm for me :-)

  • andrew Jul 20, 2010 @ 1:38

    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!!

  • Brian Jul 19, 2010 @ 15:33

    Does anyone know to loop this script for say 100 hosts at the same time?

  • aNkh Jun 20, 2010 @ 21:08

    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.

  • Nag Jun 17, 2010 @ 9:12

    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.


  • GeoStigma Jun 16, 2010 @ 16:40

    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

  • Mel May 28, 2010 @ 1:33


    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 ?

  • Elliott Mar 16, 2010 @ 19:19

    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 :)

    • Tony Aug 16, 2010 @ 8:09

      lls && echo ok || echo nok

  • sanuks Feb 18, 2010 @ 15:56

    is there any way to make sure that the process i.e logging into an ssh, runs in background

    • manish Mar 27, 2010 @ 7:34


      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.

  • hozifa Jan 23, 2010 @ 14:08

    I have a question, who can I List displays system memory utilization (free) every 10 minutes.

    thank u for ur help

    • charles Mar 22, 2010 @ 20:21

      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 .

    • manish Mar 27, 2010 @ 7:22


      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!

    • Pedro Aug 25, 2010 @ 3:39

      Why don’t use the “watch” command in Linux?

  • Sidh Nov 13, 2009 @ 19:28

    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'
    • Todor Jan 6, 2011 @ 12:57

      Man you rule! I wish I could be your padwan :)

    • Kaka Jun 13, 2013 @ 10:27

      Hi Sidh,

      Using ur script, getting error [expect: command not found] in last expect (expect eof)… Please help.

    • Ben Watson Jul 31, 2013 @ 8:38

      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.

  • Dewes Oct 19, 2009 @ 13:29

    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.

    • Pradeep Nov 8, 2009 @ 1:11

      Thanks Dewes ! I was looking for that !

  • Alexandru Sep 16, 2009 @ 8:23

    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

    • Alexandru Sep 16, 2009 @ 8:30

      My bad, figured it out that it returns by default.

  • Nilantha Jul 22, 2009 @ 12:46

    does anyone know how to pass a variable from bash to expect

  • Nilantha Jul 22, 2009 @ 12:45

    put “interact” at the end of expect script. Without “” ok

  • Santosh Jun 24, 2009 @ 5:39

    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

    • Shah Mar 11, 2011 @ 14:13

      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

  • pradeep Jun 22, 2009 @ 12:20

    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..

    • manish Mar 27, 2010 @ 6:37


      try using “interact” command instead of “expect eof”

  • RobsterLPL Jun 11, 2009 @ 1:01

    Something strange is happening. So I’m able to a root prompt BUT when I try to type anything in it just hangs then dumps me back to my original host I SSH’ed from.
    Can anyone help?

    #!/usr/bin/expect -f
    set timeout -1
    spawn ssh root@
    match_max 100000
    expect “*?assword:*”
    send — “password\r”
    send — “\r”
    sleep 2
    expect eof

    • manish Mar 27, 2010 @ 6:36


      try using “interact” command instead of “expect eof”
      send — “password\r”
      send — “\r”

      Hope this helps !

  • cragman513 Jun 1, 2009 @ 16:37

    How do you pass a variable from a shell script to an expect script? It seems that I can either call the expect script properly with no variable or I can pass the variable to the expect script, but the expect script will not run.

  • ahmed May 18, 2009 @ 15:43

    i want to login to a user using shell script anyone have idea for the steps to do

  • syed May 18, 2009 @ 15:38

    i want to login to a normal using shell script anyone have idea for the steps to do

    thanks in advance

  • frank May 5, 2009 @ 23:35

    what if you want to log into an device which can’t use expect, like a cisco IOS device?

  • siddu Mar 5, 2009 @ 6:43

    i’m getting partial output of the command and more over if the command is more than a word,which is give in double quotes, is taken as { cmd }. which error out saying { cmd } not found.

    Please help

  • ram Nov 17, 2008 @ 9:07

    while in an interactive program work as first it will ask for user_name if it is valid it will promt for passqd then ecucution will progress. in case we r sending wrong user_name it will prompt again for user_name. how we are going to solve this condition with help of expect. how we can determine that previous input was not currect so program is asking for the same input again…

    please help me

  • SeeFor Sep 10, 2008 @ 17:05

    Drink thanks a million for the addition of ssh -o StrictHostKeyChecking=no that saved me.

  • Drink Sep 9, 2008 @ 12:43

    so sshpass + -o StrictHostKeyChecking=no option and no need for expect and this script.

  • Drink Sep 9, 2008 @ 12:41

    for the yes/no question, this ssh option does the trick: -o StrictHostKeyChecking=no

  • Mohammed Aug 29, 2008 @ 14:12

    here is the final code,

    you can set the SSH port if it’s other than 22


    #!/usr/bin/expect -f
    # 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
    # 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 -p 22 root@$ipaddr $scriptname $arg1
    match_max 100000
    expect {
           -re ".*Are.*.*yes.*no.*" {
           send "yes\r"
           #look for the password prompt
           "password:" {
           send -- "$password\r"
           #he expect command will now return
    sleep 2


  • Madhusudan Aug 11, 2008 @ 4:04


    I need to check uptime in multiple hosts
    i have tried to write a script. Still it not working and stops at Password:
    #!/usr/bin/expect -f
    set password “123”
    SERVERS=”abc688 rgmgw1 abc173 abc30 abc101″
    for host in $SERVERS
    echo $host ; ssh -o StrictHostKeyChecking=no $host uptime
    expect “Password:*”
    send — “$password\r”
    send — “\r”
    expect eof

    Any one any adea…


  • vivek Aug 9, 2008 @ 9:50


    You need to install expect tool.

  • rahil Aug 7, 2008 @ 16:43

    I am not able to run this sript it says error is below

    [root@rahil sam]# ./rssh
    bash: ./rssh: /usr/bin/expect: bad interpreter: No such file or directory

  • Viven Rajendra Jun 18, 2008 @ 9:36

    I need a bash script which can login to an other machine via SSH and then run some commands and then return the result to my machine. There is a need for the sudo passwd on the remote machine.

  • Mark Jun 16, 2008 @ 19:47

    I’m having the same problem!

    Try this:

    send -- "ssh Manager@$ipaddr\r"
    expect "(yes/no)" { send "yes\r" } \
    	"Manager@$ipaddr's password:" { send "$pword\r" } 
    expect "Manager@ipaddr's password:" { send "$pword\r" } \
    	"#*" { send "" }

    The weird box at the end is the same as “Cntl Y”

    This WILL work after you have accepted this host. My problem is getting this to work 100% of the time, regardless.

  • Padmanabh Jun 5, 2008 @ 12:18


    I can’t run this script.
    Is anybody there to help me to show how to run it.

    Thanks in advance.


  • Z Jun 4, 2008 @ 13:44

    Why doesn’t this work for host names? Can the script be modified to support host names rather than just IP addresses?

  • Sarat Jun 3, 2008 @ 19:19


    What happens if the server asks for a ‘RSA key fingerprint’?

    In that the value to send is “yes”, right? Sending password will come only after this.

    We can write a script to first expect “(yes/no)? ” and then expect “password:”
    This will work only at the first time. Second time it expects “(yes/no)? ” and the script won’t get it.

    Can you make it a single script to include both using an IF loop or something?


Leave a Reply

Your email address will not be published.

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