How to use Net:SSH to upload file from server1 to server2 - ruby

i have 3 web server : local server 0 ; remote server1 ;remote server2
i want to run local ruby script to upload file in server1 to server2;
how to do it? just use ruby.
i have tried shell util such as expect; it worded but how to use it in ruby?
i also tried
ssh =Net::SSH.start(host,username,:password => password) do |ssh|
remote = Net::SSH.start(host,username,:password=>password)
remote.exec!("mkdir -p path")
result = ssh.exec!("scp local_path root#remote_host:remot_path")
puts result
but this way needs to add ssh_key in each remote web server
how to fix it?

Related

create a background ssh tunnel in ruby

My oracle db is only accessable via a jumpoff server and is load balanced. As a result I run the following background tunnel command in bash:
ssh ${jumpoffUser}#${jumpoffIp} -L1521:ont-db01-vip:1521 -L1522:ont-db02-vip:1521 -fN
Before I run my commands on the db using sqlplus like so:
sqlplus #{#sqlUsername}/#{#sqlPassword}#'#{#sqlUrl}' #scripts/populateASDB.sql
This all works fine.
Now I want to rubisize this procedure.
In looking up the documentation on ruby I could not find how to put the tunnel in the background (which would be my preference) but I found documentation on local port forwarding which I thought would emulate the above tunnel and subsequent sqlplus command.
Here is my code:
Net::SSH.start( #jumpoffIp, #jumpoffUser ) do |session|
session.forward.local( 1521, 'ont-db01-vip', 1521 )
session.forward.local( 1522, 'ont-db02-vip', 1521 )
puts "About to populateDB"
res = %x[sqlplus #{#sqlUsername}/#{#sqlPassword}#'#{#sqlUrl}' #scripts/populateASDB.sql > output.txt]
puts "populateDb output #{res}"
session.loop
end
When I run the above I get the line "About to populateDB" but it hangs on the actual running of the sqlplus command. Is there something wrong with my port forwarding code or how do I put the following:
ssh ${jumpoffUser}#${jumpoffIp} -L1521:ont-db01-vip:1521 -L1522:ont-db02-vip:1521 -fN
into ruby code?
A
Try to use this gem: https://github.com/net-ssh/net-ssh-gateway/
require 'net/ssh/gateway'
gateway = Net::SSH::Gateway.new(#jumpoffIp, #jumpoffUser)
gateway.open('ont-db01-vip', 1521, 1521)
gateway.open('ont-db02-vip', 1521, 1521)
res = %x[sqlplus #{#sqlUsername}/#{#sqlPassword}#'#{#sqlUrl}' #scripts/populateASDB.sql > output.txt]
puts "populateDb output #{res}"
gateway.shutdown!
You have two problems.
1) You need to use 'session.loop { true }' so that the session actually loops
2) You don't start looping the session until your sqlplus command is done, but the sqlplus needs the session looping (the forwarding to be up).
So I suggest creating a background thread using Thread.new and then killing the thread once sqlplus is done.
Thanks to David's answer, I came up with the following:
Net::SSH.start(ip_addr, 'user') do |session|
session.forward.local( 9090, 'localhost', 9090 )
# Need to run the event loop in the background for SSH callbacks to work
t = Thread.new {
session.loop { true }
}
commands.each do | command |
command.call(9090)
end
Thread.kill(t)
end

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

How to mock a 3rd-party library [duplicate]

an important part of my project is to log in into remote server with ssh and do something with files on it:
Net::SSH.start(#host, #username, :password => #password) do |ssh|
ssh.exec!(rename_files_on_remote_server)
end
How to test it?
I think I can have local ssh server on and check file names on it (maybe it could be in my test/spec directory).
Or maybe someone could point me better solution?
I think it's enough to test that you're sending the correct commands to the ssh server. You're application presumably doesn't implement the server - so you have to trust that the server is correctly working and tested.
If you do implement the server then you'd need to test that, but as far as the SSH stuff goes, i'd do some mocking like this (RSpec 2 syntax):
describe "SSH Access" do
let (:ssh_connection) { mock("SSH Connection") }
before (:each) do
Net::SSH.stub(:start) { ssh_connection }
end
it "should send rename commands to the connection" do
ssh_connection.should_receive(:exec!).ordered.with("expected command")
ssh_connection.should_receive(:exec!).ordered.with("next expected command")
SSHAccessClass.rename_files!
end
end
Your suggested solution is similar to how I've done it before:
Log into the local machine. For convenience you could use 'localhost' or '127.0.0.1', but for a better simulation of network activity you might want to use the full hostname. On Mac OS and Linux you can grab the host easily by using:
`hostname`
or
require 'socket'
hostname = Socket.gethostname
which should be universal.
From there create or touch a file on the local machine after logging in, so you can test for the change with your test code.

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.

Testing ssh connection

an important part of my project is to log in into remote server with ssh and do something with files on it:
Net::SSH.start(#host, #username, :password => #password) do |ssh|
ssh.exec!(rename_files_on_remote_server)
end
How to test it?
I think I can have local ssh server on and check file names on it (maybe it could be in my test/spec directory).
Or maybe someone could point me better solution?
I think it's enough to test that you're sending the correct commands to the ssh server. You're application presumably doesn't implement the server - so you have to trust that the server is correctly working and tested.
If you do implement the server then you'd need to test that, but as far as the SSH stuff goes, i'd do some mocking like this (RSpec 2 syntax):
describe "SSH Access" do
let (:ssh_connection) { mock("SSH Connection") }
before (:each) do
Net::SSH.stub(:start) { ssh_connection }
end
it "should send rename commands to the connection" do
ssh_connection.should_receive(:exec!).ordered.with("expected command")
ssh_connection.should_receive(:exec!).ordered.with("next expected command")
SSHAccessClass.rename_files!
end
end
Your suggested solution is similar to how I've done it before:
Log into the local machine. For convenience you could use 'localhost' or '127.0.0.1', but for a better simulation of network activity you might want to use the full hostname. On Mac OS and Linux you can grab the host easily by using:
`hostname`
or
require 'socket'
hostname = Socket.gethostname
which should be universal.
From there create or touch a file on the local machine after logging in, so you can test for the change with your test code.

Resources