Want interactive command in non-interactive mode? – use expect !!
Introduction- Since long time, I was thinking to write post on expect!!. and finally I start writing this post.. I am using expect tool for automation, scheduling and running commands on remote machine by using ssh in non-interactive mode. It’s very useful and handy tool for System admin specially Unix and Linux admin.
What is Expect ?
Expect is a Unix automation and testing tool, written by Don Libes. Expect has regular expression pattern matching and general program capabilities, allowing simple scripts to intelligently control programs such as telnet, ftp, and ssh, all of which lack a programming language, macros, or any other program mechanism. The result is that Expect scripts provide old tools with significantly new power, and flexibility.
Example (1) non interactive SSH login –
root@arunbagul:/home/arun# cat non-interactive.sh
#!/usr/bin/expect -f
spawn ssh arun@192.168.0.1
expect “password:”
sleep 1
send “mypassword\r”
interact
root@arunbagul:/home/arun#
root@arunbagul:/home/arun# ./non-interactive.sh
spawn ssh arun@192.168.0.1
arun@192.168.0.1’s password:
Linux arunbagul.com 2.6.22-14-generic #1 SMP Tue Feb 12 07:42:25 UTC 2008 i686
The programs included with the Ubuntu system are free software;
You have new mail.
Last login: Sat Mar 1 15:15:05 2008 from arunbagul.com
arun@arunbagul:~$ id=1200(arun) gid=1200(arun)
arun@arunbagul:~$
Example (2) non interactive SCP copy –
root@arunbagul:/home/arun# cat scp.sh
#!/usr/bin/expect -f
# set Variables
set source [lrange $argv 0 0]
set dest [lrange $argv 1 1]
set timeout -1
# connect via scp…
spawn scp $source $dest
#wait for the password to ask…
expect “password:”
sleep 1
#provide password after askinng
send “mypassword\r”
interact
#done
root@arunbagul:/home/arun#
* Now copy data to 192.168.0.1 system –
root@arunbagul:/home/arun# ./scp.sh /tmp/myfile.txt arun@192.168.0.1:/tmp/arun/
spawn scp /tmp/myfile.txt arun@192.168.0.1:/tmp/arun/
arun@192.168.0.1’s password:
myfile.txt 100% 8 0.0KB/s 00:00
root@arunbagul:/home/arun#
* Now copy data from 192.168.0.1 system to your system –
root@arunbagul:/home/arun#./scp.sh arun@192.168.0.1:/tmp/arun/myfile.txt /tmp/
spawn scp arun@192.168.0.1:/tmp/arun/myfile.txt /tmp/
arun@192.168.0.1’s password:
myfile.txt 100% 8 0.0KB/s 00:00
root@arunbagul:/home/arun#
Now you know, how this tool is powerful !!.. You can use this tool for automation purpose and where you don’t want to interact with system now and then use it…
Note:- In above two example script is non interactive means it will not ask you to inter password …. expect will do it for you…!!
Thank you,
Arun