Today I will be showing you how to use a basic expect script inside of your bash scripts for automation. Expect works just like the name sounds, expect to see a prompt or other piece of text and then send the response. With this you can do things such as automatically entering password for SSH (not recommended for daily use), automatically answer prompts, etc.
Please note that for this to work you will need to have the expect package installed, which is usually not installed by default. You can usually install it by running one of the below commands depending on your distro.
sudo yum install expect -y sudo apt-get install expect -y
In the quick and easy example below I will show you how to automatically SSH to a server and then automatically run multiple commands. You can also add the command interact afterwards to take over and input information manually, I will include this but it will be commented out.
#!/bin/bash # Login credentials password="your-password-here"; user="your-user-here"; print "Automatic SSH Connector"; /usr/bin/expect<<EOD set timeout 30; # Time to wait before timing out if expected string doesn't appear spawn ssh -o StrictHostKeyChecking=no "[email protected]$1"; # Start SSH session expect "*?assword:"; # Expect password send "$password\r"; # Send password credential expect '$'; # Expect terminal prompt send "df -h\r"; # Send "df -h" command expect '$'; # Expect terminal prompt send "free -m\r"; # Send "free -m" command interact; # Let user take over and interact with terminal session expect EOD EOD exit 0;
The way this script will work is it will start an SSH session to [email protected]$1 (./scriptname.sh yourdomain), then supply the password as-well as run a few commands and then turn control over to the user.
If you have any questions then feel free to ask, expect can be a great tool that really makes life easier.