Change the password of the KVM virtual machine root

Today, I am using qemu-kvm to install a virtual machine. Because there is already an image file of the virtual machine (in qcow2 format), it is very simple to create a virtual machine. Just start it from the image with the following command.

[plain]  view plain copy  
  1. qemu-kvm -cpu host -smp 2 -name cenos6 -m 2048 -drive file=/var/tmp/CentOS---6.6-64bit---2015-01-29-a.qcow2,if=ide,media=disk,format=qcow2 -boot order=c -usbdevice tablet -nographic  
But the tragedy is that I forgot the password of the root user in the image, so after the system is started, I can't log in to the system, and I can only stare blankly. After google for a long time, I finally found a solution, and now I want to share it with you.

1) Mount the image file in qcow2 format, which requires the help of the qemu-nbd command, as follows:

[plain]  view plain copy  
  1. // load nbd module first  
  2. $ modprobe nbd max_part=8  
[plain]  view plain copy  
  1. //Create a connection associated with the nbd device for the image file  
  2. $ qemu-nbd -c /dev/nbd0 CentOS---6.6-64bit---2015-01-29-a.qcow2  
[plain]  view plain copy  
  1. //Check whether the connection is successfully created, if there is an nbd0p1 device, it is successful  
  2. $ ls -l /dev/nbd0*  
[plain]  view plain copy  
  1. //mount image file  
  2. $ mount /dev/nbd0p1 /mnt/img  
If there are files in the /mnt/img/ directory, it means that it has been successful.

2) Use chroot to change root's password.
Now that we have mounted the OS image, we can do whatever we want.

[plain]  view plain copy  
  1. //Log in to the shell of the virtual machine  
  2. $ /mnt/img/bin/sh  
  3. sh-4.1#  
[plain]  view plain copy  
  1. </pre><pre name="code" class="html">//chroot first, then change root's password  
  2. sh-4.1# chroot /mnt/img/  
  3. [root@server-185 /]# passwd root  
  4. Changing password for user root.  
  5. New password:  
  6. Retype new password:  
  7. passwd: all authentication tokens updated successfully.  

By now, the password has been changed and it is time to log back into the virtual machine. But, don't forget to umount image, delete nbd connection and unload nbd module.

3) Aftermath work

$ umount /mnt/img

$ qemu-nbd -d /dev/nbd0

[plain]  view plain copy  
  1. $ rmmod nbd  

Be sure to develop a good habit of using up and releasing.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326289501&siteId=291194637