I found this snippet of code I am having trouble trying to find a good way to exit the tail and move on to the next part of the script. Essentially I ant the first part to make a change for the person running the scripts, show log output using the below code, then move on to the next part of the script on user keypress. I cant get out of the tail without CTRL-C.
def do_tail( session, file )
session.open_channel do |channel|
channel.on_data do |ch, data|
puts "[#{file}] -> #{data}"
end
channel.exec "tail -f #{file}"
end
end
Net::SSH.start("server", "user", :keys => ["/user/.ssh/id_dsa"]) do |session|
do_tail session, "/var/log/apache2/error.log"
do_tail session, "/var/log/apache2/access.log"
session.loop
end
UPDATE
The -f takes over I/O and makes it difficult to exit that ssh channel. I decided to move towards the suggestions and modify it. Here is the result in case someone else would like help on this topic.
require 'rubygems'
require 'net/ssh'
def exit?
begin
while input = STDIN.read_nonblock(1)
return true if input == 'q'
end
false
rescue Errno::EINTR
false
rescue Errno::EAGAIN
false
rescue EOFError
true
end
end
def do_tail( session, file )
session.open_channel do |channel|
channel.on_data do |ch, data|
puts "[#{file}]\n\n#{data}"
end
channel.exec "tail -n22 #{file}"
end
end
def loggy
iteration = 0
loop do
iteration = (iteration + 1)
Net::SSH.start("server", "user", :keys => ["/user/.ssh/id_dsa"]) do |session|
do_tail session, "/var/log/apache2/error.log"
end
puts "\n\nType 'q' and <ENTER> to exit log stream when you are done!\n\n"
sleep 5
break if exit? or iteration == 3
end
end
loggy
loop do
puts "\nDo you need to view more of the log? (y/n)\n"
confirm = gets.chomp
if confirm =="y"
loggy
else
end
break if confirm == "n"
end
puts "Part Deaux!"
You’ve given the
-fcommand line option totail(1). That explicitly instructstail(1)to exit when the user types^Cor otherwise kills the program. If you just want a specific amount of the file to be shown and not followed, then you might wish to use the-ncommand line option instead:24will show roughly one terminal’s worth of data, though if your terminals are larger or smaller — or you’re interested in different amounts of data — then you might wish to tweak it further.tail(1)is powerful; it’d be worth reading its documentation just in case there’s an even better way to do what you’re trying to accomplish.