使用命令接口对KVM虚拟机进行简单的管理

简介:

一 KVM对用户提供的命令主要在/usr/bin/目录下

[root@centoskvm ~]# ls /usr/bin/vir*

/usr/bin/virsh        /usr/bin/virt-manager

/usr/bin/virt-clone      /usr/bin/virt-pki-validate

/usr/bin/virt-convert     /usr/bin/virt-top

/usr/bin/virt-host-validate  /usr/bin/virt-viewer

/usr/bin/virt-image      /usr/bin/virt-who

/usr/bin/virt-install     /usr/bin/virt-xml-validate


[root@centoskvm ~]# ls /usr/bin/qe*

/usr/bin/qemu-img  /usr/bin/qemu-io  /usr/bin/qemu-kvm


常用的命令有:virsh,virsh-install,virsh-clone,virsh-convert,virsh-image,qemu-img和qemu-kvm



二 virsh常用的管理命令

使用xml配置文件开启虚拟机

[root@centoskvm kvm]# virsh create 1003vm.xml 

Domain 1003vm created from 1003vm.xml


列出虚拟机:

[root@centoskvm kvm]# virsh list

 Id   Name              State

----------------------------------------------------

 13   1003vm             running

Id和Name可以作为控制虚拟机的主键


列出域中全部的虚拟机:

[root@centoskvm kvm]# virsh list --all

 Id   Name              State

----------------------------------------------------

 13   1003vm             running

 -   1001vm             shut off


关闭虚拟机:

[root@centoskvm kvm]# virsh shutdown 13

或者

[root@centoskvm kvm]# virsh shutdown  1003vm


重启虚拟机:

[root@centoskvm kvm]#virsh reboot 13

或者

[root@centoskvm kvm]# virsh reboot  1003vm


强制关闭虚拟机:(不建议使用,这样容易破坏虚拟机的文件系统)

[root@centoskvm kvm]#virsh destroy 13

或者

[root@centoskvm kvm]# virsh destroy 1003vm


添加虚拟机:

[root@centoskvm kvm]#virsh define /home/kvm/1002vm.xml #根据主机配置文档添加虚拟机

Domain 1002vm defined from /home/kvm/1002vm.xml

[root@centoskvm kvm]# virsh list --all

 Id   Name              State

----------------------------------------------------

 13   1003vm             running

 -   1001vm             shut off

 -   1002vm             shut off  #1002vm已被添加到域中


移除虚拟机:

[root@centoskvm kvm]#virsh undefine 1002vm 

Domain 1002vm has been undefined

[root@centoskvm kvm]# virsh list --all

 Id   Name              State

----------------------------------------------------

 13   1003vm             running

 -   1001vm             shut off

#1002vm已被从域中移除



导出虚拟机的配置信息xml文件

[root@centoskvm kvm]# virsh dumpxml 1003vm > ~/1003vm.xml

[root@centoskvm kvm]# cat ~/1003vm.xml 

