在expect中执行远程服务器上的本地脚本

时间:2018-05-16 06:26:03

标签: shell expect

我想在远程服务器上执行本地脚本。

#!/usr/bin/expect -f
set idNhost [lindex $argv 0]
set password [lindex $argv 1]
eval spawn ssh $idNhost \'bash -s\' < a.sh
expect -re "password"
send "$password\r"
interact

但是期望将每个论点都解释为单一的推荐。所以它在远程服务器上找到脚本。

请帮助我....

2 个答案:

答案 0 :(得分:2)

试试这样:

spawn bash -c "ssh $idNhost bash -s < a.sh"

答案 1 :(得分:0)

您可以先将脚本发送到远程服务器,然后附加shell并从那里执行。最后,从远程服务器删除脚本会更清晰。以下程序是为此目的而设计的。

proc exect_on_shell { script_name user ip pass dir } {
    spawn scp $script_name $user@$ip:$dir/$user 
    expect  "password:" 
    send "$pass\r"
    expect eof

    puts "running $script_name"
    #Attach shell
    puts "Connecting to the machine $ip for user $user"
    spawn ssh $user@$ip

    expect "yes/no" {
                send "yes\r"
                expect "*?assword" { send "$pass\r"}
            } "*?assword" { send "$pass\r"}

    #regular expression to match prompt
    expect -re {\$ $}

    send "su - root\r"
    expect {
        "Password: " {send "$pass\r"}
    }

    send "cd $dir/$user\r"
    send "chmod +x $script_name\r"
    send "$script_name\r"

    send "rm -rf $script_name\r"
    #logout from root   
    send "exit\r"
    #logout from user
    send "exit\r"
    expect eof
}

您可以在以下代码段中调用它。

exect_on_shell "your_script.sh" "user_name" "192.168.2.3" "pass" "home/user_name"