Streaming SSH Output with Ruby

I'm going to show you how to stream the output of an SSH command in the middle of a Ruby script. I was recently building a script to handle distributed configuration. The script would ask the user a set of questions, then connect to distributed systems to validate the responses and finally deploy the software and configure it.

It was pretty simple to get the basic communication working by running SSH commands and processing the results after the command finished. But I wanted to be able to display log messages and status to the user in real-time. The catch is that the user must have the Net::SSH gem installed.

if defined?(Net::SSH)
  ssh = Net::SSH.start(centosa2, 'username')
  ssh.exec!(". /etc/profile; mysqlbinlog /var/lib/mysql/mysql-bin.*") do
    |ch, stream, line|
    puts line
  puts `ssh username@centosa2 -o \"PreferredAuthentications publickey\" -o \"IdentitiesOnly yes\" -o \"StrictHostKeyChecking no\" \". /etc/profile; mysqlbinlog /var/lib/mysql/mysql-bin.*\" 2>&1`.chomp
It's just that simple. In this case, the user is setup with SSH key authentication so that the program doesn't have to have a password in it.