I've been fooling around with Ruby lately, so i decided to write an sftp client.
require 'net/sftp'
require 'ostruct'
require 'optparse'
class Sftp
def parse(arguments)
ARGV << "-h" if ARGV.empty?
@options = OpenStruct.new
args = OptionParser.new do |args|
args.banner = "Usage: #{__FILE__} [options]"
args.on("--host HOST", String,
) do |host|
@options.host = host
end
args.on("--username USERNAME", String,
) do |username|
@options.username = username
end
args.on("--password PASSWORD", String,
) do |password|
@options.password = password
end
args.on("--port=PORT", Integer,
) do |port|
@options.port = port
end
args.on("--mkdir=MAKE DIRECTORY", String,
) do |mkdir|
@options.mkdir = mkdir
end
args.on("--rmdir=REMOVE DIRECTORY", String,
) do |rmdir|
@options.rmdir = rmdir
end
args.on("-h", "--help", "Show help and exit") do
puts args
exit
end
end
begin
args.parse!(arguments)
rescue OptionParser::MissingArgument => error
puts "[!] ".red + error.message.bold
exit
rescue OptionParser::InvalidOption => error
puts "[!] ".red + error.message.bold
exit
end
def connect
Net::SFTP.start(@options.host, @options.username, :password => @options.password, :port => @options.port) do |sftp|
sftp.mkdir(@options.mkdir)
puts "Creating Directory: #{@options.mkdir}"
sftp.rmdir(@options.rmdir)
puts "Deleting Directory: #{@options.rmdir}"
end
end
end
def run(arguments)
parse(arguments)
connect
end
end
sftp = Sftp.new
sftp.run(ARGV)
I want these two commands to be separated. For example when i pass the argument mkdir I just want only this to run and if I want to run rmdir again I just wanna run only this command.
It has to do with methods, but I can't find a proper solution. And I'm really rusty. Any recommendation?
A very simple approach could be to check if the required value is set before running the command, and skip the command if the value is not set.
def connect
Net::SFTP.start(@options.host, @options.username, password: @options.password, port: @options.port) do |sftp|
if @options.mkdir
sftp.mkdir(@options.mkdir)
puts "Creating Directory: #{@options.mkdir}"
end
if @options.rmdir
sftp.rmdir(@options.rmdir)
puts "Deleting Directory: #{@options.rmdir}"
end
end
end