jmp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 91fbbdade4dea6e1c7e4490efc5fbbd8a2b7944c787659cebac677962a1de17d
4
+ data.tar.gz: 01cfad99a4f480ae50f025fc4780e5283373081e657f7a7007893ce14d38c875
5
+ SHA512:
6
+ metadata.gz: 3ec7c9aa74f0de19f2e23df6747b6070b945c62438e698985849270dc070f268357b44fb97b2ef5a67f47ba27d616ff316c3d8deb06fd547cb4fc687ce5fa09b
7
+ data.tar.gz: b29ee65f3cfa635b425b70d64489e0da15ee4af81ea33089a683f4bdb112151141cf28afa102b9a271ef926db0cd65564790f831b361fb6a87ac3ee1fefd00e4
data/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # jmp
2
+
3
+ `jmp` is a command-line SSH connection and SCP file transfer manager. Save host profiles once, then connect or copy files by alias.
4
+
5
+ ## Installation
6
+
7
+ Requires Ruby >= 3.1.
8
+
9
+ ```sh
10
+ gem build jmp.gemspec
11
+ gem install ./jmp-0.1.0.gem
12
+ ```
13
+
14
+ Password authentication additionally requires [`sshpass`](https://sourceforge.net/projects/sshpass/) on your `PATH`.
15
+
16
+ ## Usage
17
+
18
+ ```sh
19
+ jmp # Pick a saved alias from a list and ssh to it
20
+ jmp --config # Manage saved hosts interactively
21
+ jmp <target> # ssh to a saved alias or a raw hostname
22
+ jmp <target> --copy <sourcepath> <dest> # scp a local file or directory to the target
23
+ jmp --copy <sourcepath> <dest> <target> # Same, with --copy first
24
+ jmp -h | --help # Show usage
25
+ jmp -v | --version # Show version
26
+ ```
27
+
28
+ Running `jmp` with no arguments lists the aliases of all saved hosts (type to filter); selecting one connects to it. If no hosts are saved, or stdin is not a terminal, usage is printed and `jmp` exits with status 1.
29
+
30
+ `<target>` is looked up by alias first. If no saved host matches, it is treated as a raw hostname with port 22, your current username and SSH agent authentication.
31
+
32
+ Directories are copied recursively (`scp -r`) automatically. The source path is expanded locally and must exist.
33
+
34
+ ### Port forwarding
35
+
36
+ ```sh
37
+ jmp <target> --localport <localport>:<remotehost>:<remoteport> # ssh -L
38
+ jmp <target> --remoteport <remotehost>:<remoteport>:<localhost>:<localport> # ssh -R
39
+ jmp <target> --dynamicport <localport> # ssh -D (SOCKS proxy)
40
+ ```
41
+
42
+ Examples:
43
+
44
+ ```sh
45
+ jmp prod-web --localport 5432:db.internal:5432 # localhost:5432 -> db.internal:5432 via prod-web
46
+ jmp prod-web --remoteport 0.0.0.0:9000:localhost:3000 # prod-web:9000 -> your localhost:3000
47
+ jmp myhost --dynamicport 27017 # SOCKS proxy on localhost:27017 via myhost
48
+ ```
49
+
50
+ For `--remoteport`, `<remotehost>` is the address the port is bound to on the remote side (e.g. `localhost` or `0.0.0.0`; binding to non-loopback addresses requires `GatewayPorts` on the server). IPv6 addresses must be bracketed, e.g. `[::1]`.
51
+
52
+ Each flag can be repeated and the flags can be combined. Port forwarding opens a normal interactive session alongside the forwards; it cannot be combined with `--copy` or `--config`.
53
+
54
+ ### Interactive configuration
55
+
56
+ `jmp --config` opens a menu that lists `<NEW>` first, then every saved host as `alias (user@hostname:port)`, then `Exit`.
57
+
58
+ - **`<NEW>`** prompts for alias, hostname, port, username, authentication method (SSH Agent / Default, Keyfile or Password) and SSH options. SSH options are entered one per prompt; leave the prompt blank to finish.
59
+ - **Selecting a host** shows its details (passwords masked as `********`) and offers **Edit**, **Delete** or **Back**. When editing, press Enter to keep the current value. Existing SSH options are shown as a checklist (untick to remove), after which new options can be added.
60
+
61
+ Press Ctrl+C at any time to exit.
62
+
63
+ ## Configuration file
64
+
65
+ Hosts are stored in `$XDG_CONFIG_HOME/jmp/hosts.yml` (default `~/.config/jmp/hosts.yml`). The directory is created with `0700` permissions and the file is always written with `0600`.
66
+
67
+ ```yaml
68
+ hosts:
69
+ - alias: prod-web
70
+ hostname: 192.168.1.50
71
+ port: 22
72
+ username: deploy
73
+ auth_type: keyfile # agent, keyfile or password
74
+ keyfile: ~/.ssh/id_ed25519
75
+ password:
76
+ ssh_options:
77
+ - ServerAliveInterval=30
78
+ - StrictHostKeyChecking=accept-new
79
+ ```
80
+
81
+ Rules:
82
+
83
+ - `alias`: required, unique, matches `[a-zA-Z0-9._-]+`, cannot be `<NEW>` or start with `-`.
84
+ - `hostname`: required, no whitespace.
85
+ - `port`: 1–65535 (default `22`).
86
+ - `username`: required (default: current user).
87
+ - `auth_type`: `agent` (default), `keyfile` (requires `keyfile`; `~` is expanded when connecting) or `password` (requires `password`).
88
+ - `ssh_options`: optional list of OpenSSH options in `Key=Value` or `Key Value` form. Each is passed to both `ssh` and `scp` as `-o <option>`. See `man ssh_config` for available options.
89
+
90
+ If `hosts.yml` cannot be parsed, `jmp` backs it up to `hosts.yml.bak`, prints a warning and exits with status 1.
91
+
92
+ ### Security note
93
+
94
+ Stored passwords are kept in plain text (protected only by file permissions) and are passed to `sshpass -p`, which makes them briefly visible to other local users via the process list. Prefer keyfile or agent authentication where possible.
95
+
96
+ ## Development
97
+
98
+ ```sh
99
+ bundle install
100
+ bundle exec rspec
101
+ bundle exec rubocop
102
+ ```
data/bin/jmp ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ $LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
5
+ require "jmp"
6
+
7
+ Jmp::CLI.start(ARGV)
data/jmp.gemspec ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ version = File.read(File.expand_path("lib/jmp.rb", __dir__))[/VERSION = "([^"]+)"/, 1]
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "jmp"
7
+ spec.version = version
8
+ spec.authors = ["Nitin"]
9
+ spec.summary = "Command-line SSH connection and SCP file transfer manager."
10
+ spec.description = "Save SSH host profiles, connect with `jmp <alias>`, copy files with " \
11
+ "`jmp <alias> --copy <src> <dest>`, and manage hosts interactively with `jmp --config`."
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = ">= 3.1"
14
+
15
+ spec.files = Dir["lib/**/*.rb", "bin/*", "README.md", "jmp.gemspec"]
16
+ spec.bindir = "bin"
17
+ spec.executables = ["jmp"]
18
+ spec.require_paths = ["lib"]
19
+
20
+ spec.add_dependency "tty-prompt", "~> 0.23"
21
+ spec.metadata["rubygems_mfa_required"] = "true"
22
+ end
data/lib/jmp/cli.rb ADDED
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+
5
+ module Jmp
6
+ # Parses arguments and routes to help, version, the TUI, ssh or scp.
7
+ class CLI
8
+ class UsageError < Error; end
9
+
10
+ COPY_FLAG = "--copy"
11
+ FORWARD_USAGE = {
12
+ local: "<localport>:<remotehost>:<remoteport>",
13
+ remote: "<remotehost>:<remoteport>:<localhost>:<localport>",
14
+ dynamic: "<localport>"
15
+ }.freeze
16
+
17
+ def self.start(argv)
18
+ exit(new.run(argv))
19
+ rescue Interrupt
20
+ exit(130)
21
+ end
22
+
23
+ def initialize(config: Config.new, runner: Runner.new, out: $stdout, err: $stderr, input: $stdin,
24
+ tui_factory: ->(cfg) { TUI.new(config: cfg) })
25
+ @config = config
26
+ @runner = runner
27
+ @out = out
28
+ @err = err
29
+ @input = input
30
+ @tui_factory = tui_factory
31
+ end
32
+
33
+ # Returns an exit status. The ssh path replaces the process and does not return.
34
+ def run(argv)
35
+ return run_picker if argv.empty?
36
+
37
+ options = parse(argv.dup)
38
+ return print_help if options[:help]
39
+ return print_version if options[:version]
40
+ return run_config(options) if options[:config]
41
+ return run_copy(options) if options[:copy]
42
+
43
+ run_ssh(options)
44
+ rescue UsageError, OptionParser::ParseError => e
45
+ @err.puts("Error: #{e.message}")
46
+ @err.puts(usage)
47
+ 1
48
+ rescue Error => e
49
+ @err.puts("Error: #{e.message}")
50
+ 1
51
+ rescue SystemCallError => e
52
+ @err.puts("Error: failed to execute command: #{e.message}")
53
+ 1
54
+ end
55
+
56
+ def usage
57
+ parser.to_s
58
+ end
59
+
60
+ private
61
+
62
+ def parse(argv)
63
+ options = { targets: [], forwards: [] }
64
+ copy_index = argv.index(COPY_FLAG)
65
+ if copy_index
66
+ options[:copy] = argv[(copy_index + 1), 2]
67
+ argv.slice!(copy_index, 3)
68
+ end
69
+ options[:targets] = parser(options).parse(argv)
70
+ options
71
+ end
72
+
73
+ def parser(options = {})
74
+ OptionParser.new do |opts|
75
+ opts.banner = <<~BANNER
76
+ Usage:
77
+ jmp Pick a saved host from a list and connect via ssh
78
+ jmp <target> Connect to a saved alias or raw hostname via ssh
79
+ jmp <target> --copy <sourcepath> <destpath> Copy a local file/directory to the target via scp
80
+ jmp <target> --localport <localport>:<remotehost>:<remoteport>
81
+ jmp <target> --remoteport <remotehost>:<remoteport>:<localhost>:<localport>
82
+ jmp <target> --dynamicport <localport>
83
+ jmp --config Manage saved hosts interactively
84
+
85
+ Options:
86
+ BANNER
87
+ opts.on("--config", "Manage saved hosts interactively") { options[:config] = true }
88
+ opts.on("--copy", "Copy <sourcepath> to <destpath> on <target> (see usage)")
89
+ opts.on("--localport SPEC", "Local port forward (ssh -L)") { |v| add_forward(options, :local, v) }
90
+ opts.on("--remoteport SPEC", "Remote port forward (ssh -R)") { |v| add_forward(options, :remote, v) }
91
+ opts.on("--dynamicport PORT", "Dynamic (SOCKS) port forward (ssh -D)") { |v| add_forward(options, :dynamic, v) }
92
+ opts.on("-h", "--help", "Show this help") { options[:help] = true }
93
+ opts.on("-v", "--version", "Show version") { options[:version] = true }
94
+ end
95
+ end
96
+
97
+ def add_forward(options, kind, spec)
98
+ args = Runner.forward_args(kind, spec)
99
+ raise OptionParser::InvalidArgument, "#{spec} (expected #{FORWARD_USAGE.fetch(kind)})" if args.nil?
100
+
101
+ options[:forwards].concat(args)
102
+ end
103
+
104
+ # Lists saved aliases and connects to the selected one. Falls back to usage when
105
+ # there is nothing to pick from or no interactive terminal.
106
+ def run_picker
107
+ if @config.hosts.empty? || !@input.tty?
108
+ @err.puts(usage)
109
+ return 1
110
+ end
111
+
112
+ host = @tui_factory.call(@config).pick_host
113
+ return 0 if host.nil?
114
+
115
+ @runner.ssh(host.validate!(require_alias: false))
116
+ end
117
+
118
+ def print_help
119
+ @out.puts(usage)
120
+ 0
121
+ end
122
+
123
+ def print_version
124
+ @out.puts("jmp #{VERSION}")
125
+ 0
126
+ end
127
+
128
+ def run_config(options)
129
+ unless options[:targets].empty? && !options[:copy] && options[:forwards].empty?
130
+ raise UsageError, "--config does not accept other arguments."
131
+ end
132
+
133
+ @tui_factory.call(@config).run
134
+ end
135
+
136
+ def run_copy(options)
137
+ raise UsageError, "port forwarding cannot be combined with --copy." unless options[:forwards].empty?
138
+
139
+ source, destination = options[:copy]
140
+ if [source, destination].any? { |v| v.nil? || v.empty? }
141
+ raise UsageError, "--copy requires <sourcepath> and <destinationpath>."
142
+ end
143
+
144
+ @runner.check_source!(source)
145
+ host = resolve(single_target(options))
146
+ @runner.scp(host, source, destination)
147
+ end
148
+
149
+ def run_ssh(options)
150
+ host = resolve(single_target(options))
151
+ @runner.ssh(host, options[:forwards])
152
+ end
153
+
154
+ def single_target(options)
155
+ targets = options[:targets]
156
+ raise UsageError, "missing <target>." if targets.empty?
157
+ raise UsageError, "unexpected arguments: #{targets.drop(1).join(" ")}" if targets.size > 1
158
+
159
+ targets.first
160
+ end
161
+
162
+ # Looks up a saved alias, falling back to treating the target as a raw hostname.
163
+ def resolve(target)
164
+ host = @config.find(target) || Host.for_hostname(target)
165
+ host.validate!(require_alias: false)
166
+ end
167
+ end
168
+ end
data/lib/jmp/config.rb ADDED
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require "fileutils"
5
+
6
+ module Jmp
7
+ # Persists host profiles to hosts.yml with restrictive file permissions.
8
+ class Config
9
+ DIR_MODE = 0o700
10
+ FILE_MODE = 0o600
11
+
12
+ # Raised when hosts.yml cannot be parsed. The corrupt file is backed up first.
13
+ class CorruptConfigError < Error
14
+ attr_reader :backup_path
15
+
16
+ def initialize(message, backup_path)
17
+ super(message)
18
+ @backup_path = backup_path
19
+ end
20
+ end
21
+
22
+ attr_reader :path
23
+
24
+ def self.default_path
25
+ xdg = ENV.fetch("XDG_CONFIG_HOME", nil)
26
+ base = xdg.nil? || xdg.strip.empty? ? File.expand_path("~/.config") : xdg
27
+ File.join(base, "jmp", "hosts.yml")
28
+ end
29
+
30
+ def initialize(path = self.class.default_path)
31
+ @path = path
32
+ end
33
+
34
+ def hosts
35
+ load_hosts
36
+ end
37
+
38
+ def find(name)
39
+ hosts.find { |host| host.alias == name }
40
+ end
41
+
42
+ def add(host)
43
+ current = hosts
44
+ host.validate!(taken: current.map(&:alias))
45
+ write(current + [host])
46
+ host
47
+ end
48
+
49
+ def update(original_alias, host)
50
+ current = hosts
51
+ index = current.index { |h| h.alias == original_alias }
52
+ raise Error, "Host '#{original_alias}' not found." if index.nil?
53
+
54
+ others = current.each_with_index.reject { |_, i| i == index }.map { |h, _| h.alias }
55
+ host.validate!(taken: others)
56
+ current[index] = host
57
+ write(current)
58
+ host
59
+ end
60
+
61
+ def delete(name)
62
+ current = hosts
63
+ remaining = current.reject { |host| host.alias == name }
64
+ return false if remaining.size == current.size
65
+
66
+ write(remaining)
67
+ true
68
+ end
69
+
70
+ private
71
+
72
+ def load_hosts
73
+ return [] unless File.exist?(path)
74
+
75
+ data = YAML.safe_load_file(path)
76
+ return [] if data.nil?
77
+
78
+ entries = data.is_a?(Hash) ? data["hosts"] : :invalid
79
+ return [] if entries.nil?
80
+ raise corrupt!("expected a top-level 'hosts' list") unless entries.is_a?(Array) && entries.all?(Hash)
81
+
82
+ entries.map { |entry| Host.from_h(entry) }
83
+ rescue Psych::SyntaxError, Psych::DisallowedClass => e
84
+ raise corrupt!(e.message)
85
+ end
86
+
87
+ def corrupt!(reason)
88
+ backup = "#{path}.bak"
89
+ FileUtils.cp(path, backup)
90
+ File.chmod(FILE_MODE, backup)
91
+ CorruptConfigError.new("Config file '#{path}' is corrupt (#{reason}). Backed up to '#{backup}'.", backup)
92
+ end
93
+
94
+ def write(hosts)
95
+ ensure_directory
96
+ yaml = YAML.dump({ "hosts" => hosts.map(&:to_h) })
97
+ tmp = "#{path}.tmp-#{Process.pid}"
98
+ File.open(tmp, File::WRONLY | File::CREAT | File::TRUNC, FILE_MODE) { |f| f.write(yaml) }
99
+ File.chmod(FILE_MODE, tmp)
100
+ File.rename(tmp, path)
101
+ File.chmod(FILE_MODE, path)
102
+ ensure
103
+ FileUtils.rm_f(tmp) if tmp && File.exist?(tmp)
104
+ end
105
+
106
+ def ensure_directory
107
+ dir = File.dirname(path)
108
+ return if File.directory?(dir)
109
+
110
+ FileUtils.mkdir_p(dir, mode: DIR_MODE)
111
+ File.chmod(DIR_MODE, dir)
112
+ end
113
+ end
114
+ end
data/lib/jmp/host.rb ADDED
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "etc"
4
+
5
+ module Jmp
6
+ class ValidationError < Error; end
7
+
8
+ # A saved (or ad-hoc) SSH host profile.
9
+ class Host
10
+ AUTH_TYPES = %w[agent keyfile password].freeze
11
+ ALIAS_FORMAT = /\A[a-zA-Z0-9._-]+\z/
12
+ RESERVED_ALIASES = ["<NEW>"].freeze
13
+ PORT_RANGE = (1..65_535)
14
+ DEFAULT_PORT = 22
15
+ DEFAULT_AUTH_TYPE = "agent"
16
+ # An OpenSSH `-o` option: "Key=Value" or "Key Value" on a single line.
17
+ SSH_OPTION_FORMAT = /\A[A-Za-z][A-Za-z0-9]*(\s*=\s*|\s+)\S.*\z/
18
+ ATTRIBUTES = %w[alias hostname port username auth_type keyfile password ssh_options].freeze
19
+
20
+ attr_accessor(*ATTRIBUTES.map(&:to_sym))
21
+
22
+ def self.default_username
23
+ ENV.fetch("USER", nil) || Etc.getlogin
24
+ end
25
+
26
+ def self.from_h(hash)
27
+ new(hash.transform_keys(&:to_s))
28
+ end
29
+
30
+ # Builds a host for a target that is not a saved alias.
31
+ def self.for_hostname(hostname)
32
+ new("hostname" => hostname)
33
+ end
34
+
35
+ def self.alias_error(value, taken = [])
36
+ value = value.to_s
37
+ return "Alias is required." if value.strip.empty?
38
+ return "Alias '#{value}' is reserved." if RESERVED_ALIASES.include?(value)
39
+ return "Alias cannot start with '-'." if value.start_with?("-")
40
+ return "Alias may only contain letters, digits, '.', '_' and '-'." unless ALIAS_FORMAT.match?(value)
41
+ return "Alias '#{value}' is already in use." if taken.include?(value)
42
+
43
+ nil
44
+ end
45
+
46
+ def self.hostname_error(value)
47
+ return "Hostname is required." unless value.is_a?(String) && !value.strip.empty?
48
+ return "Hostname cannot contain whitespace." if value.match?(/\s/)
49
+
50
+ nil
51
+ end
52
+
53
+ def self.port_error(value)
54
+ return nil if value.is_a?(Integer) && PORT_RANGE.cover?(value)
55
+
56
+ "Port must be an integer between #{PORT_RANGE.min} and #{PORT_RANGE.max}."
57
+ end
58
+
59
+ def self.username_error(value)
60
+ return "Username is required." unless value.is_a?(String) && !value.strip.empty?
61
+
62
+ nil
63
+ end
64
+
65
+ def self.auth_type_error(value)
66
+ return nil if AUTH_TYPES.include?(value)
67
+
68
+ "Authentication type must be one of: #{AUTH_TYPES.join(", ")}."
69
+ end
70
+
71
+ def self.ssh_option_error(value)
72
+ return nil if value.is_a?(String) && SSH_OPTION_FORMAT.match?(value)
73
+
74
+ "SSH option '#{value}' must look like Key=Value (e.g. ServerAliveInterval=30)."
75
+ end
76
+
77
+ def self.ssh_options_error(value)
78
+ return "SSH options must be a list." unless value.is_a?(Array)
79
+
80
+ value.filter_map { |option| ssh_option_error(option) }.first
81
+ end
82
+
83
+ # Accepts a single option string as shorthand for a one-element list.
84
+ def self.coerce_ssh_options(value)
85
+ case value
86
+ when nil then []
87
+ when String then [value]
88
+ else value
89
+ end
90
+ end
91
+
92
+ # Converts "22" to 22; leaves anything non-numeric untouched so validation can reject it.
93
+ def self.coerce_port(value)
94
+ value.is_a?(String) && value.strip.match?(/\A\d+\z/) ? value.strip.to_i : value
95
+ end
96
+
97
+ def initialize(attrs = {})
98
+ attrs = attrs.transform_keys(&:to_s)
99
+ @alias = attrs["alias"]
100
+ @hostname = attrs["hostname"]
101
+ @port = self.class.coerce_port(attrs["port"].nil? ? DEFAULT_PORT : attrs["port"])
102
+ @username = attrs["username"].nil? ? self.class.default_username : attrs["username"]
103
+ @auth_type = attrs["auth_type"].nil? ? DEFAULT_AUTH_TYPE : attrs["auth_type"].to_s
104
+ @keyfile = attrs["keyfile"]
105
+ @password = attrs["password"]
106
+ @ssh_options = self.class.coerce_ssh_options(attrs["ssh_options"])
107
+ end
108
+
109
+ # Returns a list of validation messages (empty when valid).
110
+ # `taken` lists aliases already used by other saved hosts.
111
+ def errors(taken: [], require_alias: true)
112
+ messages = []
113
+ messages << self.class.alias_error(@alias, taken) if require_alias || !@alias.nil?
114
+ messages << self.class.hostname_error(hostname)
115
+ messages << self.class.port_error(port)
116
+ messages << self.class.username_error(username)
117
+ messages << self.class.auth_type_error(auth_type)
118
+ messages << self.class.ssh_options_error(ssh_options)
119
+ messages << "Keyfile is required for keyfile authentication." if auth_type == "keyfile" && blank?(keyfile)
120
+ messages << "Password is required for password authentication." if auth_type == "password" && blank?(password)
121
+ messages.compact
122
+ end
123
+
124
+ def valid?(**opts)
125
+ errors(**opts).empty?
126
+ end
127
+
128
+ def validate!(**opts)
129
+ messages = errors(**opts)
130
+ raise ValidationError, messages.join(" ") unless messages.empty?
131
+
132
+ self
133
+ end
134
+
135
+ def label
136
+ "#{@alias} (#{username}@#{hostname}:#{port})"
137
+ end
138
+
139
+ def to_h
140
+ ATTRIBUTES.to_h { |attr| [attr, public_send(attr)] }
141
+ end
142
+
143
+ def ==(other)
144
+ other.is_a?(Host) && other.to_h == to_h
145
+ end
146
+
147
+ private
148
+
149
+ def blank?(value)
150
+ value.nil? || value.to_s.strip.empty?
151
+ end
152
+ end
153
+ end
data/lib/jmp/runner.rb ADDED
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jmp
4
+ # Builds ssh/scp command arrays and executes them without a shell.
5
+ class Runner
6
+ class SshpassMissingError < Error; end
7
+ class SourceNotFoundError < Error; end
8
+
9
+ SSHPASS_MISSING = "sshpass is required for stored password authentication but was not found in PATH. " \
10
+ "Install sshpass or switch this host to keyfile/agent authentication."
11
+
12
+ FORWARD_FLAGS = { local: "-L", remote: "-R", dynamic: "-D" }.freeze
13
+ FORWARD_HOST = /(?:\[[^\]\s]+\]|[^:\s\[\]]+)/
14
+ FORWARD_PORT = /(\d{1,5})/
15
+ FORWARD_FORMATS = {
16
+ local: /\A#{FORWARD_PORT}:#{FORWARD_HOST}:#{FORWARD_PORT}\z/,
17
+ remote: /\A#{FORWARD_HOST}:#{FORWARD_PORT}:#{FORWARD_HOST}:#{FORWARD_PORT}\z/,
18
+ dynamic: /\A#{FORWARD_PORT}\z/
19
+ }.freeze
20
+
21
+ # Returns the ssh arguments for a port forward (e.g. ["-L", "8080:db:5432"]),
22
+ # or nil if the spec is malformed or contains a port outside 1..65535.
23
+ def self.forward_args(kind, spec)
24
+ match = FORWARD_FORMATS.fetch(kind).match(spec.to_s)
25
+ return nil unless match&.captures&.all? { |port| Host::PORT_RANGE.cover?(port.to_i) }
26
+
27
+ [FORWARD_FLAGS.fetch(kind), spec]
28
+ end
29
+
30
+ def initialize(path: ENV.fetch("PATH", ""))
31
+ @path = path
32
+ end
33
+
34
+ # `forwards` is a flat list of forwarding arguments built by Runner.forward_args.
35
+ def ssh_command(host, forwards = [])
36
+ cmd = ["ssh", "-p", host.port.to_s]
37
+ cmd += ["-i", File.expand_path(host.keyfile)] if host.auth_type == "keyfile"
38
+ cmd += option_args(host)
39
+ cmd += forwards
40
+ cmd << "#{host.username}@#{host.hostname}"
41
+ with_sshpass(host, cmd)
42
+ end
43
+
44
+ def scp_command(host, source, destination)
45
+ expanded_src = check_source!(source)
46
+ cmd = ["scp"]
47
+ cmd << "-r" if File.directory?(expanded_src)
48
+ cmd += ["-P", host.port.to_s]
49
+ cmd += ["-i", File.expand_path(host.keyfile)] if host.auth_type == "keyfile"
50
+ cmd += option_args(host)
51
+ cmd << expanded_src
52
+ cmd << "#{host.username}@#{scp_hostname(host.hostname)}:#{destination}"
53
+ with_sshpass(host, cmd)
54
+ end
55
+
56
+ # Returns the expanded source path, raising if it does not exist.
57
+ def check_source!(source)
58
+ expanded = File.expand_path(source)
59
+ raise SourceNotFoundError, "Source path '#{source}' does not exist." unless File.exist?(expanded)
60
+
61
+ expanded
62
+ end
63
+
64
+ # Replaces the current process with ssh so it owns the TTY, signals and exit code.
65
+ def ssh(host, forwards = [])
66
+ Kernel.exec(*ssh_command(host, forwards))
67
+ end
68
+
69
+ def scp(host, source, destination)
70
+ Kernel.system(*scp_command(host, source, destination))
71
+ $?&.exitstatus || 1 # rubocop:disable Style/SpecialGlobalVars
72
+ end
73
+
74
+ def sshpass_available?
75
+ @path.to_s.split(File::PATH_SEPARATOR).any? do |dir|
76
+ candidate = File.join(dir, "sshpass")
77
+ File.file?(candidate) && File.executable?(candidate)
78
+ end
79
+ end
80
+
81
+ private
82
+
83
+ def option_args(host)
84
+ host.ssh_options.flat_map { |option| ["-o", option] }
85
+ end
86
+
87
+ def with_sshpass(host, cmd)
88
+ return cmd unless host.auth_type == "password"
89
+ raise SshpassMissingError, SSHPASS_MISSING unless sshpass_available?
90
+
91
+ ["sshpass", "-p", host.password.to_s] + cmd
92
+ end
93
+
94
+ # scp requires IPv6 literals to be bracketed in user@host:path targets.
95
+ def scp_hostname(hostname)
96
+ hostname.include?(":") && !hostname.start_with?("[") ? "[#{hostname}]" : hostname
97
+ end
98
+ end
99
+ end
data/lib/jmp/tui.rb ADDED
@@ -0,0 +1,180 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tty-prompt"
4
+
5
+ module Jmp
6
+ # Interactive host manager launched by `jmp --config`.
7
+ class TUI
8
+ NEW_LABEL = "<NEW>"
9
+ EXIT_LABEL = "Exit"
10
+ MASKED_PASSWORD = "********"
11
+ AUTH_CHOICES = {
12
+ "SSH Agent / Default" => "agent",
13
+ "Keyfile" => "keyfile",
14
+ "Password" => "password"
15
+ }.freeze
16
+ KEEP_SSH_OPTIONS_QUESTION = "SSH options to keep:"
17
+ ADD_SSH_OPTION_QUESTION = "Add SSH option (e.g. ServerAliveInterval=30, blank to finish):"
18
+
19
+ def initialize(config:, prompt: TTY::Prompt.new)
20
+ @config = config
21
+ @prompt = prompt
22
+ end
23
+
24
+ # Runs the main menu loop. Returns the process exit status.
25
+ def run
26
+ loop do
27
+ choice = @prompt.select("Select a host:", main_menu_choices, cycle: true, per_page: 15)
28
+ case choice
29
+ when :exit then return 0
30
+ when :new then create_host
31
+ else manage_host(choice)
32
+ end
33
+ end
34
+ rescue TTY::Reader::InputInterrupt, Interrupt
35
+ 0
36
+ end
37
+
38
+ # Lists saved aliases and returns the selected host, or nil if cancelled with Ctrl+C.
39
+ def pick_host
40
+ hosts = @config.hosts
41
+ choices = hosts.map { |host| { name: host.alias, value: host.alias } }
42
+ name = @prompt.select("Connect to:", choices, cycle: true, per_page: 15, filter: true)
43
+ hosts.find { |host| host.alias == name }
44
+ rescue TTY::Reader::InputInterrupt, Interrupt
45
+ nil
46
+ end
47
+
48
+ def main_menu_choices
49
+ [{ name: NEW_LABEL, value: :new }] +
50
+ @config.hosts.map { |host| { name: host.label, value: host.alias } } +
51
+ [{ name: EXIT_LABEL, value: :exit }]
52
+ end
53
+
54
+ private
55
+
56
+ def create_host
57
+ host = ask_host_fields(Host.new, taken: @config.hosts.map(&:alias))
58
+ save { @config.add(host) }
59
+ end
60
+
61
+ def manage_host(name)
62
+ host = @config.find(name)
63
+ return @prompt.error("Host '#{name}' no longer exists.") if host.nil?
64
+
65
+ show_details(host)
66
+ case @prompt.select("Action:", %w[Edit Delete Back])
67
+ when "Edit" then edit_host(host)
68
+ when "Delete" then delete_host(host)
69
+ end
70
+ end
71
+
72
+ def edit_host(host)
73
+ original = host.alias
74
+ taken = @config.hosts.map(&:alias) - [original]
75
+ updated = ask_host_fields(Host.from_h(host.to_h), taken: taken)
76
+ save { @config.update(original, updated) }
77
+ end
78
+
79
+ def delete_host(host)
80
+ return unless @prompt.yes?("Delete host '#{host.alias}'?")
81
+
82
+ @config.delete(host.alias)
83
+ @prompt.ok("Deleted host '#{host.alias}'.")
84
+ end
85
+
86
+ def save
87
+ host = yield
88
+ @prompt.ok("Saved host '#{host.alias}'.")
89
+ rescue ValidationError => e
90
+ @prompt.error("Could not save host: #{e.message}")
91
+ end
92
+
93
+ def show_details(host)
94
+ @prompt.say("Alias: #{host.alias}")
95
+ @prompt.say("Hostname: #{host.hostname}")
96
+ @prompt.say("Port: #{host.port}")
97
+ @prompt.say("Username: #{host.username}")
98
+ @prompt.say("Auth: #{host.auth_type}")
99
+ @prompt.say("Keyfile: #{host.keyfile}") if host.keyfile
100
+ @prompt.say("Password: #{MASKED_PASSWORD}") if host.password
101
+ host.ssh_options.each { |option| @prompt.say("Option: #{option}") }
102
+ end
103
+
104
+ # Prompts for every field, using the host's current values as defaults.
105
+ def ask_host_fields(host, taken:)
106
+ host.alias = ask_valid("Alias:", host.alias) { |v| Host.alias_error(v, taken) }
107
+ host.hostname = ask_valid("Hostname:", host.hostname) { |v| Host.hostname_error(v) }
108
+ host.port = Host.coerce_port(ask_valid("Port:", host.port.to_s) { |v| Host.port_error(Host.coerce_port(v)) })
109
+ host.username = ask_valid("Username:", host.username) { |v| Host.username_error(v) }
110
+ ask_credentials(host)
111
+ host.ssh_options = ask_ssh_options(host.ssh_options)
112
+ host
113
+ end
114
+
115
+ def ask_credentials(host)
116
+ host.auth_type = ask_auth_type(host.auth_type)
117
+ host.keyfile = host.auth_type == "keyfile" ? ask_keyfile(host.keyfile) : nil
118
+ host.password = host.auth_type == "password" ? ask_password(host.password) : nil
119
+ end
120
+
121
+ # Lets the user untick existing options, then add new ones one per prompt.
122
+ def ask_ssh_options(current)
123
+ current = current.uniq
124
+ options = []
125
+ unless current.empty?
126
+ options = @prompt.multi_select(KEEP_SSH_OPTIONS_QUESTION, current, default: (1..current.size).to_a)
127
+ end
128
+ loop do
129
+ value = @prompt.ask(ADD_SSH_OPTION_QUESTION).to_s.strip
130
+ return options if value.empty?
131
+
132
+ error = Host.ssh_option_error(value)
133
+ error ? @prompt.error(error) : options << value
134
+ end
135
+ end
136
+
137
+ def ask_valid(question, default)
138
+ loop do
139
+ value = @prompt.ask(question, default: blank?(default) ? nil : default).to_s.strip
140
+ error = yield(value)
141
+ return value if error.nil?
142
+
143
+ @prompt.error(error)
144
+ end
145
+ end
146
+
147
+ def ask_auth_type(current)
148
+ default = AUTH_CHOICES.key(current) || AUTH_CHOICES.keys.first
149
+ @prompt.select("Authentication method:", AUTH_CHOICES, default: default)
150
+ end
151
+
152
+ def ask_keyfile(current)
153
+ path = ask_valid("Keyfile path:", current || default_keyfile) do |v|
154
+ "Keyfile path is required." if v.empty?
155
+ end
156
+ @prompt.warn("Warning: keyfile '#{path}' does not exist locally.") unless File.exist?(File.expand_path(path))
157
+ path
158
+ end
159
+
160
+ def ask_password(current)
161
+ question = current ? "Password (press Enter to keep current):" : "Password:"
162
+ loop do
163
+ value = @prompt.mask(question).to_s
164
+ return value unless value.empty?
165
+ return current if current
166
+
167
+ @prompt.error("Password is required.")
168
+ end
169
+ end
170
+
171
+ def default_keyfile
172
+ ed25519 = "~/.ssh/id_ed25519"
173
+ File.exist?(File.expand_path(ed25519)) ? ed25519 : "~/.ssh/id_rsa"
174
+ end
175
+
176
+ def blank?(value)
177
+ value.nil? || value.to_s.strip.empty?
178
+ end
179
+ end
180
+ end
data/lib/jmp.rb ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Jmp is a command-line SSH connection and SCP file transfer manager.
4
+ module Jmp
5
+ VERSION = "0.1.0"
6
+
7
+ class Error < StandardError; end
8
+ end
9
+
10
+ require_relative "jmp/host"
11
+ require_relative "jmp/config"
12
+ require_relative "jmp/runner"
13
+ require_relative "jmp/tui"
14
+ require_relative "jmp/cli"
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: jmp
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Nitin
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: tty-prompt
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '0.23'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '0.23'
26
+ description: Save SSH host profiles, connect with `jmp <alias>`, copy files with `jmp
27
+ <alias> --copy <src> <dest>`, and manage hosts interactively with `jmp --config`.
28
+ executables:
29
+ - jmp
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - README.md
34
+ - bin/jmp
35
+ - jmp.gemspec
36
+ - lib/jmp.rb
37
+ - lib/jmp/cli.rb
38
+ - lib/jmp/config.rb
39
+ - lib/jmp/host.rb
40
+ - lib/jmp/runner.rb
41
+ - lib/jmp/tui.rb
42
+ licenses:
43
+ - MIT
44
+ metadata:
45
+ rubygems_mfa_required: 'true'
46
+ rdoc_options: []
47
+ require_paths:
48
+ - lib
49
+ required_ruby_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '3.1'
54
+ required_rubygems_version: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: '0'
59
+ requirements: []
60
+ rubygems_version: 3.6.7
61
+ specification_version: 4
62
+ summary: Command-line SSH connection and SCP file transfer manager.
63
+ test_files: []