Ubuntu 16.04.7 LTS (Xenial Xerus) ruby 2.5.0p0
After transferring the Ruby program to the server specified by port forward, execute the Ruby program on the transfer destination server and output the csv file as standard output. Then, bring the standard output csv file to your local environment.
def ssh_connect
begin
#Transfer files
_cmd = system('scp -P 54322 -i /home/.ssh/id_rsa /home/syori.rb [email protected]:/home')
#Port forwarding settings
Net::SSH.start(
'153.153.xx.xx',
'username',
:keys => '/home/.ssh/id_rsa',
:port => 54322
) do |_a|
_a.forward.local(2222,'192.168.xx.xx', 54323)
_a.exec!('ruby syori.rb')
end
#Get the file
_cmd = system('scp -P 54322 -i /home/.ssh/id_rsa [email protected]:/home/users.csv /home')
rescue => ex
print "***** " + self.class.name.to_s + "." + __method__.to_s + " *****\n"
print(ex.class," -> ",ex.message)
end
end
system A method that issues Linux commands in Ruby. The return value is ture / false.
scp This is a command (protocol) for transferring files. When it comes to file transfer, I think that ftp was often used in the past, but since ftp cannot encrypt account information when logging in, use scp, which is equipped with an SSH function as standard, to improve security. Is the basis.
-P Specify the port number. The SSH port number 22 is specified as the well-known port number, but if it is a server that is open to the outside, I think that it may be customized to prevent strange attacks. Specify the SSH port number of the server to connect to.
-i Set the path that stores the public key used for SSH communication as an absolute path. Mostly located in your home .ssh.
Set the file name to be transferred with an absolute path. To specify the transfer destination, specify the server name of the transfer destination: the directory of the transfer destination with an absolute path.
Net::SSH.start(
Forward source IP address,
Username of the forward source,
:keys =>Absolute path of private key of connection source,
:port =>Connection source port number
) do |_a|
_a.forward.local(Forward source port number (anything is fine),
'IP address of port forwarding destination',
Forward destination port number)
_a.exec!('The command you want to execute at the connection destination')
end
Recommended Posts