【问题标题】:How to pass variables from a shell script to an expect script?如何将变量从 shell 脚本传递到期望脚本?
【发布时间】:2013-03-15 00:37:43
【问题描述】:

我的shell脚本如下:

#!/bin/bash

echo "Select the Gateway Server:"
echo "   1. Gateway 1"
echo "   2. Gateway 2"
echo "   3. Gateway 3"

read gatewayHost

case $gatewayHost in
    1) gateway="abc.com" ;;
    2) gateway="pqr.com" ;;
    3) gateway="xyz.com" ;;
    *) echo "Invalid choice" ;;
esac

/mypath/abc

在上面的脚本中,我从用户输入选择中获取网关并尝试传递给我的 abc.sh 脚本,该脚本期望如下所示:

#!/usr/bin/expect

set timeout 3
spawn ssh "james@$gateway"
expect "password:"
send "TSfdsHhtfs\r";
interact

但我无法将网关变量从 shell 脚本传递给期望脚本。谁能告诉我如何实现这一目标?请注意,由于遗留原因,我只需要使用 shell 脚本(不能使用 tcl 脚本或不能在期望脚本本身中执行所有操作)

【问题讨论】:

    标签: bash shell expect


    【解决方案1】:

    从您的 shell 脚本中:

    /mypath/abc $gateway
    

    来自您的期望脚本:

    #!/usr/bin/expect
    
    set gateway [lindex $argv 0]; # Grab the first command line parameter
    
    set timeout 3
    spawn ssh "james@$gateway"
    expect "password:"
    send "TSfdsHhtfs\r";
    interact
    

    【讨论】: