Last active
August 29, 2015 14:14
-
-
Save wh13371/c9c51fbed17cebfaff35 to your computer and use it in GitHub Desktop.
perl - runcmd - run commands and output to console\log file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# examples: | |
# ./runcmd.pl -l -c "ls -lah" | |
# include <timestamp> and enable <verbose> mode | |
# ./runcmd.pl -t -l -v -c "ls -lah" | |
# run multiple commands with <delay> = 5 | |
# ./runcmd.pl -v -d 5 -c "ls -lh && df -h && free -m && df -h" -l -t | |
use strict; | |
use warnings; | |
use 5.010; | |
use Getopt::Long; | |
use Data::Dumper; | |
use Time::HiRes; | |
use POSIX; | |
use IO::Handle; | |
my $logger; | |
my $verbose; | |
my $timestamp; | |
my $delay = 5; | |
my $command = 'ps aux'; # default command | |
my $logfile = strftime("%Y_%m_%d_%H_%M_%S", localtime) . "_" . $^T . ".log"; | |
sub cmd_args | |
{ | |
GetOptions("log|l", \$logger, "delay|d=i", \$delay, "time|t", \$timestamp, "verbose|v", \$verbose, "command|c=s", \$command) or die $!; | |
say $delay if $verbose; | |
} | |
sub now | |
{ | |
my ($seconds, $microseconds) = Time::HiRes::gettimeofday; | |
my $dt = strftime(q/%Y:%m:%d %H:%M:%S./, localtime($seconds)) . sprintf("%06d", $microseconds); | |
return $dt; | |
} | |
sub out | |
{ | |
my $fh; | |
open($fh, '>>', $logfile) or die "$!"; | |
$fh->autoflush(1); | |
say $fh now() if $timestamp; | |
say $fh @_; | |
close($fh); | |
} | |
sub run | |
{ | |
my @cmd = qx/$command/; # run the command and store output | |
out @cmd if $logger; # to FILE | |
# to STDOUT | |
say now() if $timestamp; | |
say @cmd; | |
say now() if $verbose; | |
} | |
sub main | |
{ | |
for(;;) | |
{ | |
run(); | |
sleep($delay); | |
} | |
} | |
cmd_args; | |
main; | |
exit; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment