How to get list of file names from a private remote ip - ruby

I am having access to ServerA and don't have access to ServerB.I want to get the list of file names from ServerB via serverA.
I am logging into ServerA using the following command and doing some functions.
Net::SSH.start(url, user, forward_agent: true) do |ssh|
ssh.exec('scp -r source dest')
end
But i want to get the list the file names from ServerB via ServerA. How can i do it ?
Eg: Dir["/path/*.txt"] or ls *.txt
OS: Linux
Language: ruby

You can use ssh to execute a remote command:
ssh username#hostname ls -l /foo/bar
If the ls command is not enough you can always use find or any other command.
EDIT
Here you have a full working script
require 'net/ssh'
Net::SSH.start('localhost', 'user', :password => "password") do |ssh|
stdout = ''
ssh.exec!("ls -l /tmp") do |channel, stream, data|
stdout << data if stream == :stdout
end
puts stdout
end
working with ruby 2.1.2p95
Also make sure you have ruby compiled with OpenSSL:
ruby -ropenssl -e 'puts OpenSSL::OPENSSL_VERSION'
EDIT 2
What you need is a tunnel, for more information check the official documentation.
require 'net/ssh/gateway'
gateway = Net::SSH::Gateway.new('host', 'user')
gateway.ssh("host.private", "user") do |ssh|
puts ssh.exec!("hostname")
end
gateway.open("host.private", 80) do |port|
Net::HTTP.get_print("127.0.0.1", "/path", port)
end
gateway.shutdown!

Related

copy contents of a remote location to a local file in ruby script

I want to copy the contents of a remote location file to some local file after an ssh connection has been made.
begin
ssh = Net::SSH.start("localhost", "user")
logger.info "conn successful!"
results = conn.exec!('ruby somefile "#{arguments}"')
#code to copy the contents of a.txt in remote location to local file
#IO.copy_stream (localfile, remotefile)
rescue
logger.info "error - cannot connect to host"
end
I tried using IO.copy_stream but that doesn't work. How do I go about this?
Use Net::SCP (which requires Net::SSH) to transfer files:
Net::SCP.download!("remote.host.com", "username",
"/remote/path", "/local/path",
:password => password)
More info here: https://rubygems.org/gems/net-scp

Why does serverspec connect to the localhost instead of the remote host

My serverspec example, setup using serverspec-init, then I generated this simple test file ./spec/altspf01/sample_spec.rb
require 'spec_helper'
describe command( '/bin/hostname -s' ) do
its(:stdout) { should match /atlspf01/ }
end
I expect it to ssh to a remote host (atlspf01) and check its hostname (atlspf01). Instead it connects to the localhost (ltipc682).
1) Command "/bin/hostname -s" stdout should match /atlspf01/
Failure/Error: its(:stdout) { should match /atlspf01/ }
expected "ltipc682\n" to match /atlspf01/
Diff:
## -1,2 +1,2 ##
-/atlspf01/
+ltipc682
What have I done wrong?
All code here: https://gist.github.com/neilhwatson/a3f4a26ad8cf27d62307
Serverspec's specs should be run via rake. Otherwise, the spec doesn't know the target host.
However, if you wish to run it via rspec, you could use this workaround:
env TARGET_HOST='atlspf01' rspec spec/atlspf01/sample_spec.rb
Hope this helps.

Ruby - checking ping status featback with ssh, backtick via ssh?

In my project I want to write a script to check if every device in my network is online/reachable. I have a method called pingtest and it works for now..
def pingtest(destination)
system("ping -n 2 #{destination}")
if $? == 0 #checking status of the backtick
puts "\n Ping was successful!"
else
close("Device is unreachable. Check the config.txt for the correct IPs.")
#close() is just print & exit..
end
end
Now I wanted to ping via a ssh session with an other device in my network:
#--------------------------------
require 'net/ssh'
Net::SSH.start(#ip, #user, :password => #password)
#--------------------------------
#ssh = Ssh.new(#config)
#ssh.cmd("ping -c 3 #{#IP}")
The ping works fine but how can I use my backtrack idea now to determine if it was succesful or not?
I thought about using a sftp connection..
"ping -c 3 #{#IP} => tmpfile.txt" => download => check/compare => delete
(or something like that) to check if it was correct, but im not statusfied with that. Is there a possibility to check the success status like I did before?
I also tried something like this..
result = #ssh.cmd("ping -c 3 #{#IP}")
if result.success? == 0 # and so on..
I startet learning ruby some days ago, so im a newbie looking forward for your ideas to help me with this problem.
You can use Net::SSH to run the command remotely, similarly to what you've already got there.
The result returned from running the command will be whatever is written to both stdout and stderr.
You can use the contents of that returned value to check if it was successful or not.
Net::SSH.start(#ip, #user. password: #password) do |ssh|
response = ssh.exec! "ping -c 3 #{#other_ip}"
if response.include? 'Destination Host Unreachable'
close("Host unreachable. Result was: #{result}")
else
puts "\n Ping was successful"
end
end

Net::SSH does not seem to connect to remote host

Following the syntax from http://net-ssh.github.io/net-ssh/
Net::SSH.start('remotehost', 'ava') do |ssh|
puts `hostname`
end
It prints the name of current hostname rather than remote hostname. What is wrong?
You should use as below :
Net::SSH.start('remotehost', 'ava') do |ssh|
puts ssh.host
end
As ssh is an instance of Net::SSH::Connection::Session class And if you browse the documentation,you will get the method #host,which will give you the desired result.

Unable to connect remote host through net/ssh

This is pretty weird. I have my public key added at host machine. I can simply run
ssh -p <port> -l <username> hostt.com
which simply opens the remote shell. I can even run my capistrano scripts for the deployments on the same machine. But when i was trying connect with this following simple ruby script
require 'rubygems'
require 'net/ssh'
Net::SSH.start("hostt.com",
:port => <port>,
:username => <username>
) do |session|
puts session.pwd
end
it refuses immediately with the following exception:
`initialize': Connection refused - connect(2) (Errno::ECONNREFUSED)
Is there anything I'm missing here?
Appreciate your help.
Okay, now after a few days when I look back to the problem, I got a quick success with the following tweak:
Net::SSH.start("<host>", "<user>", :port => "<port>") { |ssh|
puts "logged in"
puts ssh.exec!("ls -l")
} rescue puts "failed to connect."
So the difference with the previous one is the username, which in this case is passed as the second argument rather than like an option key.
you probably need to provide the location of your SSH key, or a password to use with the username you provide in the SSH.start parameters. for the keys, you need to pass the map value as an array :keys => ["path_to_key"]. I'm not sure why the api is set up that way, but it is.

Resources