How to pass argument in expect through command lin

2019-03-09 19:58发布

I am passing argument in expect through command line in shell script

I tried this

#!/usr/bin/expect -f

set arg1 [lindex $argv 0]

spawn lockdis -p
expect "password:" {send "$arg1\r"}
expect "password:" {send "$arg1\r"}
expect "$ "

but it's not working. Please help me to figure it out.

Thanks

6条回答
Emotional °昔
2楼-- · 2019-03-09 20:06

If you want to read from arguments, you can achieve this simply by

set username [lindex $argv 0];
set password [lindex $argv 1];

And print it

send_user "$username $password"

That script will print

$ ./test.exp user1 pass1
user1 pass1

You can use Debug mode

$ ./test.exp -d user1 pass1
查看更多
爷的心禁止访问
3楼-- · 2019-03-09 20:08

A better way might be this:

lassign $argv arg1 arg2 arg3

However, your method should work as well. Check that arg1 is retrieved. For example, with send_user "arg1: $arg1\n".

查看更多
4楼-- · 2019-03-09 20:17
#!/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
查看更多
霸刀☆藐视天下
5楼-- · 2019-03-09 20:20

I like the answer provided with this guide. It creates a parse argument process.

#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 arguements
puts -nonewline "username: $OPTS(username) password: $OPTS(password)"

The above is just a snippet. It's important to read through the guide in full and add sufficient user argument checks.

查看更多
别忘想泡老子
6楼-- · 2019-03-09 20:20

note, sometimes argv 0 is the name of the script you are calling. so if you run it that way, argv 0 doesn't work,
for me I run "> expect script.exp password"

that makes argv 1 = password argv 0 = script.exp

查看更多
一夜七次
7楼-- · 2019-03-09 20:23

Args with spaces are fine, assuming the arg you want is the first after the script name ($0 is script name, $1 is first arg, etc.)

Make sure you use "$ARG" NOT $ARG as it wil NOT include the whitespace, but break them up into individual args. Do this in your bash script:

#!/bin/bash

ARG="$1"
echo WORD FROM BASH IS: "$ARG" #test for debugging

expect -d exp.expect "$ARG"

exit 0

Also, as the first answer states, use debug mode, (the -d flag) It will output your argv variables as expect sees them, should show you what is going on.

查看更多
登录 后发表回答