[英]Ruby Net::SSH reuse session
I have a few methods doing this: 我有几种方法可以做到这一点:
def method_a
Net::SSH.start(...) do |ssh|
end
end
def method_b
Net::SSH.start(...) do |ssh|
end
end
def method_c
Net::SSH.start(...) do |ssh|
end
end
Each methods call Net::SSH start which are individual SSH sessions, doing different things. 每个方法都调用Net :: SSH start,它们是单独的SSH会话,它们执行不同的操作。
Is there a way to reuse Net::SSH session so that all 3 methods utilize a single session? 有没有一种方法可以重用Net :: SSH会话,以便所有3种方法都利用一个会话?
THanks. 谢谢。
Yes, definitely you can make it DRY. 是的,绝对可以使其干燥。
You can add one method which accept hostname for the Net::SSH connection as below: 您可以添加一种接受Net :: SSH连接的主机名的方法,如下所示:
def ssh_exec(hostname)
Net::SSH.start( hostname, 'user', :timeout => 5, :paranoid => false ) do |ssh|
....
end
end
Then you can call this method ssh_exec()
with proper hostname wherever you need it... 然后,您可以在需要的地方使用适当的主机名调用此方法
ssh_exec()
。
The way to go in Net::SSH is to put 进入Net :: SSH的方法是放入
@ssh_session = Net::SSH.start( @host, nil, option={:config => true})
to a variable and then on each methods 到一个变量,然后在每种方法上
def method_a
@ssh_session.exec!("Hello a")
end
def method_b
@ssh_session.exec!("Hello b")
end
def method_c
@ssh_session.exec!("Hello c")
end
And of course i place all the above in a class, so that I can initialize and start a ssh session and exec commands without re-establishing SSH. 当然,我将以上所有内容都放在了一个类中,这样我就可以初始化并启动ssh会话和exec命令,而无需重新建立SSH。
Outside a class, you can try: 在课外,您可以尝试:
def call
Net::SSH.start(...) do |ssh|
method_a(ssh)
method_b(ssh)
method_c(ssh)
end
end
def method_a(ssh)
ssh.exec(...)
end
def method_b(ssh)
ssh.exec(...)
end
def method_c(ssh)
ssh.exec(...)
end
If it's in a class, you can define `attr_reader :ssh` and then initialize it thus:
def method_a
ssh.exec(...)
end
With that, you can simply define 这样,您可以简单地定义
def method_a ssh.exec(...) end
Same applies for other methods. 其他方法也一样。 I hope this helps?
我希望这有帮助?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.