Ruby_erb
Nothing special.. just me wanna see if Raspberry is running on the network before I bother to shut it down.
But I’be been thinking about strings.. and string templates.
So, I have a little erb
in there.
#!/usr/bin/env ruby
# frozen_string_literal: true
class Array; alias in? include?; end
class Netz
require 'open3'
require 'erb'
attr_accessor :ip, :port, :host
def initialize(ip: '192.168.8.3', port: 22, host: 'mw')
@ip, @port, @host, @bnd = ip, port, host, binding
@temps = {
nc: ERB.new('nc -zw1 <%= @ip %> <%= @port %>'),
ssh: ERB.new('ssh <%= @host %>@<%= @ip %> "sudo systemctl <%= cmd.to_s %>"')
}
end
# faster than `nmap` or `systemctl is-system-running`
def alive? = ( ocap(@temps[:nc].result(@bnd)) )
def sctl(cmd = :poweroff)
%i(poweroff reboot).in?(cmd) ?
ocap(@temps[:ssh].result(binding)) : nil
end
private
def ocap(s) = ( Open3.capture2e(s)[1].exitstatus == 0 )
end
# Examples
netz = Netz.new
# p netz.ip
# p netz.port
# p netz.host
# netz.ip = '192.168.8.2'
# p netz.alive? # => true (if Raspberry is running)
# netz.sctl(:reboot) if netz.alive?
netz.sctl if netz.alive? # poweroff if alive
The thinking I’ve been doing on strings is.. THERE’S A LOT OF ‘EM !!!
I don’t want that. I want to gather ALL strings into ONE place. I see a lot of benefits..