Using Net::SSH in an `initialize` block does not work

161 views Asked by At

I want to connect to a remote server and run some commands there. For that I am writing the following Ruby script and it works fine.

@hostname = "SERVER_NAME"
@username = "user"
@password = "pass"
@cmd = "ls -alt"

begin
  @ssh = Net::SSH.start(@hostname, @username, :password => @password)
  puts "#{@ssh}"
  res = @ssh.exec!(@cmd)
  @ssh.close
  puts res
rescue
  puts "Unable to connect to #{@hostname} using #{@username}/#{@password}"
end

But when I try to put the same code in an initialize block it is not working. Below is the code for that:

def initialize(hostname, user, password)
  @hostname = "#{hostname}"
  @username = "#{user}"
  @password = "#{password}"

  begin
    puts "entered begin"
    @ssh = Net::SSH.start(@hostname, @username, :password => @password)
    puts "#{@ssh}"
    res = @ssh.exec!(@cmd)
    puts "#{res}"
    # @ssh.close
    puts res
  rescue => e
    puts e
    puts "#{@ssh} Unable to connect to #{@hostname} using #{@username}/#{@password}"
  end
end

Printing @ssh gives different results in first and second chunk of code.

Can some one help me in figuring out what's going wrong?

1

There are 1 answers

0
itsh On

Problem was that I did not initialize @cmd in initialize block. That is why it was not working as expected. I fixed it as recommended by @ptierno. Below is the working code:

def initialize(hostname, user, password)
  @hostname = "#{hostname}"
  @username = "#{user}"
  @password = "#{password}"
  @cmd = "ls -alt"

  begin
    puts "entered begin"
    @ssh = Net::SSH.start(@hostname, @username, :password => @password)
    puts "#{@ssh}"
    res = @ssh.exec!(@cmd)
    puts "#{res}"
    # @ssh.close
    puts res
  rescue => e
    puts e
    puts "#{@ssh} Unable to connect to #{@hostname} using #{@username}/#{@password}"
  end
end