簡體   English   中英

如何調用在執行期間傳遞給另一個bash腳本的變量?

[英]How to call variables that were passed during execution time to another bash script?

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命令,因此,我編寫了另一個腳本,其期望值是解釋器。我想將用戶輸入的詳細信息傳遞給腳本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?)'

您的bash腳本將像這樣調用Expect腳本:

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

並且期望腳本將開始如下:

#!/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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM