#!/usr/bin/perl -w use strict; use IO::Socket::INET; my $PORT = $ARGV[0]; my $IP_ADDRESS = $ARGV[1]; if ((!defined $PORT) || (!defined $IP_ADDRESS)){ print "Please provide the IP-Adress or Port no!!\ne.g. Perl TCP_Server.pl \nPerl TCP_Server.pl 7777 127.0.0.1\n"; exit 0; } my $Receiving_Port = $PORT; # flush after every write $| = 1; my ( $socket, $received_data ); my ( $peeraddress, $peerport ); $socket = new IO::Socket::INET ( LocalHost => $IP_ADDRESS, LocalPort => $Receiving_Port, Proto => 'tcp', Listen => 5, Reuse => 1 ) or die "ERROR in Socket Creation : $!\n"; $socket->listen(); $socket->autoflush(1); print "TCP Server Started\n"; # Stay in endless loop to wait and look for tcp commands to be executed. my $addr; while (1) { $addr = $socket->accept(); print "$addr\n"; $peeraddress = $addr->peerhost(); $peerport = $addr->peerport() ; my $pid = fork(); # ignore signal CHILD in linux to prevent Zombie Process. if ( $^O !~ m/mswin32/i ) { $SIG{CHLD} = 'IGNORE'; } if ( $pid == 0 ) { my $exitCode; while (<$addr>) { # Read all messages from client # Print received message $received_data = $_; # Execute RunCommand for running the command and sending its response back. $exitCode = RunCommand( $received_data, $peeraddress, $peerport ); } exit $exitCode; close $addr; } } # Close socket when Command is received. $socket->close(); sub RunCommand { my $Command_To_Send = shift; my $send_ip = shift; my $peerport = shift; # file handler which will have response values. my $fileHandler; print "Executing: '$Command_To_Send'\n"; print "Output on: '$send_ip:$peerport'\n"; if ( $Command_To_Send =~ m/Check Connectivity/i ) { #sleep 20; ## Send Response back to Client, that tcp_server is now connected. print $addr "Connected to TCP socket server\n"; return 0; } if ( $Command_To_Send =~ m/\x03|\x1A/i ) { return 0; } # Execute the command by opening a pipe to channel. -| will read STDOUT # and assign it to fileHandler. my @pid = open( $fileHandler, '-|', "$Command_To_Send 2>&1" ); if ( $^O !~ m/mswin32/i ) { #Traversing pid array. foreach (@pid) { print "'$Command_To_Send' PID: $_\n"; print $addr "Process ID = $_\n"; } } # if no pid is assigned, means the command was incorrect or error while # sending the commmand. if ( $#pid == -1 ) { warn "Cannot Open Command !!\n"; print $addr "'$Command_To_Send' Unable to Start\n"; } # hotlist the filehandler for immediate flushing, no buffering. my $ofh = select $fileHandler; $| = 1; select $ofh; print $addr "Sending Command '$Command_To_Send'\n"; # write response of command to tcp socket which is sent to ATF. while (<$fileHandler>) { print $addr $_; } print $addr "\n"; print $addr "normal-exit\n"; print $addr "done\n"; # Killing if any process has not completed gracefully. # Traversing pid array. foreach (@pid) { my $curr_pid = $_; if ( $^O !~ m/mswin32/i ) { kill 9, $curr_pid; } } #Closing filehandler. close($fileHandler); return 0; }