Linux 如何通过shell脚本中的命令行传递Expect中的参数
我正在通过shell脚本中的命令行传递Expect中的参数 我试过这个Linux 如何通过shell脚本中的命令行传递Expect中的参数,linux,bash,shell,expect,Linux,Bash,Shell,Expect,我正在通过shell脚本中的命令行传递Expect中的参数 我试过这个 #!/usr/bin/expect -f set arg1 [lindex $argv 0] spawn lockdis -p expect "password:" {send "$arg1\r"} expect "password:" {send "$arg1\r"} expect "$ " 但它不起作
#!/usr/bin/expect -f
set arg1 [lindex $argv 0]
spawn lockdis -p
expect "password:" {send "$arg1\r"}
expect "password:" {send "$arg1\r"}
expect "$ "
但它不起作用。如何修复它?如果您想读取参数,只需
set username [lindex $argv 0];
set password [lindex $argv 1];
然后打印出来
send_user "$username $password"
那个脚本将被打印出来
$ ./test.exp user1 pass1
user1 pass1
您可以使用调试模式
$ ./test.exp -d user1 pass1
更好的方法可能是:
lassign $argv arg1 arg2 arg3
但是,您的方法也应该有效。检查是否检索到
arg1
。例如,对于send\u user“arg1:$arg1\n”
注意,有时argv 0是您正在调用的脚本的名称。因此,如果这样运行,argv 0将不起作用
为了我,我跑步
expect script.exp password
这使得argv 1=password和argv 0=script.exp.带空格的参数是可以的,假设您想要的参数是脚本名称后的第一个参数(
$0
是脚本名称,$1
是第一个参数,等等)
确保使用“$ARG”
,not$ARG
,因为它将not包括空格,但将它们分解为单独的参数。在Bash脚本中执行以下操作:
#!/bin/bash
ARG="$1"
echo WORD FROM BASH IS: "$ARG" #test for debugging
expect -d exp.expect "$ARG"
exit 0
另外,如前所述,请使用调试模式(
-d
标志)。它将输出Expect看到的argv
变量,并向您显示发生了什么。我喜欢随附的答案
#!/usr/bin/expect
set username [lindex $argv 0]
set password [lindex $argv 1]
log_file -a "/tmp/expect.log"
set timeout 600
spawn /anyscript.sh
expect "username: " { send "$username\r" }
expect "password: " { send "$password\r" }
interact
它创建一个解析参数过程
#process to parse command line arguments into OPTS array
proc parseargs {argc argv} {
global OPTS
foreach {key val} $argv {
switch -exact -- $key {
"-username" { set OPTS(username) $val }
"-password" { set OPTS(password) $val }
}
}
}
parseargs $argc $argv
#print out parsed username and password arguments
puts -nonewline "username: $OPTS(username) password: $OPTS(password)"
以上只是一个片段。完整阅读本指南并添加足够的用户参数检查非常重要。在这一过程中,请小心使用它,因为您的进程将显示参数、用户名和密码,在执行类似“ps aux”的操作时,我们可以循环参数列表并将其放入数组吗?预期脚本丢失,而不是“丢失”对于通过bash调用的任何expect脚本,它的工作方式都是相同的。虽然在这个例子中,它需要被称为“exp.expect”。没有必要进行否决表决,但我的回答解释了如何处理有问题的内容。好的,我
expect
编辑了脚本的内容,该脚本引用了外部参数,正如其他示例中所示。上面的代码适用于expect
正在使用的TCL,对Bash没有意义。