patrik
patrik

Reputation: 4558

How to run expect script from remote server via ssh?

I have deployed an expect script on a remote server, which I want to run via ssh.

ssh user@host 'expect -d ./netopeer_expect.sh' (1)

user@host:~$ cat netopeer_expect.sh
#!/usr/bin/expect

set timeout 5
#spawn netopeer2-cli
spawn ./np2_multi_cli
expect ">"
send "listen --timeout 120\r"
expect "ru_id 0"
send "get-config -D=0 --source running --out /home/user/out.xml\r"
expect ">"
send "exit\r"
expect "$"

This code runs a modified version of the netopeer2-cli, which we call ./np2_multi_cli. This netopeer2-cli have an own shell and a prompt like >. It works fine when I do it in two steps

ssh user@host
expect -d ./netopeer_expect.sh (2)

However, the message

send "get-config -D=0 --source running --out /home/user/out.xml\r"

is cut and is sent as,

send "-D=0 --source running --out /home/user/out.xml\r"

From running (1) with the -d argument I see this,

expect: does "\u001b[6n" (spawn_id exp3) match glob pattern ">"? no

When I try to match the first >. When I instead try to run (2), it looks as it should,

expect: does "> " (spawn_id exp4) match glob pattern ">"? yes

I run bash and it seems as if there are some encoding issues regarding the > character. Any idea how to deal with this?

BR Patrik

Upvotes: 3

Views: 1360

Answers (2)

pynexj
pynexj

Reputation: 20798

Did some investigation and found out why ssh -t makes a difference in patrik's answer. See the following examples:

enter image description here

According to Expect manual:

Internally, spawn uses a pty, initialized the same way as the user's tty.

With -t, ssh would allocate a pty (the same type as the local $TERM) for the remote session, then expect allocates a pty of the same type.

Without -t, ssh would not allocate pty for the remote session, and expect uses the (default?) dumb tty which is not fully featured. As a "workaround", we can explicityly set the TERM var (e.g. set env(TERM) vt100) before spawn.


Here's the command I used. Just for easy copy-and-paste.

[STEP 101] # cmd=' "spawn -noe bash -c {echo TERM=\$TERM | grep --color TERM}; expect eof" '
[STEP 102] #
[STEP 103] # ssh 127.0.0.1 expect -c "$cmd"
TERM=dumb
[STEP 104] # ssh -t 127.0.0.1 expect -c "$cmd"
TERM=linux
Connection to 127.0.0.1 closed.
[STEP 105] #
[STEP 106] # cmd=' "set env(TERM) vt100; spawn -noe bash -c {echo TERM=\$TERM | grep --color TERM}; expect eof" '
[STEP 107] # ssh 127.0.0.1 expect -c "$cmd"
TERM=vt100
[STEP 108] #

Upvotes: 3

patrik
patrik

Reputation: 4558

Looks as if I made a faulty call when I was running ssh. I forced pseudo terminal allocation it went fine,

ssh -t -t [email protected] 'expect -d ./netopeer_expect.sh'

Upvotes: 3

Related Questions