使用expect传输环境变量

时间:2011-06-24 21:41:01

标签: linux shell unix expect

我正在编写一个期望脚本,需要通过telnet会话传输环境变量(该手册页自豪地宣传为一个功能,但没有提及其他内容)。

这样的事情:

#!/usr/bin/expect -c

spawn telnet 1.2.3.4
set rpath ""

expect "#" { set rpath $PATH }

其中$ PATH在远程系统的环境中......有什么想法?

1 个答案:

答案 0 :(得分:0)

您可以通过生成bash然后将telnet发送到远程系统来轻松完成此操作。

我假设您要将路径变量从本地计算机设置为远程计算机。

#!/bin/sh
# the next line restarts using tclsh \
exec expect "$0" "$@"

set prompt "~$"
set hostname "anyhost"

spawn bash 
send "echo $PATH\r"
expect {
    $prompt {
        set pathVariable $expect_out(buffer)
    }
    timeout {
        send_user "path hasn't been set - exiting\n"
        close
        exit 1
    }

}

send "telnet $hostname\r"
expect {
       "Login:" {}
       "telnet: " {
           send_error "$argv0 couldn't login to $hostname\n"
           exit 1;
       }
       timeout {
           send_error "$argv0 couldn't login to $hostname, timeout of $timeout passed\n"
           exit 1;
       }
    }    
send "$username\r"
expect "Password:"
send "$password\r"

expect $remotePrompt
send "bash\r"
send "export PATH=$pathVariable\r"

# continue with whatever you want.