Net::SSH.exec Using the "exec" method interactively

G

Guillermo Riojas

Hi there,

Recently i started playing with the Net::SSH gem. So far, good, but i
just came across i question i haven't been able to respond.

My intention is to issue several commands using the same channel in
order to be able to give continuity to my list of instructions, making
it somehow "interactive". So far, after the first command is typed and
the output returned, the rest of the instructions seem to be "not
executed". As i am pretty new to the gem and SSH in general, i realized
that somehow once the channel is closed the session too and of course,
opening a new channel puts me back in the starting point.

So if i would like to create folder, navigate to the folder i just
created , do some other stuff there and then exit, wont work as i
expect, because every command sent starts in a new session.

A sample of the code here:

def exec_cmd
cont = true

channel = @ssh.open_channel do |chn|
while cont
print "cmd> "; STDOUT.flush; str = gets.chop #User input command
cont = false if str.empty?
channel_execute chn, str.to_s
end
end #channel open loop

channel.wait
end

def channel_execute(chn, cmd = nil)
return nil if cmd.nil?
puts "Executing Command [#{cmd}]"

chn.exec(cmd.to_s) do |ch,success|
raise "Could not execute command" unless success

ch.on_data do |c, data|
out = data.split("\n")
out.each do |e|
puts "#{e}"
end
end

ch.on_extended_data do |c, type, data|
out = data.split("\n")
out.each do |e|
puts "#{e}"
end
end

ch.on_close { @log.debug("exec") {"Command loop finished."} }

end #chn exec loop

chn.wait

end


Now, my first work around is sending once the list of all the commands,
in this way "mkdir testfolder; cd testfolder; mkdir testfolder2; cd /;
..."

However, is there any way i can keep the channel "open" in order to be
able to send each and every command separately?

Any hint is greatly appreaciated.

guillermo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top