Expect in Bash script: expect_out not printing out buffer - bash

I am trying to capture the output of the "dir" command by logging into a switch, but I am unable to do so. I am using Expect within Bash. I am making use of expect_out to capture output of that command in a buffer and print it out. Actually I want to capture the output and perform some operations on it.
Script:
#!/bin/bash
expect -c "
spawn telnet 1.1.1.1 2000
sleep 1
send \"\r\"
send \"\r\"
expect {
Prompt> { send \"dir\r\" }
}
set output $expect_out(buffer)
"
echo "$output"
Output:
spawn telnet 1.1.1.1 2000
Trying 1.1.1.1...
Connected to 1.1.1.1 (1.1.1.1).
Escape character is '^]'.
Prompt>
Prompt>
After these prompts are displayed, the scripts just exits. How can I fix this problem?
After I split it, I can use parameter substitution as well as single quotes. Now I am facing different error.
Script:
expect -c "
spawn telnet $IP $PORT1
sleep 1
send \"\r\"
send \"\r\"
"
expect -c '
expect {
Prompt> { send \"dir\r\" }
set output $expect_out(buffer)
puts "$output"
}
'
Output:
spawn telnet 172.23.149.139 2033
can't read "expect_out(buffer)": no such variable
while executing
"expect {
Prompt> { send \"dir\r\" }
set output $expect_out(buffer)
puts "$output"
}
"
I changed it to according to the suggestions. But I am still facing errors.
Script:
output=$(expect -c '
spawn telnet '"$IP $PORT1"'
sleep 1
send '"\r"'
send '"\r"'
expect Prompt> { send '"dir\r"' }
expect '"\n"'
expect -indices Prompt>
puts '"[string range $expect_out(buffer) 0 [expr $expect_out(0,end) - 1]]"'
')
echo "======="
echo "$output"
echo "======="
Output:
syntax error in expression "(0,end) - 1"
while executing
"expr (0,end) - 1"
invoked from within
"string range (buffer) 0 [expr (0,end) - 1]"
invoked from within
"puts [string range (buffer) 0 [expr (0,end) - 1]]"
=======
spawn telnet 1.1.1.1 2000
Trying 1.1.1.1...
Connected to 1.1.1.1 (1.1.1.1).
Escape character is '^]'.
Prompt>
Prompt>
=======
Hence to circumvent the error, I changed, the line
puts '"[string range $expect_out(buffer) 0 [expr $expect_out(0,end) - 1]]"'
to
puts '"$expect_out(buffer)"'
But then I am getting no error, but the output of dir is also not getting printed. Something like:
Prompt>
Prompt> (buffer)

The second of your “split” Expect programs does not have access to the spawned telnet process. When you split them like that, you made them independent (one can not access the variables or state of the other; actually by the time the second one has started the first one, and its telnet process, no longer exist).
The shell will automatically concatenate any strings (that are not separated by unquoted/unescaped whitespace) without regard to the kind of quotes (if any) they use. This means you can start put the first part of your Expect program in single quotes, switch to double quotes for the parameter substitution, and then go back to single quotes for the rest of the program (to avoid having to escape any of "$\` that occur in your Expect code).
expect -c '
spawn telnet '"$HOST $PORT"'
sleep 1
⋮ (rest of Expect program)
'
It uses single quotes to protect most of the program, but switches back to double quotes to let the shell substitute the its HOST and IP parameters into the text of the Expect program.
Next, the shell that started expect can not access variable set inside the Expect program. The normal way to collect output from a child process is to have it write to stdout or stderr and have the shell collect the output via a command substitution ($()).
In Tcl (and Expect), you can use puts to send a string to stdout. But, by default, Expect will also send to stdout the normal “interaction” output (what it receives from any spawned commands and what it sent to them; i.e. what you would see if you were running the spawned command manually). You can disable this default logging with log_user 0.
You might write your program like this:
#!/bin/sh
output=$(expect -c '
# suppress the display of the process interaction
log_user 0
spawn telnet '"$HOST $PORT"'
sleep 1
send "\r"
send "\r"
# after a prompt, send the interesting command
expect Prompt> { send "dir\r" }
# eat the \n the remote end sent after we sent our \r
expect "\n"
# wait for the next prompt, saving its position in expect_out(buffer)
expect -indices Prompt>
# output what came after the command and before the next prompt
# (i.e. the output of the "dir" command)
puts [string range $expect_out(buffer) \
0 [expr $expect_out(0,start) - 1]]
')
echo "======="
echo "$output"
echo "======="

Because your Expect script is enclosed in double quotes, the shell is expanding $expect_out to an empty string. Put the body of the expect script in single quotes.
When you set a variable in Expect, the shell will have no idea. When the Expect script completes, its variables vanish too. You have to puts the expect_out buffer.

Related

Expect script can't read a variable

I have been trying to pass a variable to expect script, this variable contains the password for an ssh command, however when I try to execute the script, I receive a message stating that the variable couldn't be read - no such variable.
The variable is declared in the shell script, however expect just can't read it.
Here is how the variable is declared:
D=`s="$LIST1" printenv s |grep $ip | awk '{print $3}'`
If I export variable D, then it works, but I can't have this variable exported to all child process, does anyone know how can I add this variable to expect without having to export it?
/usr/bin/expect <<'END_EXPECT'
set timeout -1
log_file expect-log.txt
spawn -noecho sh ./script.sh
expect "yes" { send "yes\r"}
expect {
-nocase "*assword*" {
send "$D\r"
exp_continue
}
send \r
eof
admin#server1's password: can't read "D": no such variable
while executing
"send "$D\r""
invoked from within
"expect {
-nocase "*assword*" {
send "$D\r"
exp_continue
}
send \r
eof
}"
By far the easiest method of getting the variable into expect is by exporting it. You can unexport it after launching expect, and expect can remove the variable from the environment before launching any subprocesses.
You are strongly advised to not embed the expect script within a shell script, but rather to make it a separate file (that uses Tcl highlighting rules, if you're using an editor that supports it). It's just so much easier that way.
# This is bash; other shells have their own quirks
export D=`s="$LIST1" printenv s |grep $ip | awk '{print $3}'`
expect script.expect
unexport D
# Move the variable from the environment to a script variable; DO THIS BEFORE exec OR spawn
set D $env(D)
unset env(D)
set timeout -1
log_file expect-log.txt
spawn -noecho sh ./script.sh
expect "yes" { send "yes\r"}
expect {
-nocase "*assword*" {
send "$D\r"
exp_continue
}
send \r
eof
That code looks incomplete BTW. The braces aren't balanced, the indentation looks strange, and it generally looks like something is missing. You'll have to fix that before everything works.

expect in bash: quoting with special characters and output as VAR

I have this bash scipt
#!/bin/bash
Login="bla 0, xy;Z" ##the spaces and the ',' and ';' are important!
expect -c "
spawn telnet *HOST*
expect "Done."
send '$Login'
expect "Done."
send "command 0". ## the ' 0' is important! Same prob as with the password
??? ## what do I have to do to get the output in a VAR?
expect "Done."
"
The two questions are:
the $Login is not interpreted as text from bash, so it thinks with 0 a new command starts... and ',' as well as ';' seems to be a problem too. escaping with '' did not work!?
How do I get the output as a $VAR to use it later?
Is this possible at all in bash? or do I have to use tcl (which I have never ever used or read anything about before)?
Thanks for advices!
andy
In addition to the useful comments above, single quotes have no special meaning in Tcl/expect, they are just ordinary characters that are being sent with the password.
As Charles writes, passing data via the environment is helpful.
Also, Tcl comments are a bit annoying: the # is only recognized as a comment if it occurs where a command starts, so you'll see me use ;# below.
I find using a quoted heredoc removes quoting difficulties.
When you say "result in a VAR", I assume you want a shell variable?
untested
export Login="bla 0, xy;Z"
export HOST=something
VAR=$(expect << 'END_EXPECT'
log_user 0 ;# turn off normal stdout of the interaction
# so we can capture only the output you want
spawn telnet $env(HOST)
expect "Done."
send "$env(Login)\r" ;# don't forget to "hit enter"
expect "Done."
send "command 0\r"
# what do I have to do to get the output in a VAR?
# use a regex capturing the command's output. Note that the command
# itself appears in the output
expect -re "command 0\r\n(.+)Done."
# the shell will capture this output
puts $expect_out(1,string)
send "exit\r" ;# or whatever you need to do to quit
expect eof
END_EXPECT
)

When telneting with expect, how to grep an output word as the next command input variable via expect_out ?

I am trying to connect a device from telnet with expect command in bash script. What I would like to do is something as follows:
#!/usr/bin/expect -f
telnet_setup()
{ sleep 10
expect <<EOF
spawn telnet $1
expect "Password:"
send "mypass\n"
expect "#"
send "my command to be run\n"
expect "Last number to be captured:"
#Here the whole sentence to be captured something like:
#Last number to be captured: 213124
set mynumber expect_out(buffer,0) | awk '{print $6}'
send "my next command with number $mynumber\"
expect "Correct number $mynumber is achieved!"
send "exit\n"
EOF
}
To use the function, I use as follows:
telnet_setup 1.1.1.1 > file.txt
My goal is to use this function with $mynumber to be used in the next commands. Can you please suggest how to provide this?
You're having some trouble separating expect code from shell code. To capture the number, expect a regular expression with capturing parentheses
send "my command to be run\r"
expect -re {Last number to be captured:\s+(\d+)}
set mynumber $expect_out(1,string)

invalid command name "cat". expect send [ ] at shell script

I want to use expect at shell script
My code is here
#!/bin/sh
expect << EOF
send [cat hello]
EOF
This command is failed
invalid command name "cat"
while executing "cat hello"
invoked from within "send [cat hello]"
but, send [cat hello] command successed in expect prompt
expect1.1> send [cat hello]
world
expect1.2>
Why do I output the different execution results ?
Inside expect shell:
While you are in expect shell and whenever any executable shell command is given, that will be executed and as if like you have executed it in terminal normally.
expect1.1> ls
A B C D
expect1.2> cat A
I am A
expect1.3> pwd
/home/dinesh/test
expect1.4>
If you have keep them inside square brackets like [cat A], unlike a normal command call, still it will execute shell command and returns empty string.
expect1.4> set val [cat A]
I am A
expect1.5> puts "->$val<-"
-><-
expect1.6>
If you add a procedure which is having a name equivalent as that of any shell command, then only the corresponding command will be called.
expect1.6> proc cat {input} {
+> return "you passed $input\n"
+> }
expect1.7> cat A
you passed A
expect1.8> cat
wrong # args: should be "cat input"
while executing
"cat "
expect1.9> send [cat A]
you passed A
expect1.10>
Unless spawn_id is set (by means of spawning any program), Expect will always expect and send commands to the stdin and stdout respectively.
expect1.11> exp_internal 1
expect1.12> expect hai
expect: does "" (spawn_id exp0) match glob pattern "hai"? no
As you can see in the debug output, exp0 points to the stdin only.
When expect program called
When expect program is called explicitly, at that time, in order to execute any shell command, you have to use exec command, else you will get the invalid command name error message.
expect << EOF
send [exec cat hello]
EOF
Output :
[dinesh#lab test]$ ./baek.sh
I am A
[dinesh#lab test]$
Now, why this difference ?
Technically, when you are using expect shell, you are allowed with the feature of executing shell command in there itself.

expect response seen in bash debug but I cant get it.

I am trying to get the information from a keepass database and I can't get past this last step!
#!/usr/bin/env bash
#!/usr/bin/expect
firewall=$1
password="PASSWORD"
echo "connecting to KeepassDB..."
function get_creds {
expect <<- DONE
set timeout 10
spawn kpcli
match_max 100000000
expect "kpcli:/>"
send "open /media/sf_VM_shared/keepass.kdb\n"
expect "password:"
send "$password\n"
expect ">"
send "cd General/Network/Firewalls/SSH\n"
expect "SSH>"
send "ls\n"
expect ">"
DONE
}
credentials=$(get_creds)
echo $credentials
When I do a bash -x I can see what I want, it's a long list of information, but without the -x the script is not returning the list to the terminal.
You are getting the output when using bash -x because then every command output is printed after they are run (debug mode)
The script does not print because your last line of output from get_creds is empty. It should print the last line of output from the method.
When using echo to output your credentials you should use quoutes (") in order to preserve newlines.
Try replacing the last line in your script with this:
echo "$credentials"

Resources