<domaintype='kvm' id='13'>

 <name>1003vm</name>

 <uuid>323286df-2fa9-9864-4754-b51df76bd336</uuid>

 <memory unit='KiB'>2097152</memory>

 <currentMemory unit='KiB'>2097152</currentMemory>

 <vcpu placement='static'>2</vcpu>

 <os>

  <type arch='x86_64' machine='rhel6.2.0'>hvm</type>

  <boot dev='hd'/>

 </os>

 <features>

  <acpi/>

  <apic/>

  <pae/>

 </features>

 <clock offset='utc'/>

 <on_poweroff>destroy</on_poweroff>

 <on_reboot>restart</on_reboot>

 <on_crash>restart</on_crash>

 <devices>

  <emulator>/usr/libexec/qemu-kvm</emulator>

  <disk type='file' device='disk'>

   <driver name='qemu' type='raw' cache='none'/>

   <source file='/home/kvm/1003vm.img'/>

   <target dev='vda' bus='virtio'/>

   <shareable/>

   <alias name='virtio-disk0'/>

   <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>

  </disk>

  <controller type='usb' index='0'>

   <alias name='usb0'/>

   <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x2'/>

  </controller>

  <interface type='bridge'>

   <mac address='52:54:00:88:f8:03'/>

   <source bridge='br0'/>

   <target dev='vnet0'/>

   <model type='virtio'/>

   <alias name='net0'/>

   <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>

  </interface>

  <serial type='pty'>

   <source path='/dev/pts/1'/>

   <target port='0'/>

   <alias name='serial0'/>

  </serial>

  <console type='pty' tty='/dev/pts/1'>

   <source path='/dev/pts/1'/>

   <target type='serial' port='0'/>

   <alias name='serial0'/>

  </console>

  <input type='tablet' bus='usb'>

   <alias name='input0'/>

  </input>

  <input type='mouse' bus='ps2'/>

  <graphics type='vnc' port='5900' listen='127.0.0.1'>

   <listen type='address' address='127.0.0.1'/>

  </graphics>

  <video>

   <model type='cirrus' vram='9216' heads='1'/>

   <alias name='video0'/>

   <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>

  </video>

  <memballoon model='virtio'>

   <alias name='balloon0'/>

   <address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/>

  </memballoon>

 </devices>

 <seclabel type='dynamic' model='selinux' relabel='yes'>

  <label>system_u:system_r:svirt_t:s0:c97,c672</label>

  <imagelabel>system_u:object_r:svirt_image_t:s0:c97,c672</imagelabel>

 </seclabel>

</domain>



也可以使用xml配置来启动虚拟机:

[root@centoskvm kvm]# virsh shutdown 1003vm

[root@centoskvm kvm]# virsh list --all

 Id   Name              State

----------------------------------------------------

 -   1003vm              shut off

 -   1001vm             shut off


[root@centoskvm kvm]# virsh create ~/1003vm.xml

[root@centoskvm kvm]# virsh list --all

 Id   Name              State

----------------------------------------------------

 14   1003vm             running

 -   1001vm             shut off





三 使用命令接口创建虚拟机

创建镜像文件:

[root@centoskvm kvm]# qemu-img create -f qcow2 /home/kvm/1001vm.img 16G

查看img文件信息:

[root@centoskvm img]# qemu-img info 1001vm.img 

image: 1001vm.img

file format: qcow2

virtual size: 16G (17179869184 bytes)

disk size: 5.9G

cluster_size: 65536


其中参数 -f 表示镜像文件的格式[qcow2],具体介绍如下:

[root@centoskvm img]# qemu-img create --help

create: invalid option -- '-'

qemu-img version 0.12.1, Copyright (c) 2004-2008 Fabrice Bellard

usage: qemu-img command [command options]

QEMU disk image utility


Command syntax:

 check [-f fmt] filename

 create [-f fmt] [-o options] filename [size]

 commit [-f fmt] [-t cache] filename

 convert [-c] [-p] [-f fmt] [-t cache] [-O output_fmt] [-o options] [-S sparse_size] filename [filename2 [...]] output_filename

 info [-f fmt] filename

 snapshot [-l | -a snapshot | -c snapshot | -d snapshot] filename

 rebase [-f fmt] [-t cache] [-p] [-u] -b backing_file [-F backing_fmt] filename

 resize filename [+ | -]size


Command parameters:

 'filename' is a disk image filename

 'fmt' is the disk image format. It is guessed automatically in most cases

 'cache' is the cache mode used to write the output disk image, the valid

  options are: 'none', 'writeback' (default), 'writethrough' and 'unsafe'

 'size' is the disk image size in bytes. Optional suffixes

  'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M)

  and T (terabyte, 1024G) are supported. 'b' is ignored.

 'output_filename' is the destination disk image filename

 'output_fmt' is the destination format

 'options' is a comma separated list of format specific options in a

  name=value format. Use -o ? for an overview of the options supported by the

  used format

 '-c' indicates that target image must be compressed (qcow format only)

 '-u' enables unsafe rebasing. It is assumed that old and new backing file

    match exactly. The image doesn't need a working backing file before

    rebasing in this case (useful for renaming the backing file)

 '-h' with or without a command shows this help and lists the supported formats

 '-p' show progress of command (only certain commands)

 '-S' indicates the consecutive number of bytes that must contain only zeros

    for qemu-img to create a sparse image during conversion


