我有一个树莓派。它有一个用户 pi,我们在每次启动时自动登录。我需要将 pi 重命名为 myuser。为此,我按照以下步骤操作:
- sudo passwd root -> 为 root 用户分配密码
- 须藤重新启动
- 以 root 身份登录
- 运行命令
usermod -l myuser pi
usermod -m -d /home/myuser myuser
- 须藤重新启动
- 以 myuser 身份登录
- 编辑文件
/etc/sudoers
并将 pi 更改为 myuser
按照上述步骤将 pi 用户更改为 myuser。
我需要为此编写一个脚本。但我面临的问题是如何在重新启动并以 root/pi 身份登录时保持脚本运行。例如,以 root 身份登录并可以使用以下命令从 pi 注销
sudo pkill -u pi
这将从 pi 注销,当我可以通过输入用户名 (root) 和密码以 root 身份登录时,会出现登录屏幕。但是以 root 身份登录后,如何保持脚本运行以便它可以运行命令usermod -l myuser pi
usermod -m -d /home/myuser myuser
。有什么方法可以做到这一点,或者有任何替代方法可以更改用户名。
谢谢。
答案1
您遇到的问题似乎是您试图修改登录的用户帐户。这可能有点棘手。但你可以尝试如下操作:
# Become the root user (if you aren't already)
sudo su
# Set the password for the root user
echo "root:<PASSWORD>" | chpasswd
# Update the system user-datbase files to reflect the name-change
sed -i 's/pi/myuser/g' /etc/passwd
sed -i 's/pi/myuser/g' /etc/shadow
sed -i 's/pi/myuser/g' /etc/group
# Update the sudoers file to reflect the name-change
sed -i /etc/sudoers 's/pi/myuser/g'
# Move the user home directory to the new location (the UID stays the same, we don't need to run chown)
mv -i /home/pi /home/newuser
如果您想在以用户身份登录时以非交互方式运行此脚本pi
,则可以创建以下脚本:
#!/bin/bash
# update_user.sh
# Set the password for the root user
echo "root:<PASSWORD>" | chpasswd
# Update the system user-datbase files to reflect the name-change
sed -i 's/pi/myuser/g' /etc/passwd
sed -i 's/pi/myuser/g' /etc/shadow
sed -i 's/pi/myuser/g' /etc/group
# Update the sudoers file to reflect the name-change
sed -i /etc/sudoers 's/pi/myuser/g'
# Move the user home directory to the new location (the UID stays the same, we don't need to run chown)
mv -i /home/pi /home/newuser
然后使用sudo
如下方式运行它:
sudo update_user.sh
笔记:我认为拥有一个包含 root 密码的 shell 脚本可能不是一个好主意。您可能需要考虑不是像这样以编程方式设置 root 密码。
我原来的解决方案如下。
也许我遗漏了一些东西,但我不确定为什么你必须反复重新启动设备。您应该能够进行所需的所有更改,然后在完成后重新启动。尝试以下方法怎么样:
# Become the root user (if you aren't already)
sudo su
# Set the password for the root user
passwd
# Change the login name of the "pi" user to "myuser"
usermod -l myuser pi
# Update the "myuser" home directory
usermod -m -d /home/myuser myuser
# Edit the file /etc/sudoers and change pi to myuser
visudo
# Reboot the system
reboot
这是对您正在使用的命令列表的轻微更改:sudo su
首先,执行所有命令,并且仅在完成后重新启动。目前的形式仍然无法编写脚本,因为它需要用户交互 - 特别是设置密码和编辑 sudoers 文件。如果您确实希望能够在无人值守的情况下运行此任务,那么您需要自动执行这两项任务。如果这是您的目标,那么您可能需要修改脚本以使其看起来更像以下内容:
# Become the root user (if you aren't already)
sudo su
# Set the password for the root user
echo "root:<PASSWORD>" | chpasswd
# Change the login name of the "pi" user to "myuser"
usermod -l myuser pi
# Update the "myuser" home directory
usermod -m -d /home/myuser myuser
# Edit the file /etc/sudoers and change pi to myuser (CAREFUL!)
sed -i /etc/sudoers 's/pi/myuser/g'
# Reboot the system
reboot
有关以编程方式设置或更改密码的进一步讨论,请参阅这篇文章: