【问题标题】:Replace matches in a file with a hashed value用散列值替换文件中的匹配项
【发布时间】:2013-12-23 02:05:54
【问题描述】:

我偶然发现了一个我有很大弱点的问题。我没有完成此任务所需的 ninja bash、awk、sed 等技能:

我正在处理一个 Freeradius 用户文件,其中存储了 VPN 客户端的用户名、密码和其他设置。所以这个文件中的记录是这样的格式:

vpnclient       Cleartext-Password := "ComplexPassword"
                Service-Type = Outbound-User,
                Framed-IP-Address = 172.16.0.225,
                Framed-IP-Netmask = 255.255.255.255,
                Cisco-AVPair += "ipsec:inacl=IPSEC_EXTRANET",
                Cisco-AVPair += "ipsec:dns-servers=192.168.1.31 192.168.1.32",
                Cisco-AVPair += "ipsec:split-dns=mydomain.com",
                Cisco-AVPair += "ipsec:split-dns=yourdomain.com"

我想从中提取Cleartext-Password := "ComplexPassword" 位并将密码替换为相应的 MD5 哈希值。我还想同时将Cleartext-Password 替换为MD5-Password。所以处理后我希望文件中的记录看起来像这样:

vpnclient       MD5-Password := "be2cb07387a0574f11772a5b3540845c"
                Service-Type = Outbound-User,
                etc.

所以真的,我只想找到一个正则表达式匹配,处理它并将其插入而不是文件中的原始值。我认为这在许多其他情况下也很方便。问题是,我不知道是否有可能,例如使用外部命令或函数代替 sed 和类似的东西。

【问题讨论】:

  • 您不必具备忍者技能就可以开始并尝试一下。 :-) 包括尝试解决方案在内的问题(无论有多么错误)通常都能得到更快的回答。

标签: regex bash sed awk


【解决方案1】:
awk '/Cleartext-Password/{
    match($0,/"(.*)"/,a)
    passw=a[1]
   ("echo "passw " | md5sum") |& getline var
   split (var,b)
   sub(/".*"/,"\""b[1]"\"")
} 1 ' input.txt

【讨论】:

    【解决方案2】:

    使用 awk:

    awk -F' *:= *' '$1~/Cleartext-Password/{gsub(/"/, "", $2); printf "%s := \"", $1;
        system("md5 <<< \"" $2 "\"|tr -d \"\\n\""); print "\"";next}1' vpnfile
    
    vpnclient       Cleartext-Password := "be2cb07387a0574f11772a5b3540845c"
                    Service-Type = Outbound-User,
                    Framed-IP-Address = 172.16.0.225,
                    Framed-IP-Netmask = 255.255.255.255,
                    Cisco-AVPair += "ipsec:inacl=IPSEC_EXTRANET",
                    Cisco-AVPair += "ipsec:dns-servers=192.168.1.31 192.168.1.32",
                    Cisco-AVPair += "ipsec:split-dns=mydomain.com",
                    Cisco-AVPair += "ipsec:split-dns=yourdomain.com"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 2015-09-20
      • 2021-12-03
      相关资源
      最近更新 更多