Skip to content

Instantly share code, notes, and snippets.

@jhyland87
Created May 18, 2018 17:44
Show Gist options
  • Save jhyland87/29f672d1dfb83f2da7879c0dd8ec7db8 to your computer and use it in GitHub Desktop.
Save jhyland87/29f672d1dfb83f2da7879c0dd8ec7db8 to your computer and use it in GitHub Desktop.
#!c:/perl/bin
########################################################################################################################################################
# MMFTool.pl
# Created: 7/12/2010
# Justin Hyland [email protected]
# ######################################################################################################################################################
# DESCRIPTION: Provides WMI access to windows dedicated and virtual dedicated servers, ability to start tasts, stop, start, restart services, gather
# CPU/MEM info, reboot RDP & Psexec
# ######################################################################################################################################################
# NOTES: PerlIO needs to be manually compacted into MMFTool, so run command: pp -o mmftool.exe mmftool.pl -M PerlIO
# ######################################################################################################################################################
# Change Log
# 07/15/2010 - Added RDP 2003. If "C:/mstsc" exists, and "rdp" is requested, it will launch c:\mstsc\rstsc.exe, type the username and password in
# connect to the target server
# - Added ping -t $dedreq to the reboot command.
# 07/18/2010 - Added sub RESOLVE, script now connects to the server via WMI with the IP, not the domain name
# - Added sub WATCH, to list memory and CPU information, as well as a task list with the top 10 programs running
# - Added "start ping -t $svr_ip" to the reboot sub
# 07/19/2010 - Edited RESOLVE, now uses the beta SOAP service by DEV to get the primary IP of the server via the GetDedicatedServerIP method, DEV
# still has it in beta, to be released on 7.27.2010
# 07/28/2010 - DEV Completed the GetDedicatedServerIP SOAP namespace, service now works without hosts file
# - Fixed a bug in the watch command, cleared the array after every refresh.
# 08/08/2010 - Added "du" to show disk usage and availability on all drives
# - Fixed the percents of mem and CPU in the 'info' and 'watch' command.
# 08/10/2010 - Added "run" command, makes it easier to do forcable reboots nad iisresets.
# - Added "passwd" to add the users password to the clipboard, and display it (if not csdapp1 or 2)
# 08/11/2010 - Added "ipconfig" command to gather ipconfig info
# - mmftool now downloads/installs mstsc and psexec.exe into the proper directories, if they dont exist
# 08/11/2010 - Modified the 'who' and added a 'kick' command to see users on a server, and/or terminate the session
# - Added a "msg" command, to message users on the server.
# 08/17/2010 - Added "cons" to list the connections, type cons -d for a more detailed list
# - MMFtool now checks for RDP sessions whenever it connects to a server to avoid issues with customers
########################################################################################################################################################
use Switch;
use Win32::OLE qw( in );
use Win32;
use Win32::Service;
use Win32::Clipboard;
use Win32::API;
use Win32::Process;
use Win32::OLE::Variant;
use Win32::Process::Info;
use POSIX qw/floor/;
use Scalar::Util 'looks_like_number';
use Term::ReadKey;
use SOAP::Lite;
use XML::Simple;
use Number::Bytes::Human qw(format_bytes);
use Win32::GuiTest qw(FindWindowLike GetWindowText SetForegroundWindow SendKeys);
#use Data::Dumper;
######################################################################
# CATCHING CTRL + C
#$SIG{INT} = 'IGNORE';
&START;
######################################################################
# CONVERTING BYTES TO A MORE READABLE SIZE
sub ConvertBytes
{
$bytes = shift;
$size = format_bytes($bytes);
return $size;
}
######################################################################
# SUB TO CHECK FOR NUMERICS
sub IS_NUMERIC
{
$var = shift;
if (0 != substr($var,0,1) and looks_like_number($var))
{
return 1;
}
else
{
return 0;
}
}
#####################################################################
# TFSwitch: Switch 1 to "True" and 0 to "False
sub tfswitch
{
$var = shift;
switch($var)
{
case 1
{
$tf_result = "True";
}
case 0
{
$tf_result = "False";
}
else
{
$tf_result = $tf_result;
}
}
return $tf_result;
}
######################################################################
# GET SERVER LOGIN
# result codes ($svr_result):
# 0 = unable to login with creds given
# 1 = Loggedin but server not found
# 2 = Loggedin, sever found, creds provided as $svr_pw and $svr_un
# List of servers to bypass authentication on
%bp_auth = ('csdapp1', '216.119.106.193', 'csdapp2', '216.119.106.174');
sub GET_LOGIN
{
# List of servers to bypass authentication on
%bp_auth = ('csdapp1', '216.119.106.193', 'csdapp2', '216.119.106.174');
($my_un, $my_pw, $ded) = @_;
if (exists($bp_auth{$ded}))
{
$server_ip = $ded;
$bypassed = 1;
$svr_result = 2;
$svr_un = "CRYSTALTECH\\".$my_un;
$svr_pw = $my_pw;
return $svr_result;
return $svr_un;
return $svr_pw;
}
else
{
# Get info from WCC SOAP Service
$bypassed = 0;
$method = 'GetDedicatedLoginInfo';
$ep = 'http://webcontrolcenter.com/services/srvDedicatedInformation.asmx';
$uri1 = 'http://tempuri.org/ControlCenterNET/srvDedicatedInformation/';
$uri2 = 'http://tempuri.org/ControlCenterNET/srvDedicatedInformation';
$xml = '<AdminUsername xsi:type="xsd:string">' . $my_un . '</AdminUsername><AdminPassword xsi:type="xsd:string">' . $my_pw . '</AdminPassword><ServerName xsi:type="xsd:string">' . $ded . '</ServerName>';
$soap = SOAP::Lite
-> proxy ($ep)
-> uri($uri2)
-> on_action( sub { join '', $uri1, $_[1] } )
-> readable(1)
-> call ($method => SOAP::Data->type('xml' => $xml));
$out_xml = $soap->{_context}->{_transport}->{_proxy}->{_http_response}->{_content};
$xml = new XML::Simple;
$data = $xml->XMLin($out_xml);
chomp($result = $data->{'soap:Body'}->{'GetDedicatedLoginInfoResponse'}->{'GetDedicatedLoginInfoResult'});
if($result eq "Failed to authenticate username & password")
{
$svr_result = 0;
$svr_pw1 = "";
$svr_un = "administrator";
}
elsif($result eq "No login credentials found for")
{
$svr_result = 1;
$svr_pw1 = "";
$svr_un = "administrator";
}
else
{
$svr_result = 2;
($svr_un, $svr_pw1) = split ',', $result;
$svr_un = "administrator";
}
$vpsbuild = 0;
# Is it a VPS? COnstruct the password
if ($ded =~ /dedva/i)
{
$vpsbuild = 1;
}
if ($vpsbuild == 1)
{
$serverid = $ded;
($srvalpha, $srvnumber) = split(m/^...../, $serverid);
}
else
{
$serverid = $ded;
($srvalpha, $srvnumber) = split(m/^..../, $serverid);
($srvalpha, $nil) = split(m/\d+$/, $serverid);
}
$svr_pw = $svr_pw1.$srvnumber;
return $svr_result;
return $svr_un;
return $svr_pw;
return $result;
}
}
######################################################################
# SUB RESOLVE: Resolves a server name to its IP
# Results: 0 = Couldnt auth WCC un/pw, 1 = Couldnt find IP, 2 = IP found
sub RESOLVE
{
$ded = shift;
# List of servers to bypass authentication on
%bp_auth = ('csdapp1', '216.119.106.193', 'csdapp2', '216.119.106.174');
if(exists($bp_auth{$ded}))
{
$result = '2';
$svr_ip = $bp_auth{$ded};
}
else
{
$method = 'GetDedicatedServerIP';
$ep = 'http://webcontrolcenter.com/services/srvdedicatedinformation.asmx';
$uri1 = 'http://tempuri.org/ControlCenterNET/srvDedicatedInformation/';
$uri2 = 'http://tempuri.org/ControlCenterNET/srvDedicatedInformation';
$xml = '<AdminUsername xsi:type="xsd:string">' . $my_un . '</AdminUsername><AdminPassword xsi:type="xsd:string">'. $my_pw .'</AdminPassword><ServerName xsi:type="xsd:string">' . $ded . '</ServerName>';
$soap = SOAP::Lite
-> proxy ($ep)
-> uri($uri2)
-> on_action( sub { join '', $uri1, $_[1] } )
-> readable(1)
-> call ($method => SOAP::Data->type('xml' => $xml));
$out_xml = $soap->{_context}->{_transport}->{_proxy}->{_http_response}->{_content};
$xml = new XML::Simple;
$data = $xml->XMLin($out_xml);
chomp($ip_result = $data->{'soap:Body'}->{'GetDedicatedServerIPResponse'}->{'GetDedicatedServerIPResult'});
if($result eq "Failed to authenticate username & password")
{
$result = '0';
}
elsif($result eq "No primary IP found for $ded")
{
$result = '1';
}
else
{
$result = '2';
$svr_ip = $ip_result;
}
}
return $result;
return $svr_ip;
}
######################################################################
# SUB START: Primary sub
sub START
{
system("cls");
print "MMFTool v1.0 7/19/2010 by Justin Hyland\n";
system("title MMFTool v1.0");
&PSEXEC_CHECK;
sub PSEXEC_CHECK
{
close STDERR;
$psexec = `psexec`;
open(STDERR, ">&STDOUT");
if(!$psexec){
print "\nIt seems like your system does not have psexec installed, please press enter to install..\n\n";
system("pause");
close STDERR;
$xcopy_command = 'xcopy "X:\\New Hire\\tools\\psexec.exe" c:\\windows\\system32\\';
$copy =`$xcopy_command`;
open(STDERR, ">&STDOUT");
#print "output: $copy\n$xcopy_command";
if ($copy !~ /1 File/i)
{
print "\nIt seems that psexec was not installed..\n\n";
#print $copy."\n\n";
print "Please download psexec from http://technet.microsoft.com, and install it into c:\windows\system32 to continue";
print "\n\n\n";
exit;
}
else
{
print "\nPsexec.exe copied into c:\\windows\\system32..\n";
# GET THE server
&UN;
}
}
else
{
# GET THE server
&UN;
}
}
sub GET_DED
{
ReadMode('normal');
print "NOTE: You can only connect to Windows dedicated and VPS servers\n\n";
print "Dedicated Server> ";
chomp($ded_req = <>);
if(!$ded_req)
{
# CHECK FOR INPUT
print "\nPlease provide a dedicated server..\n\n";
&GET_DED;
}
&GET_LOGIN($my_un, $my_pw, $ded_req);
if($svr_result eq 1)
{
print "Unable to retreve credentials for $ded_req\n\n";
&GET_DED;
}
else
{
# get servers IP;
&RESOLVE($ded_req);
if($result ne '2')
{
if($result eq '1')
{
print "The WCC denied your username and password\n";
&GET_DED;
}
else
{
print "No primary IP found for $ded_req\n";
&GET_DED;
}
}
$success = "false";
$resolve = "false";
open PING, ("ping -n 3 " . $svr_ip . "|");
while (<PING>)
{
foreach ($_)
{
if ( $_ =~ /Reply from (.*)\s/i )
{
$success = "true";
}
}
}
if($success eq "false")
{
print "\n$ded_req is not responding (IP: $svr_ip)\n\n";
&GET_DED;
}
else
{
&SVR_LOGIN;
}
}
}
# GET USERNAME
sub UN
{
print "\nEnter your username (default: " . $ENV{'USERNAME'} . ")> ";
chomp($my_un = <>);
if(!$my_un)
{
$my_un = $ENV{'USERNAME'};
&PW;
}
&PW;
}
# GET THE PASSWORD
sub PW
{
print "\nEnter your password (Hidden)> ";
ReadMode('noecho');
chomp($my_pw = ReadLine(0));
if(!$my_pw)
{
print "\n";
&PW;
}
else
{
&GET_LOGIN($my_un, $my_pw, "");
#die($svr_result. " " .$result);
if($svr_result eq 0)
{
print "\n\nThe login credentials you have provided are incorrect, Please be sure to use CRYSTALTECH Credentials\n";
&UN;
}
else
{
print "\n\nYou are logged in as $my_un\n\n";
ReadMode('normal');
&GET_DED;
}
}
}
# CHECK WMI CONNECTION TO SERVER
sub SVR_LOGIN
{
$err = 0;
print "\nConnecting to $svr_ip... ";
$| = 1;
$locator = Win32::OLE->CreateObject('WbemScripting.SWbemLocator') or $err = 1;
if($err eq 1)
{
print "Failed\n\nUnable to connect to WMI on the target server\n\n";
&GET_DED;
}
$service = $locator->ConnectServer($svr_ip, "root\\cimv2", $svr_un, $svr_pw) or $err = 1;
if($err eq 1)
{
print "Failed\n\nUnable to login with the WCC credentials\n\n";
&GET_DED;
}
print "Success\n\n";
@col = in($service->ExecQuery("Select * from Win32_OperatingSystem"));
foreach $objItem ( @col )
{
print $objItem->{Caption};
}
print "\n";
print "\nChecking for other sessions... \n";
&WHO;
}
}
##############################################
# GET_STATUS: Will provide the readable status
# of a requested service (running, starting,
# stopped, stopping, paused, etc
sub GET_STATUS
{
$input_svc = shift;
@col = in($service->ExecQuery("Select * from Win32_Service WHERE DisplayName = '$input_svc'"));
foreach $objItem ( @col )
{
$service_state = $objItem->{State};
}
return $service_state;
}
############################################
# GET_MATCHES: Regex for shift in all sys
# Statuses, and return in %matches
sub GET_MATCHES
{
$input_svc = shift;
# EMPTY ARRAY TO GET POSSIBLE MATCHES
$count = 0;
%matches = ();
$#matches = -1;
@col = in($service->ExecQuery("Select * from Win32_Service"));
foreach $objItem ( @col )
{
if($objItem->{Caption} =~ /$input_svc/i)
{
$count++;
$matches{$count} = $objItem->{Caption};
}
}
return(%matches);
return($count);
}
############################################
# COMMANDS: Main subroutine, default to
# &COMMANDS; after errors or completed requests
sub COMMANDS
{
system("title MMFTool v1.0");
$SIG{INT} = \&COMMANDS;
print "\n$ded_req> ";
chomp($command = <>);
@args = split(" ", $command);
$do = $args[0];
switch($do)
{
#########################################################
# START: Back to start
case "start"
{
print "\n";
&START;
}
########################################################
# CONS: View Connections on server -d for detailed
case "cons"
{
print "\n";
if(($args[1]) && ($args[1] eq "-d")){
$command = "psexec \\\\" . $svr_ip . " -u " . $svr_un . " -p " . $svr_pw . " netstat -np tcp";
close STDERR;
$stdout = do {
open(local *STDERR, ">", \$stderr) or die "Could not capture STDERR: $!";
`$command`;
};
if(!$stdout)
{
print "\nError executing command.. (".$!." - ".$command.")\n";
}
else {
@rows = split("\n", $stdout);
splice @rows, 0, 4; # Remove the first 5 rows, which are the empty lines and column headers
$status_established = 0;
$status_time_wait = 0;
$str_ips = ();
foreach $row (@rows)
{
$row =~ /\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/i;
$proto = $1;
$local = $2;
@local = split(":", $local); #Get the local IP and Port
$local_ip = $local[0];
$local_port = $local[1];
$remote_ip = $3;
$status = $4;
if($local_ip ne "127.0.0.1") {
$total++;
# RECORD PORTS
if(!$str_ips->{$local_ip}->{$local_port}) {
$str_ips->{$local_ip}->{$local_port} = 1;
}
else {
$str_ips->{$local_ip}->{$local_port} ++;
}
}
}
for my $k1 ( sort keys %$str_ips ) {
print "# IP: $k1 ";
print "#" x 3 ."\n";
printf("%-8s %-8s\n", "PORT", "CONNECTIONS");
for my $k2 ( keys %{$str_ips->{ $k1 }} ) {
printf("%-8s %-8s\n", $k2, $str_ips->{ $k1 }->{ $k2 });
}
print "\n";
}
}
}
else {
$command = "psexec \\\\" . $svr_ip . " -u " . $svr_un . " -p " . $svr_pw . " netstat -np tcp";
close STDERR;
$stdout = do {
open(local *STDERR, ">", \$stderr) or die "Could not capture STDERR: $!";
`$command`;
};
if(!$stdout)
{
print "\nError executing command.. (".$!." - ".$command.")\n";
}
else {
@rows = split("\n", $stdout);
splice @rows, 0, 4; # Remove the first 5 rows, which are the empty lines and column headers
$status_established = 0;
$status_time_wait = 0;
%str_ports = ();
foreach $row (@rows)
{
$row =~ /\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/i;
$proto = $1;
$local = $2;
@local = split(":", $local); #Get the local IP and Port
$local_ip = $local[0];
$local_port = $local[1];
$remote_ip = $3;
$status = $4;
if($local_ip ne "127.0.0.1") {
$total++;
# RECORD PORTS
if(!$str_ports{$local_port}) {
$str_ports{$local_port} = 1;
}
else {
$str_ports{$local_port} ++;
}
}
}
printf("%-8s %-8s\n", "PORT", "CONNECTIONS");
while (($key, $value) = each(%str_ports) ) {
printf("%-8s %-8s\n", $key, $value);
}
}
}
&COMMANDS;
}
########################################################
# WHO: Return active sessions
case "who"
{
&WHO;
# Turned into subroutine, so MMFtool can check for other users on the server on connect
sub WHO
{
#@col = in($service->ExecQuery("Select * from Win32_LogonSession Where LogonType = '10'"));
#foreach $objItem ( @col )
#{
# @col2 = in($service->ExecQuery("Associators of {Win32_LogonSession.LogonId=".$objItem->{LogonId}."} Where AssocClass=Win32_LoggedOnUser Role=Dependent"));
# #print Dumper(@col2);
# foreach $objItem2 ( @col2 )
# {
# #print "full name ".$objItem2->{FullName}."\n";
# print $objItem2->{Name}."\n";
#print Dumper($objItem2);
# }
#}
$command = "psexec \\\\" . $svr_ip . " -u " . $svr_un . " -p " . $svr_pw . " qwinsta";
close STDERR;
$stdout = do {
open(local *STDERR, ">", \$stderr) or die "Could not capture STDERR: $!";
`$command`;
};
open(STDERR, ">&STDOUT");
if(!$stdout)
{
print "\nError executing command.. (".$!.")\n";
}
else
{
$sessions = 0;
print "\n";
@rows = split("\n", $stdout);
foreach $row ( @rows )
{
if ($row =~ /(\d+)\s\sdisc/i)
{
$sessions++;
$row =~ /(\S+)\s+(\d+)\s\sdisc/i;
$user = $1;
$session_id = $2;
print $user . " is Disconnected on session ID: " . $session_id."\n";
}
elsif($row =~ /\s(\S+)\s+(\S+)\s+(\d+)\s\s(\S+)/)
{
$sessions++;
$session_name = $1;
$user = $2;
$session_id = $3;
$session_state = $4;
print $user . " is ". $session_state ." on session ID: ". $session_id."\n";
}
}
if($sessions ne 0)
{
print "\nTotal Sessions: ". $sessions."\n";
}
else
{
print "No sessions available\n";
}
}
&COMMANDS;
}
}
########################################################
# KICK: Kick a session
case 'kick'
{
print "\n";
if(!$args[1])
{
print "Please type a session ID to kick. To see sessions, type 'who'";
}
else
{
$command = "psexec \\\\" . $svr_ip . " -u " . $svr_un . " -p " . $svr_pw . " rwinsta /V ". $args[1];
close STDERR;
$stdout = do {
open(local *STDERR, ">", \$stderr) or die "Could not capture STDERR: $!";
`$command`;
};
open(STDERR, ">&STDOUT");
if(!$stdout)
{
print "\nError executing command.. (".$!.")\n";
}
else
{
@rows = split("\n", $stdout);
$failed = 0;
foreach $row (@rows)
{
if ($row =~ /Session ID (.*) not found/)
{
$failed = 1;
}
}
if ($failed == 1)
{
print "Sesssion ID ". $args[1] ." was not found on ". $ded_req;
}
else
{
print "Session ID ". $args[1] ." has been reset";
}
}
}
print "\n";
&COMMANDS;
}
########################################################
# MSG: Message Users
case 'msg'
{
print "\n";
if(!$args[1])
{
print "Please type a session ID to message. To see sessions, type 'who'";
}
else
{
print "Message> ";
chomp($message = <>);
$command = "psexec \\\\" . $svr_ip . " -u " . $svr_un . " -p " . $svr_pw . " msg /V /TIME:500 ". $args[1] ." ". $message;
close STDERR;
$stdout = do {
open(local *STDERR, ">", \$stderr) or die "Could not capture STDERR: $!";
`$command`;
};
open(STDERR, ">&STDOUT");
if(!$stdout)
{
print "\nError executing command.. (".$!.")\n";
}
else
{
@rows = split("\n", $stdout);
$failed = 1;
foreach $row (@rows)
{
if ($row !~ /Async message sent to session/)
{
$failed = 0;
}
}
if ($failed == 1)
{
print "\nUnable to send message to Sesssion ID ". $args[1] ." on ". $ded_req;
}
else
{
print "\nMessage sent to Session ID ". $args[1];
}
}
}
print "\n";
&COMMANDS;
}
########################################################
# PASSWD: Display the password of Administrator, copy to clipboard
case 'passwd'
{
$CLIP = Win32::Clipboard();
$CLIP->Set($svr_pw);
if($bypassed eq 0)
{
print "\nPassword: set in clipboard ($svr_pw)\n";
}
&COMMANDS;
}
########################################################
# IPCONFIG: get NIC info
case 'ipconfig'
{
$command = "psexec \\\\" . $svr_ip . " -u " . $svr_un . " -p " . $svr_pw . " ipconfig";
close STDERR;
$stdout = do {
open(local *STDERR, ">", \$stderr) or die "Could not capture STDERR: $!";
`$command`;
};
open(STDERR, ">&STDOUT");
if(!$stdout){
print "\nUnable to connect to the target server..\n";
} else {
print $stdout."\n";
}
&COMMANDS;
}
########################################################
# RUN: Start a tastk from the command line
case "run"
{
print "\n";
delete $args[0]; #Remove "run"
if(@args eq 0)
{
print "Execute a command on the remote server.\nEG: run iisreset";
}
else
{
$run_arg = "";
# Construct command to run
foreach $arg (@args)
{
chomp($arg);
$run_arg = $run_arg."$arg ";
}
$run_arg = substr($run_arg, 1);
$run_arg = substr($run_arg, 0, -1);
@col = ($service->Get('Win32_Process'));
foreach $proc ( @col )
{
$vPid = Variant(VT_I4 | VT_BYREF, 0);
# Create the new process
if ($proc->Create($run_arg, undef, undef, $vPid) == 0)
{
print "Command: $run_arg\n";
print "Process Created ok, pid=$vPid";
}
else
{
print "Process create failed (Possibly an unknown command) $^E";
}
}
}
print "\n";
&COMMANDS;
}
########################################################
# TASK: Task kill, task list
case "task"
{
print "\n";
$arg = $args[1];
switch($arg)
{
####################################
# TASK LIST
case "list"
{
printf("%-25s %12s %12s\n", "Process", "PID", "Mem Usage");
foreach $Proc ( sort {lc $a->{Name} cmp lc $b->{Name}} in( $service->InstancesOf( "Win32_Process" ) ) )
{
printf("%-25s %12s %12s\n", $Proc->{Name}, $Proc->{ProcessID}, &ConvertBytes($Proc->{WorkingSetSize}));
}
}
###################################
# TASK KILL
case "kill"
{
#Task to kill
$kill_task = $args[2];
if($kill_task eq "")
{
print "Please type a task to kill, EG: task kill jrun\n";
&COMMANDS;
}
$success_killed = 0;
$failed_killed = 0;
foreach $Proc ( sort {lc $a->{Name} cmp lc $b->{Name}} in( $service->InstancesOf( "Win32_Process" ) ) )
{
$regex1 = "($kill_task)";
# Loop through processes, regex for the application
if ($Proc->{Name} =~ /$regex1/i)
{
$proc_name = $Proc->{Name};
# Grab each process with the regex results
@col = in($service->ExecQuery("Select * from Win32_Process Where Name = '$proc_name'"));
foreach $objItem ( @col )
{
#Grab PID and Process name
print "Killing ". $objItem->{Name} ." (". $objItem->{ProcessID} .") ..";
$thispid = $objItem->{ProcessID};
# Terminate, and give 3 seconds to Check
$objItem->{Terminate};
sleep(3);
@col2 = in($service->ExecQuery("Select * from Win32_Process Where ProcessID = '$thispid'"));
$count = 0;
foreach $objItem2 ( @col2 )
{
$count ++;
}
if($count eq 0)
{
print "Completed\n";
$success_killed++;
}
else
{
print "Failed\n";
$failed_killed++;
}
}
}
}
print "\tKilled: $success_killed\n\tFailed: $failed_killed\n";
$success_killed = 0;
$failed_killed = 0;
}
else
{
print "Task - Stop or list all tasks on target server\n\n";
print "EG:\n\ttask kill jrun\n\t- Will kill jrun.exe and jrunsvc.exe\n\n\ttask list \n\t- Would list all tasks on the server";
}
}
&COMMANDS;
}
#########################################################
# RDP: RDP into the server, print the password
# NOTE: Will not print password if $override is 1
# Means if it agents CT pw for server
case "rdp"
{
# If MSTSC 2003 exists, launch that and type the password
if(-d "C:/mstsc")
{
$Win32::GuiTest::debug = 0; # Set to "1" to enable verbose mode
print "\nC:\\MSTSC found, launching & connecting... ";
&RDP_CONNECT;
sub RDP_CONNECT
{
system("start C:/mstsc/mstsc.exe");
sleep(1);
@windows = FindWindowLike('', "Remote Desktop Connection");
$i = 0; #do it once
for (@windows) {
if($i eq 0){
$i++;
#print "$_>\t'", GetWindowText($_), "'\n";
SetForegroundWindow($_);
SendKeys($svr_ip."%o%c".$svr_ip."%u".$svr_un."%p".$svr_pw."%d{BACKSPACE}{ENTER}");
}
}
print "Done\n";
}
}
# Else, launch MSTSC, connect to the IP, put the PW in the clipboard
else
{
print "\nC:\\MSTSC Not found, Downloading from X:\\ ... ";
#xcopy /S /I "x:\New Hire\mstsc" c:\mstsc
close STDERR;
$xcopy_command = 'xcopy /S /I "x:\\New Hire\\tools\\mstsc" c:\\mstsc';
$copy =`$xcopy_command`;
open(STDERR, ">&STDOUT");
#print "output: $copy\n$xcopy_command";
if ($copy !~ /5 File/i)
{
print "Failed\n\n";
system("start mstsc.exe");
}
else
{
print "Done\n\n";
print "Connecting via RDP... ";
&RDP_CONNECT;
}
}
&COMMANDS;
}
#########################################################
# PSEXEC: Psexecs into the server
case "psexec"
{
system( "start psexec \\\\$svr_ip -u $svr_un -p $svr_pw cmd.exe" );
print "\nPsexec launched...\n";
&COMMANDS;
}
#########################################################
# DU: Show disk usage for all drives
case "du"
{
@col = in($service->ExecQuery("SELECT * FROM Win32_LogicalDisk"));
foreach $objItem ( @col )
{
print "\n";
print "Drive: ". $objItem->{Name}."\n";
print "Status: ". $objItem->{Status}."\n";
print "Size: ". ConvertBytes($objItem->{Size})."\n";
print "Free Space: ". ConvertBytes($objItem->{FreeSpace})."\n";
}
&COMMANDS;
}
#########################################################
# WATCH: Watch the server process
case "watch"
{
print "\nctrl+c to stop watching..";
$sleep = 3;
use constant wbemFlagReturnImmediately => 0x10;
use constant wbemFlagForwardOnly => 0x20;
WATCH_START:
# GET PROCESSOR INFORMATION
@col = in($service->ExecQuery("SELECT * FROM Win32_Processor", "WQL", wbemFlagReturnImmediately | wbemFlagForwardOnly));
foreach $proc(@col){
system ("cls");
print "CPU: LoadPercentage: ". $proc->{LoadPercentage} ."%\n";
}
# GET MEMORY INFORMATION
@col = in($service->ExecQuery("Select * from Win32_OperatingSystem"));
print "MEM: ";
foreach $objItem(@col){
$total_physical = &ConvertBytes($objItem->{TotalVisibleMemorySize});
$free_physical = &ConvertBytes($objItem->{FreePhysicalMemory});
$total_virtual = &ConvertBytes($objItem->{TotalVirtualMemorySize});
$free_virtual = &ConvertBytes($objItem->{FreeVirtualMemory});
$used_mem = $total_physical - $free_physical;
$used_mem2 = $objItem->{TotalVisibleMemorySize} - $objItem->{FreePhysicalMemory};
$total_physical2= $objItem->{TotalVisibleMemorySize};
$mem_percent = $used_mem2 / $total_physical2 * 100;
$mem_percent = floor($mem_percent);
printf("%-5s %-20s %-25s %-25s\n", $mem_percent."%,", $total_physical . " Total,", $free_physical . " Free Physical,", $free_virtual . " Free Virtual");
}
# SHOW TOP 10 PROGRAMS USING MEMORY
print "\n\tTop 10 memory usage programs\n";
@col = in($service->ExecQuery("SELECT * FROM Win32_Process WHERE WorkingSetSize > 20000000", "WQL", wbemFlagReturnImmediately | wbemFlagForwardOnly));
if($err eq 1){
print "\n\nUnable to view Win32_Process on ".$ip;
} else {
$aa = ();
foreach $objItem(@col){
$memory = $objItem->{WorkingSetSize}/1024;
push @aa, [$objItem->{ProcessId}, $objItem->{ParentProcessId}, $objItem->{WorkingSetSize}, $memory, $objItem->{Caption}];
}
@aa = sort{$b->[3] <=> $a->[3]} @aa;
$current = 0;
$list = 10;
print "\n";
printf("%-6s %-6s %-15s %-10s %-15s %-10s\n", "PID", "PPID", "Time", "Mem (M)", "Name");
print "\n";
while ($current < $list){
printf("%-6s %-6s %-15s %-10s %-15s %-10s\n", $aa[$current][0], $aa[$current][1], $aa[$current][2], $aa[$current][3], $aa[$current][4]);
$current++;
}
}
$#aa = -1;
sleep($sleep);
goto WATCH_START;
}
##########################################################
# REBOOT
case "reboot"
{
print "\nAre you sure you want to reboot this server? (y/n)\n\n";
print "> ";
chomp($confirm = <>);
if($confirm eq "y")
{
@col = in($service->ExecQuery("Select * from Win32_OperatingSystem"));
foreach $objItem ( @col )
{
$service_state = $objItem->{Reboot};
}
system("start ping -t " . $svr_ip);
}
&COMMANDS;
}
##########################################################
# INFO: Will return the CPU usage and Memory Usage
case "info"
{
# GET PROCESSOR INFORMATION
use constant wbemFlagReturnImmediately => 0x10;
use constant wbemFlagForwardOnly => 0x20;
print "\nCPU INFORMATION\n";
@col = in($service->ExecQuery("SELECT * FROM Win32_Processor", "WQL", wbemFlagReturnImmediately | wbemFlagForwardOnly));
foreach $proc(@col)
{
print "\t" . $proc->{Description} . ": LoadPercentage: ". $proc->{LoadPercentage} ."%\n";
}
print "\n";
# GET MEMORY INFORMATION
@col = in($service->ExecQuery("Select * from Win32_OperatingSystem"));
print "MEMORY INFORMATION\n ";
foreach $objItem(@col)
{
$total_physical = &ConvertBytes($objItem->{TotalVisibleMemorySize});
$free_physical = &ConvertBytes($objItem->{FreePhysicalMemory});
$total_virtual = &ConvertBytes($objItem->{TotalVirtualMemorySize});
$free_virtual = &ConvertBytes($objItem->{FreeVirtualMemory});
$used_mem = $total_physical - $free_physical;
$used_mem2 = $objItem->{TotalVisibleMemorySize} - $objItem->{FreePhysicalMemory};
$total_physical2= $objItem->{TotalVisibleMemorySize};
$mem_percent = $used_mem2 / $total_physical2 * 100;
$mem_percent = floor($mem_percent);
printf("\t%-5s %-20s %-25s %-25s\n", $mem_percent."%,", $total_physical . " Total,", $free_physical . " Free Physical,", $free_virtual . " Free Virtual");
}
print "\n";
&COMMANDS;
}
##########################################################
# HELP: duh
case "help"
{
# HELP ARRAY
%commands = (
"info", "Get information about target server (CPU info, memory info)",
"svc", "list, stop, start, or restart a service",
"psexec", "Connects to target server via psexec",
"rdp", "Opens RDP Session with target server",
"help", "Prints This Menu",
"task", "List or kill tasks",
"reboot", "Reboots target server",
"new", "Switch to a new dedicated server",
"watch", "Process monitor, (ctrl + c to stop)",
"du", "Show disk usage for all disks",
"exit", "Exits mmftool",
"run", "Runs any command via the server",
"passwd", "Display Administrator password, and copy to clipboard",
"ipconfig", "Displays the IP configuration of the server",
"who", "Displays active terminal sessions",
"kick", "Kick a session ID on the server",
"msg", "Message a user on the server",
"cons", "Luist Ports, IP's and connections, (cons -d for detailed list)",
);
print "\n";
printf("%-15s %8s\n", "Command", "Description");
print "\n";
while (($cmd, $desc) = each(%commands)){
printf("%-15s %8s\n", $cmd, $desc);
}
print "\nYou can get more information by adding 'help' to the end of any command\n\n";
&COMMANDS;
}
#########################################################
# NEW: Connect to a new server
case "new"
{
print "\n";
&GET_DED;
}
##########################################################
# SVC: List Services, stats, restart, stop, start, etc
case "svc"
{
if(!$args[1])
{
&SVC_HELP;
}
else
{
switch($args[1])
{
case "list"
{
&SVC_LIST;
}
case "start"
{
&SVC_START;
}
case "stop"
{
&SVC_STOP;
}
case "restart"
{
&SVC_RESTART;
}
else
{
&SVC_HELP;
}
}
}
###############################
# LIST SERVICES
sub SVC_LIST
{
print "\n";
@col = in($service->ExecQuery("Select * from Win32_Service"));
printf("%-65s %8s\n", "SERVICE NAME", "STATE");
print "\n";
foreach $objItem ( @col )
{
printf("%-65s %8s\n", $objItem->{Caption}, $objItem->{State});
}
print "\n";
printf("%-65s %8s\n", "SERVICE NAME", "STATE");
}
###############################
# STOP SERVICE
sub SVC_STOP
{
print "\n";
if(!$args[2])
{
&SVC_HELP;
}
else
{
$svc = $args[2];
GET_MATCHES($svc);
if($count == 0)
{
print "Sorry, no matches found!\n";
}
else
{
foreach $k (sort keys(%matches))
{
print $k." - ".$matches{$k}."\n";
}
print "\nPlease type the number of the service you wish to stop..\n\n";
&GET_STOP_SVC;
sub GET_STOP_SVC
{
print "> ";
chomp($svc_stop_input = <>);
if(!$svc_stop_input)
{
&COMMANDS;
}
elsif($matches{$svc_stop_input} eq "")
{
print "\nThat is not an option.\n\n";
&GET_STOP_SVC;
}
else
{
$stop_svc = $matches{$svc_stop_input};
&GET_STATUS($stop_svc);
if($service_state eq "Stopped")
{
print "\n'$stop_svc' is already stopped..\n";
}
else
{
print "\nStopping '$stop_svc'... ";
@col = in($service->ExecQuery("Select * from Win32_Service WHERE DisplayName = '$stop_svc'"));
foreach $objItem ( @col )
{
$objItem->{StopService};
}
&GET_STATUS($stop_svc);
while($service_state ne "Stopped")
{
&GET_STATUS($stop_svc);
}
print "Stopped.\n";
}
}
}
}
}
&COMMANDS;
}
###############################
# START SERVICE
sub SVC_START
{
print "\n";
if(!$args[2])
{
&SVC_HELP;
}
else
{
$svc = $args[2];
GET_MATCHES($svc);
if($count == 0)
{
print "Sorry, no matches found!\n";
}
else
{
foreach $k (sort keys(%matches))
{
print $k." - ".$matches{$k}."\n";
}
print "\nPlease type the number of the service you wish to start..\n\n";
&GET_START_SVC;
sub GET_START_SVC
{
print "> ";
chomp($svc_start_input = <>);
if(!$svc_start_input)
{
&COMMANDS;
}
elsif($matches{$svc_start_input} eq "")
{
print "\nThat is not an option.\n\n";
&GET_START_SVC;
}
else
{
$start_svc = $matches{$svc_start_input};
&GET_STATUS($start_svc);
if($service_state eq "Running")
{
print "\n'$start_svc' is already Running..\n";
}
else
{
print "\nStarting '$start_svc'... ";
@col = in($service->ExecQuery("Select * from Win32_Service WHERE DisplayName = '$start_svc'"));
foreach $objItem ( @col )
{
$objItem->{StartService};
}
&GET_STATUS($start_svc);
while($service_state ne "Running")
{
&GET_STATUS($start_svc);
}
print "Running.\n";
}
}
}
}
}
&COMMANDS;
}
###############################
# RESTART SERVICE
sub SVC_RESTART
{
print "\n";
if(!$args[2])
{
&SVC_HELP;
}
else
{
$svc = $args[2];
GET_MATCHES($svc);
if($count == 0)
{
print "Sorry, no matches found!\n";
}
else
{
foreach $k (sort keys(%matches))
{
print $k." - ".$matches{$k}."\n";
}
print "\nPlease type the number of the service you wish to restart..\n\n";
&GET_RESTART_SVC;
sub GET_RESTART_SVC
{
print "> ";
chomp($svc_restart_input = <>);
if(!$svc_restart_input)
{
&COMMANDS;
}
elsif($matches{$svc_restart_input} eq "")
{
print "\nThat is not an option.\n\n";
&GET_RESTART_SVC;
}
else
{
$restart_svc = $matches{$svc_restart_input};
# STOP SERVICE
&GET_STATUS($restart_svc);
if($service_state eq "Stopped")
{
print "\n'$restart_svc' is already Stopped..\n";
}
else
{
print "\nStopping '$restart_svc'... ";
@col = in($service->ExecQuery("Select * from Win32_Service WHERE DisplayName = '$restart_svc'"));
foreach $objItem ( @col )
{
$objItem->{StopService};
}
&GET_STATUS($restart_svc);
while($service_state ne "Stopped")
{
&GET_STATUS($restart_svc);
}
print "Stopped.\n";
}
# START SERVICE
&GET_STATUS($restart_svc);
if($service_state eq "Running")
{
print "\n'$restart_svc' is already Sunning..\n";
}
else
{
print "\nStarting '$restart_svc'... ";
@col = in($service->ExecQuery("Select * from Win32_Service WHERE DisplayName = '$restart_svc'"));
foreach $objItem ( @col )
{
$objItem->{StartService};
}
&GET_STATUS($restart_svc);
while($service_state ne "Running")
{
&GET_STATUS($restart_svc);
}
print "Running.\n";
}
}
}
}
}
&COMMANDS;
}
###############################
# SERVICE HELP
sub SVC_HELP
{
print "\nSVC - Stop, Start, Restart or List servies on target server\n";
print "EG: svc restart cold\n\tWill list all coldfusion related services, and prompt for which one to restart\n";
}
&COMMANDS;
}
##################################################
# EXIT Switch
case 'exit'
{
exit;
}
###################################################
# Else Switch
else
{
print "\nYou have entered an invalid command, type 'help' for help\n";
&COMMANDS;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment