KBouldin9
KBouldin9

Reputation: 404

Expect Script - enter password then run bash script

I have a bash script that calls an expect script with a password that initiates the ssh process:

#!/usr/bin/bash
/usr/bin/expect $PWD/sshScript.exp $SSHPASSWORD

The expect script calls the ssh command, waits for prompt to enter password and sends in the password.

#!/usr/bin/expect
set password [lindex $argv 0];
spawn ssh -o "StrictHostKeyChecking no" username@host
expect "Enter your AD Password:" {
    send "$password\r"
}

I can get the remote server to ssh correctly and display the [user@host ~]$ but I want to add to the expect script a way to automatically run a bash script that is stored in the same location as the other two scripts.

I've tried to

a) scp the file to the remote and call it in the server but I can't seem to get expect to send any text pass the password

b) do spawn ssh -o "StrictHostKeyChecking no" username@host < secondscript.shto send in the script to run but it won't wait for the password to be entered before trying to run the script.

Upvotes: 0

Views: 2247

Answers (1)

AnythingIsFine
AnythingIsFine

Reputation: 1807

You may combine you bash and expect script together and use it to copy the 3rd bash script to the remote server, execute it and return the output. Here's a simple NON-TESTED example:

#!/bin/bash

[... other bash code here ...]

SCRIPT='/path/to/script/to/run/remotely.sh'
LOGIN='test'
IP='your ip or hostname'
LOCATION='/destination/path/to/script/to/run/remotely.sh'

### start expect part here, you may add '-d' after 'expect' for debug

/usr/bin/expect << EOD
### set a 3 minute timeout
set timeout 180
### copy the script you wish to run on the remote machine
spawn scp -o StrictHostKeyChecking=no -p $SCRIPT $LOGIN@$IP:$LOCATION
expect {
  timeout            { send_user "\n# TIMED OUT. HOST NOT REACHABLE #\n"; exit 3 }
  "*assword: "
}
send "your_password\r"
expect {
  "*assword: " { send_user "\n# Incorrect Password. Login Failed. #\n"; exit 4 }
  "100%" { send_user "\nFile copied\n" }
}

### ssh to remote server to run script
spawn ssh $LOGIN@$IP
expect {
  timeout        { send_user "\n# TIMED OUT. SSH DAEMON or PORT 22 CLOSED #\n"; exit 6 }
  "*assword: "
}
send "your_password\r"
expect {
  timeout        { send_user "\n# TIMED OUT. PROMPT NOT RECOGNISED! #\n"; exit 7 }
### expect the prompt symbol
  -re {[#>$] }
## execute your script on the remote machine
send "$LOCATION\r"
expect {
  "enter what you expect here" { send_user "\nRESULT: Message based on what you set the expect to read $IP\n" }
  -re {[#>$] }
}

[... other expect code here ... ]

### exit remote ssh session
send "exit\r"
### end of expect part of script 
EOD
### continue bash script here

[... other bash code here ...]

Upvotes: 1

Related Questions