Thursday, November 6, 2008

Establish SSH Tunnel and run VNCViewer using Perl

Using perl, I was trying to run SSH Tunnel first and then run VNCViewer through this tunnel. Of course it was not so simple as to just doing the following in perl:

#!/usr/bin/perl
system("ssh -l -L 10000:localhost:5901 ");
system("vncviewer localhost:10000");

If you try to do the above, it won't work! This is because the process gets stuck on the first line while in SSH. Basically if the tunnel is active, it can't possibly run the next command which is to launch vncviewer. But if the tunnel is terminated, so that we can run vncviewer, vncviewer won't work because there is no more binding on port 10000.

We need to use perls' build in fork function. Similar to running programs using the trailing & command in C. My implementation (thanks to estabroo from LQ) is as follows:

$pid = fork();
if ($pid == 0) {
system("ssh -l -L 10000:localhost:5901 ");
exit(0);
} elsif ($pid > 0) {
sleep(5);
system("vncviewer localhost:10000");
} else {
print "fork failed\n";
}

Basically what this does is, fork the process, execute SSH, wait for login and exit, sleep for 5 seconds, run the child process vncviewer. Done :)

No comments: