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 root@192.168.119.129 expect "password" {send "123456r"} expect "]#" {send "touch /tmp/a.txtr"} #interact
The output is:
kaiwen@kaiwen-virtual-machine:~/Work$ ./a.sh spawn ssh root@192.168.119.129 root@192.168.119.129'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 root@192.168.119.129 expect "password" {send "123456r"} expect "]#" {send "touch /tmp/a.txtr"} interact
Here is the output:
kaiwen@kaiwen-virtual-machine:~/Work$ ./a.sh spawn ssh root@192.168.119.129 root@192.168.119.129'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.
Advertisement
Answer
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.