【问题标题】:How to call variables that were passed during execution time to another bash script?如何将执行期间传递的变量调用到另一个 bash 脚本?
【发布时间】:2018-11-29 23:10:19
【问题描述】:

Bash 脚本 1:

询问用户名和主机名并存储到另一个变量。

#!/bin/bash

echo "Please enter hostname:"
read hostname

echo -n "Enter the username"
read username

echo -n "enter the password:"
read -s password

: ' (我想在 ssh 之前使用 spawn 命令,因此,我编写了另一个脚本,用 expect 作为解释器。 我想将用户输入的详细信息传递给脚本 2) '
Bash 脚本 2:

#!/bin/expect

spawn ssh -o StrictHostKeyChecking=no $username\@$hostname

expect {
         timeout
                { send_user "\nTimeout Exceeded - Check Host\n"; exit 1 }
         eof
                { send_user "\nSSH Connection To $hostname Failed\n"; exit 1 }
        incorrect
                {send_user "invalid password or account\n"; exit 1}

        "*assword:"
                { send "$password\n" }
expect "$"
interact
        }

: ' (但是,如何将脚本1在运行时询问的信息调用到脚本2?)'

【问题讨论】:

  • 看看sexpect,你可以用它编写Expect脚本,shell代码

标签: linux bash expect


【解决方案1】:

你的 bash 脚本会像这样调用期望脚本:

expect script.exp "$username" "$password" "$hostname"

expect 脚本的开头如下:

#!/bin/expect

lassign $argv username password hostname

# or if your version of expect is old and does not have "lassign"
# foreach {username password hostname} $argv break

# or, if you prefer
# set username [lindex $argv 0]
# set password [lindex $argv 1]
# set hostname [lindex $argv 2]

spawn ssh -o StrictHostKeyChecking=no $username@$hostname
# etc etc

@ 字符没有特殊含义,因此不需要转义。


上述方法存在安全风险:在期望代码运行时,ps 输出将显示密码。

您可以通过环境共享密码:

狂欢

export username password hostname
expect script.exp

期待

spawn ssh -o StrictHostKeyChecking=no $env(username)@$env(hostname)
# etc etc

【讨论】:

    猜你喜欢
    • 2012-11-15
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    相关资源
    最近更新 更多