Ruby Net::SSH Change directories using variable in

2019-07-06 03:22发布

I am fairly new to Ruby, so please forgive me if I am missing something obvious.

The problem is that Ruby doesn't seem to be doing variable interpolation in the Net::SSH.exec! method.

VCL_DIR = "/usr/local/etc/varnish/"
host = '0.0.0.0'
Net::SSH.start(host, 'root') do |ssh|
  puts "Changing directories to #{VCL_DIR}"
  ssh.exec!("cd #{VCL_DIR}")
  res = ssh.exec!("pwd")
  puts "Server reports current directory as #{res}"
end

Output:

Changing directories to /usr/local/etc/varnish/
Server reports current directory as /root

Any help is appreciated. Using Ruby 1.9.3p194

标签: ruby ssh exec
2条回答
放荡不羁爱自由
2楼-- · 2019-07-06 03:40

The problem is that Net::SSH uses a different shell for each exec call. The solution is to use stateful shell. There is a gem to do this, but it is outdated. Net::SSH::Shell via https://github.com/mitchellh/net-ssh-shell

I chose to use Rye to handle this task. http://code.google.com/p/rye/

查看更多
老娘就宠你
3楼-- · 2019-07-06 03:51

Net::SSH.start( "10.2.10.1", "botp:)", :password=>"secret=)") do |session| puts session.exec! "ls -la; cd /etc; ls -la" end

Reference: https://www.ruby-forum.com/topic/160890

Please note: you have to "cd" per each .exec! command ran.
Something like below, will show you that using cd in one exec! command does not change the location for the next exec command.

Net::SSH.start( "10.2.10.1", "botp:)", :password=>"secret=)") do |session| puts session.exec!("ls -la; cd /etc; ls -la") puts session.exec!("ls -la") end

查看更多
登录 后发表回答