Sha256: 06b46d12f81ecc3605667322a67cf86511891e018b3702b749bd6b04cda00d65

Contents?: true

Size: 1.43 KB

Versions: 16

Compression:

Stored size: 1.43 KB

Contents

require 'fileutils'
module LinuxAdmin
  class SSHAgent
    attr_accessor :pid
    attr_reader :socket

    def initialize(ssh_private_key, agent_socket = nil)
      @socket = agent_socket
      @private_key = ssh_private_key
    end

    def start
      if @socket
        FileUtils.mkdir_p(File.dirname(@socket))
        agent_details = `ssh-agent -a #{@socket}`
      else
        agent_details = `ssh-agent`
        @socket = parse_ssh_agent_socket(agent_details)
      end
      @pid = parse_ssh_agent_pid(agent_details)
      IO.popen({'SSH_AUTH_SOCK' => @socket, 'SSH_AGENT_PID' => @pid}, ['ssh-add', '-'], :mode => 'w') do |f|
        f.puts(@private_key)
      end
      raise StandardError, "Couldn't add key to agent" if $CHILD_STATUS.to_i != 0
    end

    def with_service
      start
      yield @socket
    ensure
      stop
    end

    def stop
      system({'SSH_AGENT_PID' => @pid}, '(ssh-agent -k) &> /dev/null') if process_exists?(@pid)
      File.delete(@socket) if File.exist?(@socket)
      @socket = nil
      @pid = nil
    end

    private

    def process_exists?(process_pid)
      Process.kill(0, process_pid) == 1
    rescue
      false
    end

    def parse_ssh_agent_socket(output)
      parse_ssh_agent_output(output, 1)
    end

    def parse_ssh_agent_pid(output)
      parse_ssh_agent_output(output, 2)
    end

    def parse_ssh_agent_output(output, index)
      output.split('=')[index].split(' ')[0].chop
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
linux_admin-2.0.2 lib/linux_admin/ssh_agent.rb
linux_admin-2.0.1 lib/linux_admin/ssh_agent.rb
linux_admin-2.0.0 lib/linux_admin/ssh_agent.rb
linux_admin-1.2.4 lib/linux_admin/ssh_agent.rb
linux_admin-1.2.3 lib/linux_admin/ssh_agent.rb
linux_admin-1.2.2 lib/linux_admin/ssh_agent.rb
linux_admin-1.2.1 lib/linux_admin/ssh_agent.rb
linux_admin-1.0.1 lib/linux_admin/ssh_agent.rb
linux_admin-1.2.0 lib/linux_admin/ssh_agent.rb
linux_admin-1.1.0 lib/linux_admin/ssh_agent.rb
linux_admin-1.0.0 lib/linux_admin/ssh_agent.rb
linux_admin-0.20.2 lib/linux_admin/ssh_agent.rb
linux_admin-0.20.1 lib/linux_admin/ssh_agent.rb
linux_admin-0.20.0 lib/linux_admin/ssh_agent.rb
linux_admin-0.19.0 lib/linux_admin/ssh_agent.rb
linux_admin-0.18.0 lib/linux_admin/ssh_agent.rb