如何在运行时期间在expect shell脚本中传递参数

时间:2014-10-07 07:56:11

标签: shell expect

我正在尝试动态传递密码,同时运行expect脚本。

脚本看起来有点像这样:

#!/usr/bin/Expect

set server [lindex $argv 0] 

send "enter you password" 

read Password; 

send $password\n; 

spawn ssh c1210427@$server ...

在运行脚本中从终端获取密码时卡住了。

2 个答案:

答案 0 :(得分:1)

[read]命令会一直读到文件末尾,所以它等着你关闭终端。改为使用[gets]命令:

set password [gets stdin]

此外,您使用[read]错误。第一个参数是要读取的通道ID。有关详细信息,请参阅文档:

http://www.tcl.tk/man/tcl8.6/TclCmd/read.htm

http://www.tcl.tk/man/tcl8.6/TclCmd/gets.htm

答案 1 :(得分:1)

在您的代码中,您使用了以下代码,例如puts语句

send "enter your password"

这不是一个正确的方法。通常,send命令将尝试向控制台发送命令,如果通过脚本生成任何进程,则此命令将被发送到该进程。

无论如何,您将在控制台中打印语句。但是,要注意它。相反,最好使用send_user命令。

你可以试试这个

#!/usr/bin/expect

set server [lindex $argv 0]

stty -echo; #Disable echo. To avoid the password to get printed in the terminal

send_user "enter you password : "

# Using regex to grab all the input till user press 'Enter'
# Each submatch will be saved in the the expect_out buffer with the index of 'n,string' 
# for the 'n'th submatch string

# expect_out(0,string) will have the whole expect match string including the newline

# The first submatch is nothing but the whole text without newline
# which is saved in the variable 'expect_out(1,string)
expect_user -re "(.*)\n" ;     

stty echo; #Enable echo

set pwd  $expect_out(1,string)

send $pwd\n;

expect "some-other-statment"

#Your further code here

如果您不打扰在控制台中打印的密码,可以删除stty -echostty echo

参考:http://www.tcl.tk/man/expect5.31/expect.1.html

相关问题