Skip to content

Instantly share code, notes, and snippets.

@wusuopu
Created May 10, 2019 07:27
Show Gist options
  • Save wusuopu/b0348a7bb91a9a5f7126aa5ae1f6dcc9 to your computer and use it in GitHub Desktop.
Save wusuopu/b0348a7bb91a9a5f7126aa5ae1f6dcc9 to your computer and use it in GitHub Desktop.
ssh connection manage
#!/usr/bin/env ruby
#-*- coding:utf-8 -*-
# ssh connection manage
require 'json'
require 'optparse'
def main action, options
cfg = "#{ENV['HOME']}/.ssh/.config.json"
begin
config = JSON.parse File.read cfg
rescue
config = {}
end
case action
when 'help'
puts "list list config"
puts "add add new config, Usage: add --name <name> --host <host> [--identity_file <identity_file> [--alias <alias> [--port <port>]]]"
puts "del del config: del --name <name>"
puts "connect connect config: connect --name <name>"
when 'list'
config.each_pair do |name, value|
puts "#{name} => #{value['host']}#{value['port'] ? ':'+value['port'] : ''} #{value['alias']}"
end
when 'add'
if options[:name] && options[:host]
config[options[:name]] = {
"host": options[:host],
"identity_file": options[:identity_file],
"alias": options[:alias],
"port": options[:port]
}
File.write cfg, JSON.generate(config, indent: ' ', object_nl: "\n")
end
when 'del'
name = options[:name] || ARGV[1]
if name
config.delete name
File.write cfg, JSON.generate(config, indent: ' ', object_nl: "\n")
end
when 'connect'
value = config[options[:name] || ARGV[1]]
if value && value['host']
host = value['host']
cmd = "ssh #{host}"
if value['identity_file']
cmd = "#{cmd} -i #{value['identity_file']}"
end
if value['port']
cmd = "#{cmd} -p #{value['port']}"
end
puts cmd
exec cmd
end
end
end
if caller.length == 0 then
action = ARGV[0] || 'list'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: myssh <action> <options>"
opts.on('-nNAME', '--name=NAME', 'config name') do |v|
options[:name] = v
end
opts.on('-hHOST', '--host=HOST', 'ssh host') do |v|
options[:host] = v
end
opts.on('-pPORT', '--port=PORT', 'ssh port') do |v|
options[:port] = v
end
opts.on('-iIDENTITY_FILE', '--identity_file=IDENTITY_FILE', 'ssh identity_file') do |v|
options[:identity_file] = v
end
opts.on('-aALIAS', '--alias=ALIAS', 'ssh alias name') do |v|
options[:alias] = v
end
end.parse(ARGV[1..])
main action, options
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment