将shell输出传递给perl脚本日志

时间:2013-11-19 16:14:09

标签: perl shell logging

这个脚本的作用是下拉用户名和passowrds列表并对其进行哈希处理,然后将其添加到 一个列表。当有非asci字符时,quotemeta会转义它们,这允许htpasswd命令 消耗vaule。当我运行它时,它会将/ usr / local / apache2 / bin / htpasswd的结果打印到终端。 我想将所有结果传递给文件

#!/usr/bin/perl
use strict; 
use warnings;
use DBI;
use File::Copy;

unshift @INC,"/production/lib";
require "config.pl";
$configFile = "/production/cfg/syncUsers.cfg";
readConfig($configFile);

#doBackup($prefs{passwdFile});
generatePasswdFile("tmpusers");
getUsers($prefs{dbUser},$prefs{dbPass},$prefs{dbSid});
#copyPasswdFile($prefs{passwdFile});

# getUsers - grab user from the db and set them up
sub getUsers { 
    $dbUser = shift;
    $dbPass = shift;
    $dbSid  = shift;
    $dbh =  DBI->connect("dbi:Oracle:$dbSid","$dbUser","$dbPass") or die( "Couldn't connect: $!" );
    $sql = "SELECT user_name,passwd FROM login_tbl";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    while ( ( $user_name,$passwd ) = $sth->fetchrow_array ) {
            $user_name = quotemeta($user_name);
            $passwd = quotemeta($passwd);
            #print "$user_name,$passwd\n";
            updatePasswdFile($user_name,$passwd);   
    }
    $dbh->disconnect();
}

# generatePasswdFile - generate a dummy file to start with
sub generatePasswdFile {
    $file = shift;
    $cmd = "$prefs{htpasswd} -bc /tmp/$file dummyuser dummyuser";
    system($cmd); 
}

# updatePasswdFile - update the passwdfile
sub updatePasswdFile {
    $file = "/tmp/tmpusers"; 
    $user = shift;
    $pass = shift;
    print "Adding user: $user\n";
    $cmd = "$prefs{htpasswd} -b $file $user $pass";
    system($cmd);
}

这就是我打印到屏幕的方式。

Adding user: dev_ops
Adding password for user dev_ops
Adding user: dev_shed
Adding password for user dev_shed
Adding user: robogrl
Adding password for user robogrl
Adding user: a_foo
Adding password for user a_foo
Adding user: atank
Adding password for user atank
Adding user: acar
Adding password for user acar
Adding user: acarlson
Adding password for user acarlson
Adding user: dnick
Adding password for user dnick

当我将它传递给文件以便我可以检查错误时,只有一半会转到文件 另一半输出到屏幕。

bash-3.00$ ./caspser.pl > /tmp/checkFORerrors2013Nov19   

此输出仍会显示在屏幕上 -

Adding password for user dev_ops
Adding password for user dev_shed
Adding password for user robogrl
Adding password for user a_foo
Adding password for user atank
Adding password for user acar
Adding password for user acarlson
Adding password for user dnick

这将转到文件

Adding user: dev_ops
Adding user: dev_shed
Adding user: robogrl
Adding user: a_foo
Adding user: atank
Adding user: acar
Adding user: acarlson
Adding user: dnick

如何将所有内容转到文件中? 更好的是 - 有没有办法只打印错误?

1 个答案:

答案 0 :(得分:3)

您使用的htpasswd命令打印到STDERR(标准错误)。您执行的重定向会将STDOUT(标准输出)重定向到文件中。要重定向两者,您需要更新命令:

bash-3.00$ ./caspser.pl > /tmp/checkFORerrors2013Nov19 2>&1

基本上,错误会打印到不同的流中。两个流都在终端中显示而没有重定向,只有当您开始更改它们时,差异才会变得明显。