This is a simple expect API written in pure ruby. Part of this library includes a simple procedure DSL for creating sequences of expect/send behavior.
This example will use the system ssh binary and connect to a host. Upon connecting it will execute a command and wait for the response then exit. The response from the command will be parsed and printed to the screen.
#!/usr/bin/rubyrequire'ruby_expect'username='username'password='password'hostname='hostname'exp=RubyExpect::Expect.spawn("/usr/bin/ssh #{username}@#{hostname}")exp.proceduredoretval=0while(retval != 2)retval=anydoexpect/Are you sure you want to continue connecting \(yes\/no\)\?/dosend'yes'endexpect/password:\s*$/dosendpasswordendexpect/\$\s*$/dosend'uptime'endendend# Expect each of the followingeachdoexpect/load\s+average:\s+\d+\.\d+,\s+\d+\.\d+,\s+\d+\.\d+/do# expect the output of uptimeputslast_match.to_sendexpect/\$\s+$/do# shell promptsend'exit'endendendThis example runs a script and interacts with it
#!/usr/bin/rubyrequire'ruby_expect'root_password='root_password'new_root_password='new_password'exp=RubyExpect::Expect.spawn('mysql_secure_installation',:debug=>true)exp.proceduredoeachdoexpect"Enter current password for root (enter for none):"dosendroot_passwordendexpect"Change the root password? [Y/n]"dosend"y"endexpect"New password:"dosendnew_root_passwordendexpect"Re-enter new password:"dosendnew_root_passwordendexpect"Remove anonymous users?"dosend"y"endexpect"Disallow root login remotely?"dosend"y"endexpect"Remove test database and access to it?"dosend"y"endexpect"Reload privilege tables now?"dosend"y"endendendputs"Ended expect script."This example will spawn ssh and login to the host. Once logged in, the interact method is called which returns control to the user and allows them to interact directly with the remote system
#!/usr/bin/rubyrequire'ruby_expect'username='username'password='password'hostname='hostname'exp=RubyExpect::Expect.spawn("/usr/bin/ssh #{username}@#{hostname}")exp.proceduredoretval=0while(retval != 2)retval=anydo# Accept the key if it isn't already knownexpect/Are you sure you want to continue connecting \(yes\/no\)\?/dosend'yes'end# Send the password at the promptexpect/password:\s*$/dosendpasswordend# Expect the shell promptexpect/\$\s*$/dosend""endendendend# Pass control back to the userexp.interact