Created
September 23, 2022 20:11
-
-
Save jcreed/ad491df62732c536e8efeb45dbd8b44d to your computer and use it in GitHub Desktop.
sftp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/sftp' | |
require 'uri' | |
class SftpUploader | |
attr_reader :host, :username, :password, :ssh_private_key, :port, :auth_type, :root_path | |
def initialize(host, user, auth_type, port, password: nil, ssh_private_key: nil, root_path) | |
@host = host | |
@user = user | |
@port = port | |
@password = password | |
@auth_type = auth_type | |
@ssh_private_key = ssh_private_key | |
@root_path = root_path | |
end | |
def connect | |
sftp_client.connect! && root_path_valid? | |
rescue => error | |
Airbrake.notify(error, error_message: 'Could not connect Host') | |
false | |
end | |
def disconnect | |
sftp_client.close_channel | |
ssh_session.close | |
end | |
def upload(local_file_path, remote_file_path) | |
sftp_client.upload!(local_file_path, remote_file_path) do |event, uploader, *args| | |
send("#{event}_event", uploader, *args) if respond_to?(event, true) | |
end | |
end | |
def sftp_client | |
@sftp_client ||= Net::SFTP::Session.new(ssh_session) | |
end | |
private | |
def root_path_valid? | |
begin | |
sftp_client.opendir!(@root_path) do |response| | |
end | |
true | |
rescue Net::SFTP::StatusException | |
false | |
end | |
end | |
def ssh_session | |
@ssh_session ||= if @auth_type == 'password' | |
Net::SSH.start(@host, @user, port: @port, password: @password, timeout: 5, non_interactive: true) | |
else | |
key_data = @ssh_private_key.gsub("\r\n","\n") | |
Net::SSH.start(@host, @user, port: @port, passphrase: @password, key_data: [key_data], timeout: 5, non_interactive: true) | |
end | |
end | |
def open_event(uploader, *args) | |
Rails.logger.info('Starting upload...') | |
end | |
def close_event(uploader, *args) | |
Rails.logger.info('Upload complete') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment