Bash/Expect Script for SSH - bash

I am new to Expect and scripting in general. I am trying to make a few scripts to make my life a bit easier when pulling network device configurations. I managed to create a basic Expect script to SSH to a device and save the configuration.
I want to expand upon this and allow the script to connect to a number of IP addresses instead of just one like I have right now. I have a file named list.txt with a few different IP addresses with each IP address on a separate line.
What would I need to do to have the Expect script connect to each of these IP addresses and perform the rest of the tasks in the script as well?
Here is the Expect script I have so far:
#!/usr/bin/expect -f
# Tells interpreter where the expect program is located. This may need adjusting according to
# your specific environment. Type ' which expect ' (without quotes) at a command prompt
# to find where it is located on your system and adjust the following line accordingly.
#
#
# Use the built in telnet program to connect to an IP and port number
spawn ssh 192.168.1.4 -l admin
#
# The first thing we should see is a User Name prompt
#expect "login as:"
#
# Send a valid username to the device
#send "admin"
#
# The next thing we should see is a Password prompt
expect "Password:"
#
# Send a valid password to the device
send "password\n"
#
# If the device automatically assigns us to a privileged level after successful logon,
# then we should be at an enable prompt
expect "Last login:"
#
# Tell the device to turn off paging
#
# After each command issued at the enable prompt, we expect the enable prompt again to tell us the
# command has executed and is ready for another command
expect "admin#"
#
# Turn off the paging
send "set cli pager off\n"
#
# Show us the running configuration on the screen
send "show config running\n"
#
# Set the date.
set date [timestamp -format %C%y%m%d]
#
# Test output sent to file with a timestamp on end
#-noappend will create a new file if one already exists
log_file -noappend /home/test.cfg$date
#
expect "admin#"
#
# Exit out of the network device
send "exit\n"
#
# The interact command is part of the expect script, which tells the script to hand off control to the user.
# This will allow you to continue to stay in the device for issuing future commands, instead of just closing
# the session after finishing running all the commands.`enter code here`
interact
Do I need to integrate this with a Bash script? If so, is it possible to read one line of the list.txt file, use that as the IP address/host variable and then read the next and repeat?

I would do this (untested):
#!/usr/bin/expect -f
set logfile "/home/text.cfg[clock format [clock seconds] -format %Y%m%d]"
close [open $logfile w] ;# truncate the logfile if it exists
set ip_file "list.txt"
set fid [open $ip_file r]
while {[gets $fid ip] != -1} {
spawn ssh $ip -l admin
expect "Password:"
send "password\r"
expect "admin#"
send "set cli pager off\r"
log_file $logfile
send "show config running\r"
expect "admin#"
log_file
send "exit\r"
expect eof
}
close $fid
Notes:
I removed all your comments for brevity
use \r to simulate hitting enter when you send commands.
I assumed you only want to log the "show config running" output
use expect eof after you send "exit"

