简体   繁体   English

通过ssh execute设置的丢失环境变量。 Ruby和Net-ssh

[英]Losing environment variable set via ssh execute. Ruby & net-ssh

I would like to set Linux environment variables in net-ssh start and use them further down in my code. 我想在net-ssh start中设置Linux环境变量,并在我的代码中进一步使用它们。 But I am losing the scope of the variables. 但是我正在失去变量的范围。 Can you please advise how that can be achieved. 您能建议如何实现吗?

I am using net-ssh and logging into Linux via rsa key. 我正在使用net-ssh并通过rsa密钥登录Linux。 I have set a environment variable which I would like to use further down but I am losing the scope of the variable. 我设置了一个环境变量,我想进一步使用它,但是我失去了该变量的范围。

ssh = Net::SSH.start(host,
                     username
)
result = ssh.exec!('setenv SYBASE /opt/sybase && printenv') ### Can See environment variable SYBASE
puts result
puts "**********************************************************************************"
result = ssh.exec!('printenv')   #### Lost the environment variable SYBASE set above
puts result
puts "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"

Each exec creates an environment on it's own, environmont variables are lost. 每个执行人员都自己创建一个环境,environmont变量将丢失。 Like you do with your && (execute next command if first succeeds) or with ; 就像使用&& (如果第一次成功执行下一个命令)或使用; (execute anyway) you can chain commands. (仍然执行),您可以链接命令。

You can also send a block like this to do multiple actions 您也可以发送这样的代码块来执行多项操作

Net::SSH.start("host", "user") do |ssh|
  ssh.exec! "cp /some/file /another/location"
  hostname = ssh.exec!("hostname")
  ssh.open_channel do |ch|
    ch.exec "sudo -p 'sudo password: ' ls" do |ch, success|
      abort "could not execute sudo ls" unless success

      ch.on_data do |ch, data|
        print data
        if data =~ /sudo password: /
          ch.send_data("password\n")
        end
      end
    end
  end

  ssh.loop
end

Or use the gem net-ssh-session . 或使用gem net-ssh-session

@peter thank you for suggesting net-ssh-session. @peter感谢您建议net-ssh-session。 However net-ssh-session needed recompile to make it compatible with net-ssh 5.2.0 version. 但是,net-ssh-session需要重新编译以使其与net-ssh 5.2.0版本兼容。 Example here works great and is what needed for me. 这里的例子很好用,这正是我所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM