简体   繁体   English

如何使用Expect运行SSH脚本?

[英]How to run a SSH script with expect?

I can execute command on a remote SSH host with expect. 我可以在期望的远程SSH主机上执行命令。 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
                                        }
                        }
                }
}

<是shell语法,因此您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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