This is a Perl version for this issue:
Install instruction:
cpan Expect
This script works perfectly for my needs.
Parameter 1: Connection string (example: admin#10.34.123.10)
Parameter 2: Clear text password
Parameter 3: Command to execute
#!/usr/bin/perl
use strict;
use Expect;
my $timeout = 1;
my $command = "ssh " . $ARGV[0] . " " . $ARGV[2];
#print " => $command\n";
my $exp = Expect->spawn($command) or die "Cannot spawn $command: $!\n";
$exp->raw_pty(1);
LOGIN:
$exp->expect($timeout,
[ 'ogin: $' => sub {
$exp->send("luser\n");
exp_continue;
}
],
[ 'yes\/no\)\?\s*$' => sub {
$exp->send("yes\n");
goto LOGIN;
}
],
[ 'assword:\s*$' => sub {
$exp->send($ARGV[1]."\n");
#print "password send: ", $ARGV[1];
exp_continue;
}
],
'-re', qr'[#>:] $'
);
$exp->soft_close();

A possibility is to pass the IP address as a parameter in your Expect script:
set host_ip [lindex $argv 0]
and then make a shell script, calling your Expect script inside a while loop:
ips_file="list.txt"
while read line
do
your_expect_script line
done < $ips_file

Or use set ip [gets stdin] to the IP address from the user input.
For example,
puts "Enter your IP address\n"
set ip [get stdin]
Use this in spawn. We can do the same for multiple IP addresses using a loop -
spawn ssh $ip -l admin

Here's a good way to integrate expect with bash:
ssh_util.expect-
#!/usr/bin/expect
set timeout -1
set ip [lindex $argv 0]
set user [lindex $argv 1]
set pwd [lindex $argv 2]
set commands [lrange $argv 3 [llength $argv]]
spawn ssh -o LogLevel=QUIET -t $user#$ip $commands
expect {
yes/no {send "yes\r" ; exp_continue}
*?assword {send "$pwd\r" ; exp_continue}
}
You can run this in the terminal with ./ssh_util.expect <commands...>. In your shell script you can use it to run commands on your host machine like this:
example.sh -
#! /bin/bash
# ssh_exp <commands...>
ssh_exp () {
./ssh_util.expect 192.168.1.4 username password $*
}
# run commands on host machine here
ssh_exp ls
ssh_exp ls -la
ssh_exp echo "Echo from host machine"
# you can even run sudo commands (if sudo password is same as user password)
ssh_exp sudo apt install
Make sure to run
chmod +x ssh_util.expect
chmod +x example.sh
in the terminal to make both files executable. Hope this helps!

Related

"Expect" command line script to connect to VPN and enter password

I am trying to write an "Expect" script to connect to a VPN...
Trying to write and expect (https://likegeeks.com/expect-command/) script to connect to a vpn, is this the right idea:
The commands to connect are:
sudo vpnName [ENTER] *Password* [ENTER] Random number 1-100 [ENTER] [ENTER]
So the expect script would be something like:
#!/usr/bin/expect -f
set randNum [(( ( RANDOM % 100 ) + 1 ))]
send -- "sudo vpnName\r"
send -- "*password*\r"
send -- "randNum\r \r"
You are trying to combine a bash expression with tcl (language expect is using)
Use instead:
set randNum [expr {int(rand()*100) + 1}]
In expect, you need to spawn a process before you can interact with it:
#!/usr/bin/expect -f
set randNum [expr {int(rand()*100) + 1}] # as per #Sorin's answer
spawn sudo vpnName
expect "assword" # wait for the password prompt
send -- "*password*\r"
expect "whatever matches the random number prompt"
send -- "$randNum\r\r"
# this keeps the vpn process running, but returns interactive control to you:
interact
A tip: while debugging expect code, launch it with expect -d -f file.exp -- this is very valuable to let to see if your expect patterns are matching as you think they should.

Bash Scripting, send "logout" command being skipped during ssh session

Essentially I connect to remote host, authenticate, run command, logout. However logout command is being skipped.
/usr/bin/expect << EOD
spawn ssh $_host
expect "Password: ";
send "$_pass\r";
expect "$_host>";
send "sh arp | inc $_host2\r";
expect "$_host>";
send "logout\r";
EOD
echo "blah blah"
What i get is my expected output from arp command however, blah blah will be entered into the terminal of the remote host. It seems the logout command is being skipped, somewhat new to bash scripting but it seems that expect doesn't instantly see "$_host>" when executing and skips it? Appreciate any feedback.
Don't use expect here at all. Even if you must get the password from a variable, using sshpass for the purpose will avoid mixing two separate languages (bash and TCL).
SSHPASS="$_pass" sshpass -e "$_host" "sh arp | inc $_host2"
I believe the \r ( carrige return ) should be \n ( enter / new line ) ?
send "logout\r"; -> send "logout\n";
If that will help - I would replace it in the entire script ..
Suggesting:
/usr/bin/expect << EOD
match_max 1000000
spawn ssh $_host
expect "Password: ";
send "$_pass\n";
expect "$_host>";
send "sh arp | inc $_host2\n";
expect "$_host>";
send "logout\n";
EOD
echo "blah blah"

SSH connection requests password before password can be sent

I have an odd problem I am trying to ssh connect to a remote device inside of a script so I can send commands to it but weirdly it's asking for the password to the ssh connection before I can even call an expect command. My snippet is this:
#!/usr/bin/expect
set PASS="password"
echo {$PASS}
ssh admin#10.3.0.1 -p 4118 #Firewall Device IP
expect {
"Password: "
{send '$PASS\r'}
}
and the output I get is this:
password
Password:
I have no idea why it behaving this way.
Edit:
I've applied the changes suggested by #glenn jackman, the new code being:
#!/usr/bin/expect
set PASS "peak1234"
puts "$PASS"
ssh admin#10.3.0.1 -p 4118 #Firewall Device IP
expect "Password :"
send "$PASS\r"
with these changes I get the error:
set: Variable name must begin with a letter.
You're confusing expect with sh
#!/usr/bin/expect
set PASS "password" ; ## no "="
puts $PASS ; ## no "echo", braces wrong
ssh admin#10.3.0.1 -p 4118
expect "Password: "
send "$PASS\r" ; ## single quotes have no meaning in expect/Tcl

How to pass the argument in expect shell script during runtime

I am trying to pass the password dynamically, while running the expect script.
Script looks somewhat like this :
#!/usr/bin/Expect
set server [lindex $argv 0]
send "enter you password"
read Password;
send $password\n;
spawn ssh c1210427#$server ...
Got stuck while getting the password from terminal during the running script.
The [read] command reads until end of file so it's waiting for you to close the terminal. Use the [gets] command instead:
set password [gets stdin]
Also, you're using [read] wrong. The first argument is the channel id to read from. See the documentation for more info:
http://www.tcl.tk/man/tcl8.6/TclCmd/read.htm
http://www.tcl.tk/man/tcl8.6/TclCmd/gets.htm
In your code, you have used the following code like a puts statement
send "enter your password"
which is not a proper way. Usually, send command will try to send commands to the console and if any process spawned via script, then this command will be sent to that process.
Anyway, you will get the statements get printed in the console. But, be aware of it. Instead, better use send_user command.
You can try out this
#!/usr/bin/expect
set server [lindex $argv 0]
stty -echo; #Disable echo. To avoid the password to get printed in the terminal
send_user "enter you password : "
# Using regex to grab all the input till user press 'Enter'
# Each submatch will be saved in the the expect_out buffer with the index of 'n,string'
# for the 'n'th submatch string
# expect_out(0,string) will have the whole expect match string including the newline
# The first submatch is nothing but the whole text without newline
# which is saved in the variable 'expect_out(1,string)
expect_user -re "(.*)\n" ;
stty echo; #Enable echo
set pwd $expect_out(1,string)
send $pwd\n;
expect "some-other-statment"
#Your further code here
You can remove the stty -echo and stty echo if you don't bother about the password getting printed in console
Reference : http://www.tcl.tk/man/expect5.31/expect.1.html

Unable to call a command on windows server by connecting through linux

I am using a following script which connects to windows server from Linux, but after connecting i have to call the a command by doing to a location under D: drive of windows followed by some folders (Where the Folder names consists of spaces eg: d:\Rakesh Tatineni\not able to execute\Manager.exe 1 1)
Above is the some how i want to execute/call a command with 2 argument 1 1.
Script using to connect to windows
#!/usr/bin/expect -f
# Expect script to supply username/admin password for remote ssh server
# and execute command.
# This script needs three argument to(s) connect to remote server:
# password = Password of remote Windows server, for Windows user.
# For example:
# ./call_engine.sh password
# set Variables
set password [lrange $argv 0 0]
set timeout -1
# now connect to remote windows box (ipaddr/hostname) with given script to execute
spawn ssh userid#<WindowsserverName>
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
Appreciate your help , in between what kind of code we have to include to call a command as i mentioned above "d:\Rakesh Tatineni\not able to execute\Manager.exe 1 1"
Thanks,
Rakesh T
I see that you already give the script an argument of password. So you can change your script slighlty to add two more arguments like this:
set password [lrange $argv 0 0]
set arg1 [lrange $argv 1 1]
set arg2 [lrange $argv 2 2]

Resources