The idea
At my work, I'm tasked with retrieving logs for a list of online orders from a total of 12 servers. To do this, I SSH into them (with a jump host in between) one by one, run the script for every order, then parse the output. Overall, a very tedious process that I'm sure can be automated.
W -> J -> S
W = My Windows VM
J = Red Hat jump box
S = The Red Hat production servers
So the basic idea is the following:
Connect to every server by SSH
On every server, run the commands for all orders which are passed by command line
Associate each output with the order
Here is what I've come up with so far, and it is working on my home lab. But before I bring it in to work to propose it and try it on production servers, I want to know how the code can be cleaned up or done more efficiently.
The code
require 'net/ssh'
require 'io/console'
require 'pp'
ORDERS = ARGV.dup()
ARGV.clear()
SERVERS = [
"prod1",
"prod2",
"prod3"
]
COMMAND = "aux_search.sh"
CONFIG = "C:/Users/myuser/.ssh/config"
RESULTS = ORDERS.each_with_object({}) { |k, v| v[k] = "" }
puts("Enter your username: ")
USERNAME = gets().chomp()
puts("Enter your password for accessing the servers: ")
SERVERPASSWORD = STDIN.noecho(&:gets).chomp()
puts("Enter your sudo password: ")
SUDOPASSWORD = STDIN.noecho(&:gets).chomp()
SESSIONS = []
SERVERS.each do |server|
session = Net::SSH.start(server, USERNAME, :password => SERVERPASSWORD, :config => CONFIG,
:verbose => :debug, :auth_methods => ["publickey", "password"], :verify_host_key => :accept_new)
SESSIONS << session
end
SESSIONS.each do |ssh|
ORDERS.each do |order|
ssh.open_channel() do |channel|
channel.on_data do |_, data|
RESULTS[order].concat(data)
if data.match(/\[sudo\]/)
channel.send_data("#{SUDOPASSWORD}\n")
end
end
channel.request_pty() do |_, success|
raise "Failed to request TTY for order #{order}" unless success
end
channel.exec("sudo ./#{COMMAND} #{order}") do |_, success|
raise "Could not execute command #{COMMAND} #{order}" unless success
end
end
end
ssh.loop()
end
puts("===Results===")
pp(RESULTS)
My ssh config
Host jumpbox
HostName 192.168.16.2
User johrus2
IdentityFile C:\Users\myuser\.ssh\id_rsa3
Port 22
Host prod1
HostName 192.168.16.3
User johrus2
IdentityFile C:\Users\myuser\.ssh\id_rsa3
ProxyJump jumpbox
Port 22
Host prod2
HostName 192.168.16.4
User johrus2
IdentityFile C:\Users\myuser\.ssh\id_rsa3
ProxyJump jumpbox
Port 22
Host prod3
HostName 192.168.16.5
User johrus2
IdentityFile C:\Users\myuser\.ssh\id_rsa3
ProxyJump jumpbox
Port 22
```