Linux modify user password script

Linux modify user password script

1. Shell script to modify user password

#!/bin/bash

# 定义目标用户名和新密码
username="root"
new_password="123465"

# 使用 passwd 命令修改目标用户的密码并检查结果
if echo -e "$new_password\n$new_password" | passwd $username; then
  echo "Password changed successfully for user $username."
else
  echo "Failed to change password for user $username."
fi

2. Explanation

What this script does can be seen in more detail when we explain it line by line:

#!/bin/bash

This is a bash script that specifies the shell interpreter used by the script.

# 定义目标用户名和新密码
username="your_username"
new_password="123465"
  • Here, we define two variables username and new_password. You will need to replace your_username
    with the name of the user whose password you want to change, and 123465 with the new password you want to set.
# 使用 passwd 命令修改目标用户的密码并检查结果
if echo -e "$new_password\n$new_password" | passwd $username; then
  echo "Password changed successfully for user $username."
else
  echo "Failed to change password for user $username."
fi
  • Here, if is a keyword of a conditional statement, used to perform conditional judgment. Next, we use a command to determine whether the user password has been successfully changed.
  • echo -e "$new_password\n$new_password" | passwd $username
    is the command we execute. In this command, we use echo command to pass the new password to passwd command through pipe | echo -e means to enable parsing of escape characters so that two password inputs can be passed as multi-line strings to the passwd command. The value of $new_password will be replaced with the actual new password, and the value of $username will be replaced with the target username.
  • After the command is executed, the if conditional statement checks the command's exit status code. If the command is executed successfully, its exit status code is 0, which means the password has been changed successfully. In this case, the statement inside the then block will be executed, i.e. a success message will be printed.
  • If the command execution fails and its exit status code is not 0, it means that the password modification failed. In this case, the statements inside the else block will be executed, i.e. a failure message will be printed.
  • Regardless of success or failure, execution of the conditional statement ends and the program continues executing other statements in the script.
  • Finally, replace "your_username" with the target username, replace "123465" with the desired password, and execute the script to modify the target user's password .

Guess you like

Origin blog.csdn.net/weixin_43576565/article/details/133906129