Sunday, October 16, 2016

Creating tunnels over ssh - Connecting to remote machine ports over internet

Sometimes when I am working from home, I need my application, which generates data, to be able to send it(data) from my laptop to some machine in the office. For eg. Parsing XML files and storing it to a DB on the office LAN, or talking to web-service deployed in our staging environment, etc.

You can use a VPN to connect to your office LAN. Or you can use this simple tunneling solution that comes with ssh and get going.
From one terminal connect to your office machine (paragOfcPc).

parag@paragpc:~# ssh paragOfcPc -L 10000:192.168.42.43:12871
Last login: Tue May 16 14:41:01 2016 from 172.168.XX.YY
[root@paragOfcPc ~]# ssh 192.168.42.43
Last login: Tue May 16 08:08:51 2016 from 172.168.XX.YY
[root@SQL43 ~]# nc -lkv 12871
Connection from 10.1.1.51 port 12871 [tcp/*] accepted
This forwards the local port 10000 to port 12871 on some server on my office LAN: 192.168.42.43, which is different from my office pc : paragOfcPc. The nice thing about using ssh is I get the added benefit of being on a secure encrypted connection.

From another terminal you can test it with :

parag@paragpc:~# cat hello.txt
This is a demo message for the connection
Send more messages to the remote server
parag@paragpc:~# cat hello.txt | nc localhost 10000
parag@paragpc:~#
After you execute the second command you should now see the content of the file hello.txt in nc -lkv output.

In case you want to send data only to your office pc (in my case paragOfcPc), you can substitute 192.168.42.43 with localhost while creating the tunnel with -L parameter

No comments:

Interview Question Preperation : Find longest subarray whose sum is equal to K

Software Engineering Practice interview question Given a array of N elements. Find the length of Longest Subarray whose sum is equal to give...