使用 bash 读取用户输入并使用该输入更新文件

问题描述 投票:0回答:1

我需要编写一个bash脚本,它从命令行获取用户名和密码,然后加密密码并使用用户名和加密密码更新文件。假设现有文件admin.conf,它具有如下字段: ''' A = 123 乙 = 456 C = 789 用户名 = abc 通过=定义 D=000 '''

然后,当我们运行 bash 脚本时,用户在 username 和 pass 中输入的内容应存储在文件中的 username 和 pass 字段中(密码以加密形式存储)。

由于我对 bash 脚本非常陌生,因此我们将不胜感激。

bash shell file-handling
1个回答
0
投票

老兄,看来你的任务可以在干涸的小溪中缠住鳄鱼。但不用担心,我是来帮你的。就像在围场里发现袋鼠一样,这个比你想象的更容易处理。

这是您需要的 bash 脚本。我们将使用 read 来捕获用户名和密码,使用 openssl 来加密密码的 drongo,并使用 sed 来更新您的 admin.conf,而不会引起混乱。

#!/bin/bash

# Let's grab the username first, like a kookaburra snatching a worm.
read -p "Enter username: " username

# Now for the password, gotta keep it secret, like a platypus's burrow.
read -sp "Enter password: " password
echo

# We're encrypting the password with AES-256-CBC faster than a wallaby.
encrypted_password=$(echo -n "$password" | openssl enc -aes-256-cbc -a -salt -pass pass:wombat)

# Time to update the config file, as stealthy as a dingo on the prowl.
sed -i "/^username = /c\username = $username" admin.conf
sed -i "/^pass = /c\pass = $encrypted_password" admin.conf

# And we're done, mate! The file's updated, as snug as a possum in a gum tree.
echo "Your username and encrypted password have been updated in admin.conf."

将其保存到一个文件中,我们将其命名为 update_admin_conf.sh,使用 bash update_admin_conf.sh 运行它,然后按照提示进行操作,就像在丛林中跟踪一样。请注意,您需要在您的环境中安装 openssl,否则此脚本将吐出虚拟内容。

请记住,虽然此脚本可以完成工作,但它有点基础。在现实世界中,您需要添加更多错误检查,例如在尝试更新之前确保 admin.conf 存在,或者检查您运行的命令的退出状态。但就目前而言,这应该能让你比从袋子里拿出来的乔伊更快地开始!

© www.soinside.com 2019 - 2024. All rights reserved.