Parameters to snapshot subcommand:

 'snapshot' is the name of the snapshot to create, apply or delete

 '-a' applies a snapshot (revert disk to saved state)

 '-c' creates a snapshot

 '-d' deletes a snapshot

 '-l' lists all snapshots in the given image


Supported formats: raw cow qcow vdi vmdk cloop dmg bochs vpc vvfat qcow2 qed parallels nbd blkdebug host_cdrom host_floppy host_device file


常用的格式为raw和qcow2,推荐使用qcow2格式。

raw格式:可以简单、容易地导出到其它模拟器中,但是立即分配占用空间大。

qcow2格式:是qcow格式的升级版本,是目前最万能的格式。使用它可获得较小映像,也是虚拟池一直在使用的镜像格式,支持镜像快照,方便的恢复管理。



安装虚拟机客户操作系统:

[root@centoskvm img]#virt-install --name 1001vm --ram=1024 --arch=x86_64 --vcpus=2 --check-cpu --os-type=linux --os-variant='rhel6' -c /home/mysoft/os/CentOS-6.2-x86_64-bin-DVD1.iso --disk path=/home/img/1001vm.img,device=disk,bus=virtio,format=qcow2 --bridge=br0 --noautoconsole --vnc --vncport=5902 --vnclisten=0.0.0.0

[root@centoskvm img]# virt-install --help

Usage: virt-install --name NAME --ram RAM STORAGE INSTALL [options]


Options:

 --version       show program's version number and exit

 -h, --help       show this help message and exit

 --connect=URI     Connect to hypervisor with libvirt URI


 General Options:

  -n NAME, --name=NAME

            Name of the guest instance

  -r MEMORY, --ram=MEMORY

            Memory to allocate for guest instance in megabytes

  --vcpus=VCPUS    Number of vcpus to configure for your guest. Ex:

            --vcpus 5

            --vcpus 5,maxcpus=10

            --vcpus sockets=2,cores=4,threads=2

  --cpuset=CPUSET   Set which physical CPUs domain can use.

  --cpu=CPU      CPU model and features. Ex: --cpu coreduo,+x2apic

  --description=DESCRIPTION

            Human readable description of the VM to store in the

            generated XML.

  --security=SECURITY

            Set domain security driver configuration.

  --numatune=NUMATUNE

            Tune NUMA policy for the domain process.


 Installation Method Options:

  -c CDROM, --cdrom=CDROM

            CD-ROM installation media

  -l LOCATION, --location=LOCATION

            Installation source (eg, nfs:host:/path,

            http://host/path, ftp://host/path)

  --pxe        Boot from the network using the PXE protocol

  --import       Build guest around an existing disk image

  --init=INIT     Path to init binary for container guest. Ex:

            --init /path/to/app (to contain an application)

            --init /sbin/init (for a full OS container)

  --livecd       Treat the CD-ROM media as a Live CD

  -x EXTRA, --extra-args=EXTRA

            Additional arguments to pass to the install kernel

            booted from --location

  --initrd-inject=INITRD_INJECTIONS

            Add given file to root of initrd from --location

  --os-type=DISTRO_TYPE

            The OS type being installed, e.g. 'linux', 'unix',

            'windows'

  --os-variant=DISTRO_VARIANT

            The OS variant being installed guests, e.g. 'fedora6',

            'rhel5', 'solaris10', 'win2k'

  --boot=BOOTOPTS   Optionally configure post-install boot order, menu,

            permanent kernel boot, etc.


 Storage Configuration:

  --disk=DISKOPTS   Specify storage with various options. Ex.

            --disk path=/my/existing/disk

            --disk path=/my/new/disk,size=5 (in gigabytes)

            --disk vol=poolname:volname,device=cdrom,bus=scsi,...

  --nodisks      Don't set up any disks for the guest.

  --filesystem=FILESYSTEMS

            Pass host directory to the guest. Ex:

            --filesystem /my/source/dir,/dir/in/guest

            --filesystem template_name,/,type=template


 Networking Configuration:

  -w NETWORK, --network=NETWORK

            Configure a guest network interface. Ex:

            --network bridge=mybr0

            --network network=my_libvirt_virtual_net

            --network network=mynet,model=virtio,mac=00:11...

  --nonetworks     Don't create network interfaces for the guest.


 Graphics Configuration:

  --graphics=GRAPHICS

            Configure guest display settings. Ex:

            --graphics vnc

            --graphics spice,port=5901,tlsport=5902

            --graphics none

            --graphics vnc,password=foobar,port=5910,keymap=ja

  --noautoconsole   Don't automatically try to connect to the guest

            console


 Device Options:

  --serial=SERIALS   Configure a guest serial device

  --parallel=PARALLELS

            Configure a guest parallel device

  --channel=CHANNELS  Configure a guest communication channel

  --console=CONSOLES  Configure a text console connection between the guest

            and host

  --host-device=HOSTDEVS

            Configure physical host devices attached to the guest

  --soundhw=SOUNDHW  Configure guest sound device emulation

  --watchdog=WATCHDOG

            Configure a guest watchdog device

  --video=VIDEO    Configure guest video hardware.

  --smartcard=SMARTCARD

            Configure a guest smartcard device. Ex:

            --smartcard mode=passthrough


 Virtualization Platform Options:

  -v, --hvm      This guest should be a fully virtualized guest

  -p, --paravirt    This guest should be a paravirtualized guest

  --container     This guest should be a container guest

  --virt-type=HV_TYPE

            Hypervisor name to use (kvm, qemu, xen, ...)

  --arch=ARCH     The CPU architecture to simulate

  --machine=MACHINE  The machine type to emulate

  --noapic       Disables APIC for fully virtualized guest (overrides

            value in os-type/os-variant db)

  --noacpi       Disables ACPI for fully virtualized guest (overrides

            value in os-type/os-variant db)

  -u UUID, --uuid=UUID

            UUID for the guest.


 Miscellaneous Options:

  --autostart     Have domain autostart on host boot up.

  --print-xml     Print the generated domain XML rather than define the

            guest.

  --print-step=XMLSTEP

            Print XML of a specific install step (1, 2, 3, all)

            rather than define the guest.

  --noreboot      Don't boot guest after completing install.

  --wait=WAIT     Time to wait (in minutes)

  --dry-run      Run through install process, but do not create devices

            or define the guest.

  --force       Forces 'yes' for any applicable prompts, terminates

            for all others

  -q, --quiet     Suppress non-error output

  --prompt       Request user input for ambiguous situations or

            required options.

  -d, --debug     Print debugging information



四 使用console登录虚拟机

[root@centoskvm img]#virsh list

 Id   Name              State

----------------------------------------------------

 13   1003vm             running

[root@centoskvm img]# virshconsole 13

若出现无法从console登录的情况,会卡在

Escape character is ^]”处无法继续。请从桌面以root登录做如下操作:

1、添加ttyS0的安全许可,允许root登录:

[root@1001vm img]# echo "ttyS0" >> /etc/securetty

[root@1001vm ~]# cat /etc/securetty 

console

vc/1

vc/2

。。。。。。

vc/10

vc/11

tty1

tty2

。。。。。。

tty11

ttyS0

2、在/etc/grub.conf文件中为内核添加参数:console=ttyS0

[root@1001vm ~]# cat /etc/grub.conf 

# grub.conf generated by anaconda

#

# Note that you do not have to rerun grub after making changes to this file

# NOTICE:  You have a /boot partition.  This means that

#      all kernel and initrd paths are relative to /boot/, eg.

#      root (hd0,0)

#      kernel /vmlinuz-version ro root=/dev/mapper/vg_1001vm-lv_root

#      initrd /initrd-[generic-]version.img

#boot=/dev/vda

default=0

timeout=5

splashimage=(hd0,0)/grub/splash.xpm.gz

hiddenmenu

title CentOS (2.6.32-220.el6.x86_64)

root (hd0,0)

kernel /vmlinuz-2.6.32-220.el6.x86_64 ro root=/dev/mapper/vg_1001vm-lv_root rd_NO_LUKS rd_LVM_LV=vg_1001vm/lv_root LANG=en_US.UTF-8 rd_NO_MD quiet SYSFONT=latarcyrheb-sun16 rhgb crashkernel=auto rd_LVM_LV=vg_1001vm/lv_swap  KEYBOARDTYPE=pc KEYTABLE=us rd_NO_DM console=ttyS0

