简体   繁体   中英

Expect script not executing after ssh login

I'm trying to write an expect script to:

  1. Connect to a remote server providing the user and password
  2. Loop through a local file reading each line
  3. Execute a specific command on the remote server for each of those lines

I could successfully achieve the step #1 and was testing the #3 with a simple scenario, but couldn't make it work yet. Unfortunately in the line 8 of the script, after sending the password, I just get logged into the server as I would have been logged manually (I can interact with the console) and the rest is not executed.

How can I circumvent this problem?

This is the script:

#!/usr/bin/expect
set timeout 20
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh -t -t "$user\@$ip"
expect "Password:"
send "$password\r";
expect "NYXOOBPN402(config)$"
send "delete decoders:ASX-Trade24-FIX.mdp\r"
expect "Are you sure you want to delete 'decoders:ASX-Trade24-FIX.mdp' (y/n)?"
send "y\r";

And this is how I'm executing it:

./test_expect.sh 172.18.250.20 admin admin

The problem is that my expect was incorrect in the line 17. Instead of "NYXOOBPN402(config)$", I should just put "*(config)*", since there's a lot of text before this part that was not being matched.

This is my final script for someone that runs into this same issue:

#!/usr/bin/expect
set timeout 9
# Check if the parameters are correct
if {[llength $argv] == 0} {
      send_user "Usage: ./test_expect.sh ip username password\n"
        exit 1
    }

# Read the file with all the decoders names to be deleted
set f [open "decoders.txt"]
set decoders [split [read $f] "\n"]
close $f

# debug mode - very useful:
#exp_internal 1

# Connect to the server
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh -t "$user\@$ip"
expect "Password: "
send "$password\r";
sleep 3
# send ctrl+c since this terminal shows a lot of decoders
#send \x03

expect {
    default { send_user "\nCould not find the expected value.\n"; exit 1 }
    "*(config)*" {
        # Loop through all the decoders
        foreach decoder $decoders {
            #send_user "Removing $decoder\n"
            send "delete decoders:$decoder\r"
            expect {
                "Are you sure you want to delete*" { send "y\r" }
                "*decoder will still be active*" { send_user "\nRemoved $decoder successfully\n" }
                "*no such file or directory" { send_user "\nDecoder $decoder already deleted.\n" }
                default { send_user "\nNot expected value with $decoder, please debug.\n"; exit 1 }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM