superK
superK

Reputation: 3982

Linux expect command without interact directive not working

I want to login from 192.168.119.128 to 192.168.119.129 automatic and run some commands, so I write an expect script.

a.sh

#!/usr/bin/expect -f

set timeout 5
spawn ssh [email protected]
expect "password" {send "123456\r"}
expect "]#" {send "touch /tmp/a.txt\r"}
#interact

The output is:

kaiwen@kaiwen-virtual-machine:~/Work$ ./a.sh 
spawn ssh [email protected]
[email protected]'s password: 
Last login: Sun Jan 22 17:36:21 2017 from 192.168.119.128
[root@localhost ~]# kaiwen@kaiwen-virtual-machine:~/Work$

I login successfuly, but it seems touch /tmp/a.txt command is not run.

When I uncomment the last line #interact of a.sh, it works, and the file a.txt is created.

#!/usr/bin/expect -f

set timeout 5
spawn ssh [email protected]
expect "password" {send "123456\r"}
expect "]#" {send "touch /tmp/a.txt\r"}
interact

Here is the output:

kaiwen@kaiwen-virtual-machine:~/Work$ ./a.sh 
spawn ssh [email protected]
[email protected]'s password: 
Last login: Sun Jan 22 17:41:23 2017 from 192.168.119.128
[root@localhost ~]# touch /tmp/a.txt
[root@localhost ~]#

Why without the interact directive the script work incorrect? Thanks.

Upvotes: 1

Views: 1542

Answers (1)

pynexj
pynexj

Reputation: 20797

Without interact the Expect script will exit after the last command expect "]#" and it'll kill the spawned process. It's just like you close the SSH client application (like PuTTY) window when the shell is still alive running.

The interact is a long-running command which waits for the spawned process to exit.

Upvotes: 2

Related Questions