开发者

awk or perl file editing & manipulation

开发者 https://www.devze.com 2022-12-26 10:43 出处:网络
I have a standard passwd file & a usermap file - which maps unix name (eg jbloggs) with AD account name (eg bloggsjoe) in the format:

I have a standard passwd file & a usermap file - which maps unix name (eg jbloggs) with AD account name (eg bloggsjoe) in the format:

jbloggs bloggsjoe

jsmith smithjohn

... etc.

How can I edit the passwd file to swap the original unix name with the AD account name so each line of the passwd file has the AD account name instead.

Appreciate any help f开发者_如何学Cor a perl learner.


#! /usr/bin/perl -T

use strict;
use warnings;
use File::Slurp 'slurp';

my ($map_file, $pass_file) = @ARGV or die 'No arguments given!';

my %ad_for;

for my $line (slurp($map_file)) {
    chomp $line;
    my ($unix, $ad) = split / /, $line;
    $ad_for{$unix} = $ad;
}

for my $line (slurp($pass_file)) {
    my ($name, @entries) = split /:/, $line;
    if ($ad_for{$name}) {
        print join ':', $ad_for{$name}, @entries;
    }
    else {
        warn "name $name doesn't have an ad entry\n";
    }
}


here's a awk one liner to do that

$ cat map.txt
jbloggs bloggsjoe
jsmith smithjohn

$ cat passwd
root:x:0:0:root:/root:/bin/bash
jbloggs:x:493:484:Blogger:/var/run/lib:/sbin/nologin
jsmith:x:27:481:MySQL Server user:/var/lib/mysql:/bin/bash

$ awk -F":" 'FNR==NR{gsub(" +",":");m[$1]=$2;next}($1 in m){$1=m[$1]}1' OFS=":"  map.txt passwd
root:x:0:0:root:/root:/bin/bash
bloggsjoe:x:493:484:Blogger:/var/run/lib:/sbin/nologin
smithjohn:x:27:481:MySQL Server user:/var/lib/mysql:/bin/bash


With Perl, read the AD file in and populate an AD-Unix hash, which you can then use to perform the replacement with a one-liner. This assumes that you have no duplicate usernames, of course.

(Untested)

my %AD;

system ("perl -ane '$AD{$F[0]} = $F[1]' unixMap.txt");
system ("perl -i -ape 's/$F[0]/$AD{$F[0]}/' passwordFile.txt");


Use Passwd::Unix. It will coordinate the editing of /etc/passwd, /etc/shadow, and /etc/group for you. Be sure to backup these files before you try editing them.

0

精彩评论

暂无评论...
验证码 换一张
取 消