背景
複数のサーバにまたがってログを確認する、などということをするときに、いちいち
- ssh して
- cd して
- less して
- exit して
を繰り返すと非常にだるい
解決策
capistrano/sshkitを使うと、コマンドラインの操作を自動化出来ます。
公式サンプルも豊富です => これ
サンプル
複数のインスタンスに入って、ホームディレクトリの中にあるファイルを覗いてみることにします。
以下のようになります。
また ruby の実行バイナリまでのパスを書くと、リモートにおいてある ruby のスクリプトも実行出来ます
get_log_file.rb
require 'sshkit'
require 'sshkit/dsl'
hosts = ['192.168.10.4', '192.168.10.5', '192.168.10.6']
hosts.each do |host|
remote = SSHKit::Host.new(host)
remote.user = 'vagrant'
remote.ssh_options = {
keys: ['/home/r-fujiwara/path/to/private/key'],
auth_methods: %w(publickey)
}
rb_path = '/usr/local/rbenv/shims/ruby'
on remote do
# なんかのログをのぞく
execute :cat, '/home/remote_user/some.log'
# Rubyを実行
execute :rb_path, '/home/remote_user/hoge.rb'
end
end
応用
- thorを使って任意のシェルをコマンドラインから渡すことも出来ます。
sshkit-implemantation.rb
#! /usr/bin/env ruby
require 'sshkit'
require 'sshkit/dsl'
require 'thor'
hosts = ['192.168.33.4', '192.168.33.5', '192.168.33.6']
def execute_host(command, args)
hosts.each do |host|
remote = SSHKit::Host.new(host)
remote.user = 'vagrant'
remote.ssh_options = {
keys: ['/home/r-fujiwara/path/to/private/key'],
auth_methods: %w(publickey)
}
on remote do
execute command.to_sym, args
end
end
class CLI < Thor
desc "exec", 'exec shell script'
option :command, aliases: "c"
option :args, aliases: "a"
def exec
execute_host(options[:command], options[:args])
end
end
CLI.start(ARGV)
これを以下のように実行することでリモートのrubyのプロセスを確認することが出来ます。
$ ./sshkit-implemantation.rb exec -c 'ps' -a 'aux|grep ruby'