in Uncategorized

Short Expect Tutorial

So lets say you wanted to automate a login into a machine using ssh but not having to do the ssh key sharing thats explained in many posts including this one. You could use expect to do the same thing and more. Below is a script that you pass the domain you want to connect to, the password and the command to run and it runs this automatically. You need expect inorder to run this. save the below as file run.exp:

1. spawn ssh [lindex $argv 0]
2. set psd [lindex $argv 1]
3. set cmd [lindex $argv 2]
4. expect “Password:”
5. send “$psdr”
6. expect “.*”
7. send “$cmdr”
8. expect eof

  • spawn: used to start a program
  • expect: used to wait for a string
  • send: used to send command
  • interact: used to switch the control to the user.

You can run this as: ./run.exp <root@myhost> <mypassword> <thecommandtorun>

e.g ./run.exp root@foo.bar bob123 w

this would ssh into foo.bar as user root using password bob123 and then show a listing of everyone who is logged in and what they are doing.