initrd /initramfs-2.6.32-220.el6.x86_64.img


3、在/etc/inittab中添加agetty:

S0:12345:respawn:/sbin/agetty ttyS0 115200

[root@1001vm ~]# cat /etc/inittab

# inittab is only used by upstart for the default runlevel.

#。。。。。。。。。。。。。

#。。。。。。。。。。。。。

id:5:initdefault:

S0:12345:respawn:/sbin/agetty ttyS0 115200


4、重启客户虚拟机:

[root@1001vm img]# reboot


此时,再次尝试console命令可以正常使用:

[root@centoskvm img]# virsh console 1001vm

Connected to domain 1001vm

Escape character is ^]

[  OK  ]

Setting hostname 1001vm:  [  OK  ]

Setting up Logical Volume Management:  2 logical volume(s) in volume group "vg_1001vm" now active

[  OK  ]

。。。。。。。。。。。。。。。。。。。。。。。。。。。。

。。。。。。。。。。。。。。。。。。。。。。。。。。。。

Starting atd: [  OK  ]

Starting up CIM server: [  OK  ]


CentOS release 6.2 (Final)

Kernel 2.6.32-220.el6.x86_64 on an x86_64


1001vm login: root

Password: 

[root@1001vm ~]#

本文转自silence博客51CTO博客,原文链接http://blog.51cto.com/silencezone/1944578如需转载请自行联系原作者

a120518129
相关文章
|
1月前
|
算法 虚拟化 C++
VMware虚拟机无法自适应和拖拽复制粘贴和共享目录问题
VMware虚拟机无法自适应和拖拽复制粘贴和共享目录问题
202 0
|
24天前
|
存储 SQL 数据挖掘
服务器数据恢复—误删除VMware虚拟机vmdk文件的数据恢复案例
服务器数据恢复环境: 某大厂PS4000服务器,服务器上部署VMware ESXi虚拟化平台。 服务器故障: 机房断电,重启后服务器中的某台虚拟机不能正常启动。管理员查看虚拟机配置文件,发现无法启动的虚拟机的配置文件除了磁盘文件以外其他配置文件全部丢失,xxx-flat.vmdk磁盘文件和xxx-000001-delta.vmdk快照文件还存在。联系VMware原厂工程师进行诊断,VMware原厂工程师尝试新建一个虚拟机,但发现存储空间不足,于是将故障虚拟机下的xxx-flat.vmdk磁盘文件删除了。VMware工程师重新建了一个虚拟机,分配了固定大小的虚拟磁盘,为虚拟机安装了Window
服务器数据恢复—误删除VMware虚拟机vmdk文件的数据恢复案例
|
3天前
|
存储 IDE 开发工具
【读书笔记】 玩转虚拟机基于Vmware+Windows 虚拟化技术
【读书笔记】 玩转虚拟机基于Vmware+Windows 虚拟化技术
|
4天前
|
虚拟化 UED
vmware-17虚拟机安装教程(保姆级,包含图文讲解,不需注册账户)
vmware-17虚拟机安装教程(保姆级,包含图文讲解,不需注册账户)
|
15天前
|
Linux 调度 虚拟化
Linux系统——初识Linux、虚拟机介绍、VMware WorkStation安装、在VMware上安装Linux
Linux系统——初识Linux、虚拟机介绍、VMware WorkStation安装、在VMware上安装Linux
53 4
|
26天前
|
Shell Linux 开发工具
Vmware 虚拟机挂起恢复后发现无法 Ping 通,无法连接到主机
在Linux主机上,以`root`用户停止NetworkManager服务并重启网络: ```shell systemctl stop NetworkManager systemctl restart network ``` 或修改网卡配置文件`ifcfg-ens33`,添加`NM_CONTROLLED=&quot;no&quot;`,然后重启`network`服务: ```shell vim /etc/sysconfig/network-scripts/ifcfg-ens33 systemctl restart network ```