Using the Net-SSH Ruby gem.
The net-ssh gem can be used by to programmatically SSH into machines. This might be useful of the user has to set up a cronjob that will SSH into a certain host once a day to copy over a file. The net-ssh gem can also be used to create reverse tunnels or forward tunnels.
The gem can be installed by running the following command.
gem install net-sshNote that you might need sudo privileges. net-ssh is a Pure Ruby implementation of an SSH client.
After the net-ssh gem is install, create a new file and put require 'net/ssh' on the first line. This allows us to use the code from that gem.
First we have to call Net::SSH.start and give it information about the SSH server we want to connect to. The start method needs a IP, a username, password and port. The second set of commands shows how to login to the SSH server with a key. To use an key the user must give the program the path of their public key.
After logging the gem allows the user to run commands on the remote server or computer.
Forwarding connections
The gem can be used to forward connections to another IP. It can be be used to forward ports so that the port can be accessible remotely.
Get Michael Meade’s stories in your inbox
Join Medium for free to get updates from this writer.
The IP 127.0.0.1 has to connect to port 1234 so that it can access the remote port. The listening port on the remote server is port 18080.
The code above allows the user to create a SSH client with PTY shell. PTY shell is a pseudotty, which means it acts like a terminal to the process reading and writing, but is managed by something else.
Reverse SSH Tunnel
The script above will connect to the IP, 190.8.90.80 on port 3389. The user running the script can connect to the service on localhost & port 3333.
SCP with net-scp
SCP is a handy command that allows it’s user to use SSH to securely transfer files from a machine to a different machine. Unlike FTP, SCP traffic is encrypted so the user does not have to worry about the file being intercepted by a third party.
To install the net-scp gem run the following command on your system.
gem install net-scpSCP is a protocol that uses SSH to securely copy files from one host to another over a secured connections. Protocols like FTP does not encrypt the connection. This is dangerous because an threat actor could sniff the traffic and get the login information for the FTP server. Also it could allow threat actors to intercept the file and download a copy. SCP uses SSH so everything is encrypted.
The code above could be used to download the Apache2 log file and copy the file over to your local computer.








