[原创] WinXP下根据端口查询对应的进程

来源:互联网 发布:js模块化编程思想 编辑:程序博客网 时间:2024/05/11 02:36

######################################################
# QueryPortW.pl
# 根据端口查询对应的进程(Windows XP 版本)
# Author:  Rick Cheng
# Date:    2005-10-30  
# Version: 1.0
######################################################

#! /usr/bin/perl -w

use strict;

my @portList;  #端口号列表

foreach (@ARGV)
{
    push @portList, $_ if (/^[^-]/d+$/);
}
&checkUsage();
print "PORT/tPID/tCOMMAND/n"; #输出表格头
foreach (@portList)
{
    my $port = $_;
    my $pid = undef;
   
    #根据端口定位PID
    `netstat -ano | grep $port | grep -v grep > QueryPortW.port`;
    open TMP, "./QueryPortW.port" or die "Can't open QueryPortW.port: $!";
    while (<TMP>)
    {
        chomp;
        my @tmpList = split;
        if ($tmpList[1] =~ /^/d+/./d+/./d+/./d+:(/d+)$/)
        {
            if ($1 == $port)
            {
                $pid = $tmpList[-1];
                last;
            }
        }
    }
    close TMP;
    `rm ./QueryPortW.port`;
       
    #未找到PID,跳出本次循环
    unless (defined $pid)
    {
        print "$port/tNA/tNA/n";
        next;
    }
   
    #根据PID定位进程名
    my $tmpCmd = `tasklist /NH /FI "PID eq $pid"`;
    my @tmpList = split //s+/, $tmpCmd;
    my $command = $tmpList[1];
    print "$port/t$pid/t$command/n";   
}
print ":Done!/n";

#检测命令行输入
sub checkUsage()
{
    if ($#portList == -1)
    {
        print "[USAGE] perl QueryPortW.pl port1 port2 .../n";
        exit -1;
    }
}

原创粉丝点击