This brief guide explains the right way to edit /etc/passwd and /etc/group files using vipw and vigr commands in Linux. Why can't we just edit them with a text editor like Vi or nano and be done with it? You might wonder! Well, picture this scenario. The /etc/passwd file is currently being edited by the root user using Vi or some other text editors. At the same time, another user tries to change his password while the root user editing the /etc/passwd file. So the password change may not be updated in this file and the user might not able to log in. This is where vipw and vigr commands comes in rescue.
The vipw and vigr commands are used to safely edit the files /etc/passwd and /etc/group in Linux systems. They will put appropriate locks when editing /etc/passwd and /etc/group files to prevent other users from making any changes in them and avoid file corruption. When you run those commands with -s flag, they will edit the shadow versions of those files, i.e. /etc/shadow and /etc/gshadow, respectively.
The Right Way To Edit /etc/passwd and /etc/group files using vipw and vigr commands
To safely edit /etc/password file, simply run:
$ sudo vipw
To safely edit /etc/group file, run:
$ sudo vigr
Now vipw and vigr commands will lock the /etc/passwd and /etc/group files and prevent others users from making any changes.
To verify this, open two Terminal windows. Run "sudo vipw" in one window and try to change the password of an user in another window.
The password will not get updated until you exit the vipw command. So the other users may not inadvertently or intentionally make any changes in /etc/passwd file while you're editing them as root. Once the /etc/passwd is closed, the password will be updated successfully.
You can also login as normal user and try to change the the user's password in another Terminal window. The password will not change until you close the vipw command.
You can't even create any new users while editing /etc/passwd file vipw command.
$ sudo useradd kumar useradd: cannot lock /etc/passwd; try again later.
Similarly, to edit shadow versions of those files, i.e. /etc/shadow and /etc/gshadow, use -s flag.
$ sudo vipw -s
$ sudo vigr -s
The other supported options by the vipw and vipr commands are:
-g, --group Edit group database. -h, --help Display help message and exit. -p, --passwd Edit passwd database. -q, --quiet Quiet mode. -R, --root CHROOT_DIR Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory. -s, --shadow Edit shadow or gshadow database
For more details, refer man pages.
$ man vipw
$ man vigr
Hope this helps.