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.

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

    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.



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

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

  4. simple Ex : for expect :


    use sshpass option

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

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

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

    Here is the ssh credentials
    1)ip address

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

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

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

  11. Hi,
    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…

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

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

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

  13. Hi,
    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

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

  14. Hi,

    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.

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

    Have a question? Post it on our forum!