使用 bash 将 bcrypt 哈希插入文件中的特定行

Insert bcrypt hash into specific line in file using bash

我需要通过将 bcrypt 哈希插入文件 config.yml 的特定行来更新应用程序配置。

echo -e "$Enter password for user1"
read -p ": " user1_pass

echo -e "$Enter password for user2"
read -p ": " user2_pass

user1_hash=$(htpasswd -bnBC 10 "" $user1_pass | tr -d ':\n')
user2_hash=$(htpasswd -bnBC 10 "" $user2_pass | tr -d ':\n')

$user1_hash 应放在第 2 行,$user2_hash 应放在第 7 行。

config.yml

    user1:
      hash: "y$shEKzuVfogdZFbbraSqhwOOh96hfxe1NzLQbpmHJvgDUeRfRrkf3a"
      reserved: "true"
      roles: "user"

    user2:
      hash: "y$Fkc5GAp9Za5caIfHjBgNQ.jNEss0SJfCLTlm9EhAcjzPVy.kLriBa"
      reserved: "true"
      roles: "user"

使用 bash 执行此操作的最佳方法是什么?

您可以使用 Ruby 编辑文件:

#!/usr/bin/ruby

require 'yaml'
obj = YAML.load_file('config.yml')

bcrypt_hash='y$shEKzuVfogdZFbbraSqhwOOh96hfxe1NzLQbpmHJvgDUeRfRrkf3a' 
obj['user1']['hash'] = bcrypt_hash
obj['user2']['hash'] = bcrypt_hash

puts YAML.dump(obj)

这将输出:

... More yml content
user1:
  hash: "y$shEKzuVfogdZFbbraSqhwOOh96hfxe1NzLQbpmHJvgDUeRfRrkf3a"
user2:
  hash: "y$shEKzuVfogdZFbbraSqhwOOh96hfxe1NzLQbpmHJvgDUeRfRrkf3a"
... More yml content

希望对您有所帮助!

使用关键字echo写入文件

echo -e "$Enter password for user1"
read -p ": " user1_pass

echo -e "$Enter password for user2"
read -p ": " user2_pass

user1_hash=$(htpasswd -bnBC 10 "" $user1_pass | tr -d ':\n')
user2_hash=$(htpasswd -bnBC 10 "" $user2_pass | tr -d ':\n')

echo "user1:" > config.yml
echo "    hash: " +  $user1_hash >> config.yml
echo "user2:" >> config.yml
echo "    hash: " + $user2_hash >> config.yml

config.yml 文件的内容

user1:
    hash:  + yS0fC4wTqAfm9ytJ5BquC.3KITsqLoqPXHyj3mzgXdvw10TRIybni
user2:
    hash:  + y$jcYMrOsdIzwR3AlSONNfCuc.B5AoGVV4i31KSsx0PLlpn17issJfe