Perl,对存储在哈希中的用户使用linux命令

时间:2016-02-15 18:23:43

标签: linux bash perl

以下是代码:

#!/usr/bin/perl

use warnings;
use strict;
use utf8;


my @temparray;
my $count = 0;
my @lastarray;
my $lastbash;


#Opens the file /etc/shadow and puts the users with an uid over 1000 but less that 65000 into an array.
open( my $passwd, "<", "/etc/passwd") or die "/etc/passwd failed to open.\n";

    while (my $lines = <$passwd>) {
        my @splitarray = split(/\:/, $lines );
        if( $splitarray[2] >= 1000 && $splitarray[2] < 65000) {

            $temparray[$count] =$splitarray[0];
            print "$temparray[$count]\n";
            $count++;
        }
    }
close $passwd;

foreach (@temparray) {
    $lastbash = qx(last $temparray);
    print "$lastbash\n";
}

我想要做的是使用内置的linux命令&#34; last&#34;存储在@temparray中的所有用户。我希望输出如下:

用户1:10

用户2:22

其中22和10是他们登录的次数。我怎样才能实现这一目标? 我尝试了几种不同的方法,但我总是遇到错误。

2 个答案:

答案 0 :(得分:1)

以下内容应按要求执行任务:

#!/usr/bin/perl

use warnings;
use strict;
use utf8;


my @temparray;
my $count = 0;
my @lastarray;
my $lastbash;


#Opens the file /etc/shadow and puts the users with an uid over 1000 but less that 65000 into an array.
open( my $passwd, "<", "/etc/passwd") or die "/etc/passwd failed to open.\n";

    while (my $lines = <$passwd>) {
        my @splitarray = split(/\:/, $lines );
        if( $splitarray[2] >= 1000 && $splitarray[2] < 65000) {

            $temparray[$count] =$splitarray[0];
            print "$temparray[$count]\n";
            $count++;
        }
    }
close $passwd;

foreach (@temparray) {
    my @lastbash = qx(last $_); #<----Note the lines read in go to the $_ variable. Note use of my. You also read the text into array.
    print $_.":".@lastbash."\n";  #<----Note the formatting. Reading @lastbash returns the number of elements.
}

答案 1 :(得分:1)

你真的不需要$count,你可以push @temparray, $splitarray[0]

那就是说,我不确定你为什么需要@temparray ...你可以在发现它们时对用户运行命令。

my $passwd = '/etc/passwd';
open( my $fh, '<', $passwd )
  or die "Could not open file '$passwd' : $!";

my %counts;

# Get `last` counts and store them %counts
while ( my $line = <$fh> ) {
    my ( $user, $uid ) = ( split( /:/, $line ) )[ 0, 2 ];
    if ( $uid >= 1000 && $uid < 65000 ) {
        my $last = () = qx{last $user};
        $counts{$user} = $last
    }
}
close $fh;

# Sort %counts keys by value (in descending order)
for my $user ( sort { $counts{$b} <=> $counts{$a} } keys %counts ) {
    printf "%s:\t %3d\n", $user, $counts{$user};
}