2016-02-15 166 views
0

這裏用戶使用Linux命令是代碼: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命令「最後」的所有存儲在用戶@ temparray。我想輸出是這樣的:

用戶1:10

用戶2:22

其中22和10被他們登錄的次數,我怎樣才能做到這一點? 我嘗試了幾種不同的方法,但我總是以錯誤結束。

+1

在'$ lastbash'中用'$ _'更改'$ temparray'。你的問題只是爲了解釋'last'命令的輸出嗎? – bolav

+0

@bolav非常感謝!這非常出色。 – nillenilsson

回答

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 $_.":"[email protected]"\n"; #<----Note the formatting. Reading @lastbash returns the number of elements. 
} 
+2

保持看似不必要的'utf8'編譯指示,未使用的'@ lastarray',命名不當的變量或將用戶添加到'@ temparray'的非常規方法的任何特殊原因? –

+0

通常情況下,這些瑣碎的腳本很少,而且不幸的是優化被忽略了。與往常一樣,許多優化都是可能的。然而,這不是問題的重點。 –

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}; 
}