SSH login expect shell script to supply username and password

by on April 10, 2008 · 76 comments

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 192.168.1.11 who
# ------------------------------------------------------------------------
# Copyright (c) 2004 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ 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.
4000+ howtos and counting! If you enjoyed this article, join 45000+ others and get free email updates!

{ 75 comments… read them below or add one }

61 Sriharsha June 18, 2011

Hi,
Need help…

Sorry for long message/comment

Scenario:
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
#!/bin/bash

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…

62 Anonymous June 23, 2011

you have to install expect by sudo aptitude install expect

63 Liam August 12, 2011

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

#!/bin/bash
# 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”

64 Anonymous August 17, 2011

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

65 Suman December 2, 2011

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

66 Vikrant December 21, 2011

May be you can try using Cygwin on your windows box

67 Anonymous January 31, 2012

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

68 sachin February 8, 2012

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

69 Fayiz February 18, 2012

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?

70 Anonymous February 24, 2012

That worked beautifully. Thanks :)

71 toto March 27, 2012

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

72 zam April 14, 2012

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

Here is the ssh credentials
1)ip address
2)username
3)password
4)port

73 NITESH May 4, 2012

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

74 Justin May 8, 2012

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

75 CheBrian May 21, 2012

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"
EOF

or

use sshpass option

sshpass -p "pwd" ssh uid@server_name ls -la

Leave a Comment

You can use these HTML tags and attributes for UNIX commands or shell scripts: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 8 + 10 ?
Please leave these two fields as-is:
Are you a human being? Solve the simple math so we know that you are a human and not a script.



Tagged as: /usr/bin/expect, addreess, expect command, hostname, remote script, remote server, root admin, script collection, server password, set variables, shell script, ssh server, unix, unix box, unix server

Previous Script:

Next Script: