0

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?

onebree
  • 1,853
  • 1
  • 17
  • 44
itsh
  • 1,063
  • 3
  • 14
  • 28
  • 1
    As an aside, `"#{hostname}"` shouldn't be there. Either use `hostname.to_s` to convert to a string, or drop the string conversion entirely, because `hostname` should be a string already. Same for `user` and `password`. – user229044 Nov 12 '14 at 14:42
  • what is the difference in results? – ptierno Nov 12 '14 at 14:43
  • 5
    your not setting `@cmd` anywhere in `initialize` – ptierno Nov 12 '14 at 14:44
  • Thank you for the quick replies. Setting up `@cmd` in `initialize` block fixed the problem. – itsh Nov 12 '14 at 14:52
  • 1
    Please link to the answer. There is no submitted answer for this question. Right now, it is not viewed as "answered" because there are no submitted answers through it. (Comments do not count as answers.) Please Enter your answer, with an explanation, in "Your Answer" and click "Post your answer" – onebree Aug 14 '15 at 15:33

1 Answers1

1

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
Community
  • 1
  • 1
itsh
  • 1,063
  • 3
  • 14
  • 28