If you want to add a user to a virtual machine without logging into it or change the password of root or any other user, you can use virt-customize.
The virt-customize command-line tool can be used to customize a virtual machine. For example, by installing packages and editing configuration files.
To use virt-customize, the guest virtual machine must be offline, so you must shut it down before running the commands. Note that virt-customize modifies the guest or disk image in place without making a copy of it. If you want to preserve the existing contents of the guest virtual machine, you must snapshot, copy or clone the disk first.
To install virt-customize, run one of the following commands:
sudo yum install libguestfs-tools-c
sudo apt-get install libguestfs-tools
Please follow the below-mentioned steps:
a. Add a new user:
virt-customize -a centos.img --run-command "adduser user1" virt-customize -a centos.img --ssh-inject user1:string:<YOUR PUBLICKEY STRING HERE>
Now you can login with user1 and public-key
If you want passwordless sudo access execute the following:
virt-customize -a centos.img --run-command "echo 'user1 ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers.d/user1-sudo"
b. Change root password:
virt-customize -a centos.img --root-password password:mypass
You can login to the VM with root/mypass
c. Change password of non-root user:
virt-customize -a centos.img --password user1:password:mypass2
You can login to the VM with user1/mypass2