michelemarcon
michelemarcon

Reputation: 24737

How to run a SSH script with expect?

I can execute command on a remote SSH host with expect. Everything is fine as long as I limit myself to a one-line hardcoded command.However, I'd like to create a script of local command to be executed remotely.

This one works but only with a one line command:

#!/usr/bin/expect

set USER [lindex $argv 0]
set PASSWORD [lindex $argv 1]
set CMD [lindex $argv 2]
set timeout 10

spawn ssh -o StrictHostKeyChecking=no "$USER" "$CMD"

expect {
        timeout {
                puts "Timeout happened"
                exit 8
                }
        eof {
                puts "EOF received"
                exit 4
                }
        -nocase "password:" {
                send "$PASSWORD\n"
                expect {
                        "keys" {
                        exit 200
                                }
                        -nocase "password:" {
                                        exit 1
                                        }
                        }
                }
}

This one don't work:

#!/usr/bin/expect

set USER [lindex $argv 0]
set PASSWORD [lindex $argv 1]
set timeout 10

spawn ssh -o StrictHostKeyChecking=no "$USER" < /var/myscript.sh
#                           This don't work! ^^^^^^^^^^^^^^^^^^^

expect {
        timeout {
                puts "Timeout happened"
                exit 8
                }
        eof {
                puts "EOF received"
                exit 4
                }
        -nocase "password:" {
                send "$PASSWORD\n"
                expect {
                        "keys" {
                        exit 200
                                }
                        -nocase "password:" {
                                        exit 1
                                        }
                        }
                }
}

Upvotes: 0

Views: 878

Answers (1)

pynexj
pynexj

Reputation: 20688

< is shell syntax so you can do like this:

spawn bash -c "ssh -o StrictHostKeyChecking=no $USER < /var/myscript.sh"

Upvotes: 2

Related Questions