Ever come across a situation where you want to access an interactive application like ssh from a bash script but do not want to enter password manually and let the script do it for you?
Yesterday I had the same situation and I found solution for this, with a tool called “expect”.
What is except?
“Expect is a tool for automating interactive applications like ssh, telnet, ftp etc.”
Let’s take an example,
Login to ssh on a system with,
- IP: 192.168.56.3
- username: batman
- password: batman
Now to do this you will have to do following steps manually.
- Open terminal
- type command, ssh batman@192.168.56.3
- Press Enter
- A password prompt will appear, like this

- Here’s the problem when you want to automate this activity, you will have to manually enter the password after “password:” prompt, then only you can access the system with ssh.

To automate this activity from script, you will need expect.
First install expect in your linux system with below command.
apt-get install expect
Now lets create a script to automate above activity.
- Open your terminal
- Create a script file, Let’s say ConnectToBatman
- Make it executable
chmod +x ./ConnectToBatman
- Then run the script,
./ConnectToBatman
- Here’s what script will look like,
#!/usr/bin/expect -f ############################################################# # Notice here '/usr/bin/expect -f' is used in very first line # to make define expect path ############################################################# #spawn:- Starts a script or a program, here it starts ssh call spawn ssh batman@192.168.56.3 #expect :- expect should be kept after spawn, # it will wait for ssh to respond, in case of ssh it will #respond # by asking for password with word "password:" in the end expect "password:" #send:- To send a reply to your program. # send is used after expect, to send response to program # in this case we need to provide password for username: batman # the password is 'batman' # Notice a \n after password it works as # Enter after typing password. send "batman\n" #interact:- Allowing you in interact with your program. # interact should be added following above commands otherwise # you won't be able to enter into the program after login interact
- That’s it …..
- With above 4 commands you can access ssh with script,

References:
https://likegeeks.com/expect-command/