john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

Expect non interactive ssh

linux-script-programming-interactive-ability-with-expect

Don Libes, National Institute of Standards and Technology http://expect.nist.gov/

http://en.wikipedia.org/wiki/Expect

Expect is a utility that "fools" applications into using redirects from files rather than stdin a pseudo tty opened bidirectionally


4 commands: send, expect, spawn


type expect at the command prompt to start an interactive expect shell (like a perl shell)

you can then type commands, e.g.

send "hello world\n" exit //In the interactive session you type exit to quit

notice that you need to include the newline character


To use expect with scripts simply supply a file name with the expect commands

nano helloworld.txt send "hello world\n"

then you can run expect helloworld.txt

To take it one step further, create a second file

run-expect-script.sh

comment about the script

/usr/bin/expect -f $1

chmod +x run-expect-script.sh

./run-expect-script.sh helloworld.txt

This will print "hello world"...


The "expect" command will wait until a process prompts for something (e.g. htpasswd)

could also be in /usr/bin or /usr/sbin

nano helloworld.txt set timeout 10 expect "hi\n" send "hello there!\n"

./run-expect-script.sh helloworld.txt

will wait 10 seconds to timeout, but if in that time you type hi (and press enter) it will return hello world, or after 10 seconds it will still print hello world...


A faster way of achieving this is

nano test.sh #!/usr/bin/expect set timeout 10 expect "hi\n" send "hello there!\n"

chmod 755 test.sh

./test.sh


nano htpasswdscript.sh #!/usr/bin/expect set htpasswdpath [lindex $argv 0] set username [lindex $argv 1] set userpass [lindex $argv 2]

spawn htpasswd $htpasswdpath $username

expect "New password:" 
send $userpass\n

expect "Re-type new password:" 
send $userpass\n

$ ./htpasswd.sh /usr/bin/htpasswd username userpass


nano ftplogin.txt spawn ftp ftp.uu.net expect "Name" send "anonymous\r" expect "Password:" send "dtly@yboa.csc.calpoly.edu\r" interact


  • « Expect script continued
  • Startup script creating a lsb compliant custom service »

Published

Feb 6, 2010

Category

linux

~270 words

Tags

  • expect 7
  • interactive 4
  • non 5
  • scripts 63
  • ssh 14