Ruby Threaded SSH

#!/usr/bin/ruby
#
# http://www.ruby-doc.org/core-1.9.3/Thread.html
# http://net-ssh.github.com/ssh/v2/api/index.html
#
# usage:
# ssh-agent bash
# ssh-add key
# ./sshlist.rb <LIST> '<CMD>'
#

if ARGV.length != 2
  puts "./sshlist.rb <LIST> <CMD>"
  exit
end

require 'net/ssh'

threadlist = []

def con(hostname)

        result = `/bin/ping -q -c 2 #{hostname}`
        if not $?.exitstatus == 0
          puts "Unable to ping:" + hostname
          return -1
        end

        begin
          Net::SSH.start(hostname , 'root' ) do |ssh|
                  output = ssh.exec! ARGV[1]
                  puts hostname + ":" + output
          end
        rescue
          puts "failed on :" + hostname + ".."
        end
end

fileList = File.open(ARGV[0]).read.split("\n")

  while fileList.length > 0 do

  (1..30).each do |n|

        line = fileList.pop
        line.strip!

        threadlist.push Thread.new {  con line }
        if fileList.length == 0
          break
        end

  end

        threadlist.each do |th|
          th.join 10
        end

  end

This ruby script using net::ssh and a list of machines and connects to 30 at a time to run a command. After 10 seconds the batch of 30 is killed off and the next 30 start. net::ssh will take a password, but I just use ssh keys.

Continue reading

Removing Puppet

Upgrading from Puppet to Puppet Enterprise and need to remove the old puppet from the machine.  here is a python snipit to remove free puppet.

# remove puppet

for filesdirs in ['/usr/bin/pi','/usr/bin/puppet','/usr/bin/ralsh', '/usr/bin/filebucket', '/usr/bin/puppetdoc', '/usr/sbin/puppetca', '/usr/sbin/puppetd', '/var/puppet/','/etc/puppet/','/usr/share/man/man8/puppet*', '/opt/puppet-*', '/opt/facter-*']:
    os.system("rm -rf %s " % ( filesdirs ) )

# remove the cron job
os.system('cat /var/spool/cron/root  | grep -v "puppetlastrun" | grep -v runpuppet > /tmp/newc')
os.system('cp /tmp/newc /var/spool/cron/root')
os.system('chmod 600 /var/spool/cron/root')