Perl 中的 chown 函数

Wil*_*lem 4 perl

我在 Perl 中运行 chown 函数时遇到问题。我有一个脚本:

#!/usr/bin/perl

$file   = "";
$file   = $ARGV[0];

$user   = "jboss";
$group  = "jboss";

if ($file eq "")
{
    print "Syntax: $0 <file>\n";
    exit 0;
}

@file = ($file);

print "Chowning the file $file to $user:$group\n";

$number = chown $user, $group, "$file";

print "Number of ownerships changed: $number\n";

exit 0;
Run Code Online (Sandbox Code Playgroud)

SELinux 已启用且允许,但是:

root# ls -l file 
-rw-r--r--. 1 root root 0 Jul 26 10:27 file  
root# id -a jboss uid=666(jboss) gid=666(jboss) groups=666(jboss)  
root# perlchown_file.pl file   
Chowning the file file to jboss:jboss  
Number of ownerships changed: 1  
root# ls -l file 
-rw-r--r--. 1 root root 0 Jul 26 10:27 file
Run Code Online (Sandbox Code Playgroud)

问题:我在这里想念什么?当然你可以在这里写一个 qx("/usr/bin/chown jboss:jboss "),但这里的重点是在这里使用一个更独立于平台的函数,而不是一个反引号

use*_*740 13

Perl 的chown函数需要一个数字 uid/gid 而不是用户/组名。请参阅perldoc -f chown

要从用户名中获取 uid 并从组名中获取 gid,您可以使用getpwnamgetgrnam函数,如下所示:

my $uid = getpwnam $user_name;
my $gid = getgrnam $group_name;
chown $uid, $gid, $file_name;
Run Code Online (Sandbox Code Playgroud)