有没有办法使用net-ssh在ruby中获得一个登录shell?这有可能吗?
我所说的登录shell指的是源/etc/profile..
发布于 2011-03-18 03:43:35
Net-SSH的级别太低,不能简单地预先提供它(不管怎么说,它现在的方式)。您可以查看Net-SSH-Shell,它构建在Net-SSH的基础上,以添加登录shell功能:https://github.com/mitchellh/net-ssh-shell
这个实现是可靠的,可以工作,但是我发现它不是很有用,因为您不能专门提取stderr或exit status之类的内容,因为这些命令在子shell中运行,所以您只能获取stdout。net-ssh-shell库使用一些hack来获取退出状态。
我自己的Ruby项目需要一个“登录shell”,为此,我通常使用以下代码直接在shell中执行操作:
def execute_in_shell!(commands, shell="bash")
channel = session.open_channel do |ch|
ch.exec("#{shell} -l") do |ch2, success|
# Set the terminal type
ch2.send_data "export TERM=vt100\n"
# Output each command as if they were entered on the command line
[commands].flatten.each do |command|
ch2.send_data "#{command}\n"
end
# Remember to exit or we'll hang!
ch2.send_data "exit\n"
# Configure to listen to ch2 data so you can grab stdout
end
end
# Wait for everything to complete
channel.wait
end使用这种解决方案,您仍然不会获得运行到登录shell中的命令的退出状态或stderr,但至少这些命令是在该上下文中执行的。
我希望这能帮到你。
发布于 2018-05-06 22:20:18
现在有一种更好的方法可以做到这一点。相反,您可以使用带有pty的shell子系统来获得您希望从shell登录中获得的一切:
Net::SSH.start(@config.host, @config.user, :port => @config.port, :keys => @config.key, :config => true) do |session|
session.open_channel do |channel|
channel.request_pty
channel.send_channel_request "shell" do |ch, success|
if success
ch.send_data "env\n"
ch.send_data "#{command}\n"
ch.on_data do |c, data|
puts data
end
end
channel.send_data "exit\n"
channel.on_close do
puts "shell closed"
end
end
end
end结束
https://stackoverflow.com/questions/5051782
复制相似问题