1. 程式人生 > >虛擬化技術之kvm管理工具virsh常用基礎命令(一)

虛擬化技術之kvm管理工具virsh常用基礎命令(一)

  在上一篇部落格中,我們瞭解了KVM基礎架構和部署以及圖形管理工具virt-manager安裝虛擬機器的過程,回顧請參考https://www.cnblogs.com/qiuhom-1874/p/13499801.html;今天我們來聊一下kvm的命令列工具virsh;virsh工具功能非常豐富,它可以全生命週期的管理kvm;比如建立虛擬機器,檢視虛擬機器,動態熱插拔硬碟,給虛擬機器做快照,遷移、啟動、停止、掛起、暫停、刪除虛擬機器等等操作;

  一、KVM工具棧

  提示:上圖主要描述了kvm的主要工具棧,從大的類別可以分為libvirt和qemu這兩大類,其中libvirt中分virtual machine manager和virsh,virtual machine manager中的virt-manager是基於圖形介面的管理,其他都是可以在命令列直接使用命令來管理虛擬機器;virsh是基於終端命令列管理;兩者都是通過libvirt連線至libvirtd進行管理;而對於qemu來說,它管理虛擬機器上直接呼叫kvm核心中模組的API進行管理;

  二、virsh工具的使用說明

  1、檢視virsh命令幫助資訊

[root@node1 ~]# virsh help
分組的命令:

 Domain Management (help keyword 'domain'):
    attach-device                  從一個XML檔案附加裝置
    attach-disk                    附加磁碟裝置
    attach-interface               獲得網路介面
    autostart                      自動開始一個域
    blkdeviotune                   設定或者查詢塊裝置 I/O 調節引數。
    blkiotune                      獲取或者數值 blkio 引數
    blockcommit                    啟動塊提交操作。
    blockcopy                      啟動塊複製操作。
    blockjob                       管理活躍塊操作
    blockpull                      使用其後端映像填充磁碟。
    blockresize                    創新定義域塊裝置大小
    change-media                   更改 CD 介質或者軟盤驅動器
    console                        連線到客戶會話
    cpu-stats                      顯示域 cpu 統計資料
    create                         從一個 XML 檔案建立一個域
    define                         從一個 XML 檔案定義(但不開始)一個域
    desc                           顯示或者設定域描述或者標題
    destroy                        銷燬(停止)域
    detach-device                  從一個 XML 檔案分離裝置
    detach-device-alias            detach device from an alias
    detach-disk                    分離磁碟裝置
    detach-interface               分離網路介面
    domdisplay                     域顯示連線 URI
    domfsfreeze                    Freeze domain's mounted filesystems.
    domfsthaw                      Thaw domain's mounted filesystems.
    domfsinfo                      Get information of domain's mounted filesystems.
    domfstrim                      在域掛載的檔案系統中呼叫 fstrim。
    domhostname                    輸出域主機名
    domid                          把一個域名或 UUID 轉換為域 id
    domif-setlink                  設定虛擬介面的連結狀態
    domiftune                      獲取/設定虛擬介面引數
    domjobabort                    忽略活躍域任務
    domjobinfo                     域任務資訊
    domname                        將域 id 或 UUID 轉換為域名
    domrename                      rename a domain
    dompmsuspend                   使用電源管理功能掛起域
    dompmwakeup                    從 pmsuspended 狀態喚醒域
    domuuid                        把一個域名或 id 轉換為域 UUID
    domxml-from-native             將原始配置轉換為域 XML
    domxml-to-native               將域 XML 轉換為原始配置
    dump                           把一個域的核心 dump 到一個檔案中以方便分析
    dumpxml                        XML 中的域資訊
    edit                           編輯某個域的 XML 配置
    event                          Domain Events
    inject-nmi                     在虛擬機器中輸入 NMI
    iothreadinfo                   view domain IOThreads
    iothreadpin                    control domain IOThread affinity
    iothreadadd                    add an IOThread to the guest domain
    iothreaddel                    delete an IOThread from the guest domain
    send-key                       向虛擬機發送序列號
    send-process-signal            向程序傳送訊號
    lxc-enter-namespace            LXC 虛擬機器進入名稱空間
    managedsave                    管理域狀態的儲存
    managedsave-remove             刪除域的管理儲存
    managedsave-edit               edit XML for a domain's managed save state file
    managedsave-dumpxml            Domain information of managed save state file in XML
    managedsave-define             redefine the XML for a domain's managed save state file
    memtune                        獲取或者數值記憶體引數
    perf                           Get or set perf event
    metadata                       show or set domain's custom XML metadata
    migrate                        將域遷移到另一個主機中
    migrate-setmaxdowntime         設定最大可耐受故障時間
    migrate-getmaxdowntime         get maximum tolerable downtime
    migrate-compcache              獲取/設定壓縮快取大小
    migrate-setspeed               設定遷移頻寬的最大值
    migrate-getspeed               獲取最長遷移頻寬
    migrate-postcopy               Switch running migration from pre-copy to post-copy
    numatune                       獲取或者數值 numa 引數
    qemu-attach                    QEMU 附加
    qemu-monitor-command           QEMU 監控程式命令
    qemu-monitor-event             QEMU Monitor Events
    qemu-agent-command             QEMU 虛擬機器代理命令
    reboot                         重新啟動一個域
    reset                          重新設定域
    restore                        從一個存在一個檔案中的狀態恢復一個域
    resume                         重新恢復一個域
    save                           把一個域的狀態儲存到一個檔案
    save-image-define              為域的儲存狀態檔案重新定義 XML
    save-image-dumpxml             在 XML 中儲存狀態域資訊
    save-image-edit                為域儲存狀態檔案編輯 XML
    schedinfo                      顯示/設定日程安排變數
    screenshot                     提取當前域控制檯快照並儲存到檔案中
    set-lifecycle-action           change lifecycle actions
    set-user-password              set the user password inside the domain
    setmaxmem                      改變最大記憶體限制值
    setmem                         改變記憶體的分配
    setvcpus                       改變虛擬 CPU 的號
    shutdown                       關閉一個域
    start                          開始一個(以前定義的)非活躍的域
    suspend                        掛起一個域
    ttyconsole                     tty 控制檯
    undefine                       取消定義一個域
    update-device                  從 XML 檔案中關係裝置
    vcpucount                      域 vcpu 計數
    vcpuinfo                       詳細的域 vcpu 資訊
    vcpupin                        控制或者查詢域 vcpu 親和性
    emulatorpin                    控制火車查詢域模擬器親和性
    vncdisplay                     vnc 顯示
    guestvcpus                     query or modify state of vcpu in the guest (via agent)
    setvcpu                        attach/detach vcpu or groups of threads
    domblkthreshold                set the threshold for block-threshold event for a given block device or it's backing chain element

 Domain Monitoring (help keyword 'monitor'):
    domblkerror                    在塊裝置中顯示錯誤
    domblkinfo                     域塊裝置大小資訊
    domblklist                     列出所有域塊
    domblkstat                     獲得域裝置塊狀態
    domcontrol                     域控制介面狀態
    domif-getlink                  獲取虛擬介面連結狀態
    domifaddr                      Get network interfaces' addresses for a running domain
    domiflist                      列出所有域虛擬介面
    domifstat                      獲得域網路介面狀態
    dominfo                        域資訊
    dommemstat                     獲取域的記憶體統計
    domstate                       域狀態
    domstats                       get statistics about one or multiple domains
    domtime                        domain time
    list                           列出域

 Host and Hypervisor (help keyword 'host'):
    allocpages                     Manipulate pages pool size
    capabilities                   效能
    cpu-baseline                   計算基線 CPU
    cpu-compare                    使用 XML 檔案中描述的 CPU 與主機 CPU 進行對比
    cpu-models                     CPU models
    domcapabilities                domain capabilities
    freecell                       NUMA可用記憶體
    freepages                      NUMA free pages
    hostname                       列印管理程式主機名
    hypervisor-cpu-baseline        compute baseline CPU usable by a specific hypervisor
    hypervisor-cpu-compare         compare a CPU with the CPU created by a hypervisor on the host
    maxvcpus                       連線 vcpu 最大值
    node-memory-tune               獲取或者設定節點記憶體引數
    nodecpumap                     節點 cpu 對映
    nodecpustats                   輸出節點的 cpu 狀統計資料。
    nodeinfo                       節點資訊
    nodememstats                   輸出節點的記憶體狀統計資料。
    nodesuspend                    在給定時間段掛起主機節點
    sysinfo                        輸出 hypervisor sysinfo
    uri                            列印管理程式典型的URI
    version                        顯示版本

 Interface (help keyword 'interface'):
    iface-begin                    生成當前介面設定快照,可在今後用於提交 (iface-commit) 或者恢復 (iface-rollback)
    iface-bridge                   生成橋接裝置併為其附加一個現有網路裝置
    iface-commit                   提交 iface-begin 後的更改並釋放恢復點
    iface-define                   define an inactive persistent physical host interface or modify an existing persistent one from an XML file
    iface-destroy                  刪除物理主機介面(啟用它請執行 "if-down")
    iface-dumpxml                  XML 中的介面資訊
    iface-edit                     為物理主機介面編輯 XML 配置
    iface-list                     物理主機介面列表
    iface-mac                      將介面名稱轉換為介面 MAC 地址
    iface-name                     將介面 MAC 地址轉換為介面名稱
    iface-rollback                 恢復到之前儲存的使用 iface-begin 生成的更改
    iface-start                    啟動物理主機介面(啟用它請執行 "if-up")
    iface-unbridge                 分離其輔助裝置後取消定義橋接裝置
    iface-undefine                 取消定義物理主機介面(從配置中刪除)

 Network Filter (help keyword 'filter'):
    nwfilter-define                使用 XML 檔案定義或者更新網路過濾器
    nwfilter-dumpxml               XML 中的網路過濾器資訊
    nwfilter-edit                  為網路過濾器編輯 XML 配置
    nwfilter-list                  列出網路過濾器
    nwfilter-undefine              取消定義網路過濾器
    nwfilter-binding-create        create a network filter binding from an XML file
    nwfilter-binding-delete        delete a network filter binding
    nwfilter-binding-dumpxml       XML 中的網路過濾器資訊
    nwfilter-binding-list          list network filter bindings

 Networking (help keyword 'network'):
    net-autostart                  自動開始網路
    net-create                     從一個 XML 檔案建立一個網路
    net-define                     define an inactive persistent virtual network or modify an existing persistent one from an XML file
    net-destroy                    銷燬(停止)網路
    net-dhcp-leases                print lease info for a given network
    net-dumpxml                    XML 中的網路資訊
    net-edit                       為網路編輯 XML 配置
    net-event                      Network Events
    net-info                       網路資訊
    net-list                       列出網路
    net-name                       把一個網路UUID 轉換為網路名
    net-start                      開始一個(以前定義的)不活躍的網路
    net-undefine                   undefine a persistent network
    net-update                     更新現有網路配置的部分
    net-uuid                       把一個網路名轉換為網路UUID

 Node Device (help keyword 'nodedev'):
    nodedev-create                 根據節點中的 XML 檔案定義生成裝置
    nodedev-destroy                銷燬(停止)節點中的裝置
    nodedev-detach                 將節點裝置與其裝置驅動程式分離
    nodedev-dumpxml                XML 中的節點裝置詳情
    nodedev-list                   這臺主機中中的列舉裝置
    nodedev-reattach               重新將節點裝置附加到他的裝置驅動程式中
    nodedev-reset                  重置節點裝置
    nodedev-event                  Node Device Events

 Secret (help keyword 'secret'):
    secret-define                  定義或者修改 XML 中的 secret
    secret-dumpxml                 XML 中的 secret 屬性
    secret-event                   Secret Events
    secret-get-value               secret 值輸出
    secret-list                    列出 secret
    secret-set-value               設定 secret 值
    secret-undefine                取消定義 secret

 Snapshot (help keyword 'snapshot'):
    snapshot-create                使用 XML 生成快照
    snapshot-create-as             使用一組引數生成快照
    snapshot-current               獲取或者設定當前快照
    snapshot-delete                刪除域快照
    snapshot-dumpxml               為域快照轉儲 XML
    snapshot-edit                  編輯快照 XML
    snapshot-info                  快照資訊
    snapshot-list                  為域列出快照
    snapshot-parent                獲取快照的上級快照名稱
    snapshot-revert                將域轉換為快照

 Storage Pool (help keyword 'pool'):
    find-storage-pool-sources-as   找到潛在儲存池源
    find-storage-pool-sources      發現潛在儲存池源
    pool-autostart                 自動啟動某個池
    pool-build                     建立池
    pool-create-as                 從一組變數中建立一個池
    pool-create                    從一個 XML 檔案中建立一個池
    pool-define-as                 在一組變數中定義池
    pool-define                    define an inactive persistent storage pool or modify an existing persistent one from an XML file
    pool-delete                    刪除池
    pool-destroy                   銷燬(刪除)池
    pool-dumpxml                   XML 中的池資訊
    pool-edit                      為儲存池編輯 XML 配置
    pool-info                      儲存池資訊
    pool-list                      列出池
    pool-name                      將池 UUID 轉換為池名稱
    pool-refresh                   重新整理池
    pool-start                     啟動一個(以前定義的)非活躍的池
    pool-undefine                  取消定義一個不活躍的池
    pool-uuid                      把一個池名稱轉換為池 UUID
    pool-event                     Storage Pool Events

 Storage Volume (help keyword 'volume'):
    vol-clone                      克隆卷。
    vol-create-as                  從一組變數中建立卷
    vol-create                     從一個 XML 檔案建立一個卷
    vol-create-from                生成卷,使用另一個卷作為輸入。
    vol-delete                     刪除卷
    vol-download                   將卷內容下載到檔案中
    vol-dumpxml                    XML 中的卷資訊
    vol-info                       儲存卷資訊
    vol-key                        為給定金鑰或者路徑返回卷金鑰
    vol-list                       列出卷
    vol-name                       為給定金鑰或者路徑返回卷名
    vol-path                       為給定金鑰或者路徑返回卷路徑
    vol-pool                       為給定金鑰或者路徑返回儲存池
    vol-resize                     創新定義卷大小
    vol-upload                     將檔案內容上傳到卷中
    vol-wipe                       擦除卷

 Virsh itself (help keyword 'virsh'):
    cd                             更改當前目錄
    echo                           echo 引數
    exit                           退出這個非互動式終端
    help                           列印幫助
    pwd                            輸出當前目錄
    quit                           退出這個非互動式終端
    connect                        連線(重新連線)到 hypervisor


[root@node1 ~]# 

  提示:從上面的資訊可以看到,virsh命令大概分了,Domain Management(域管理),Domain Monitoring(域監控)、 Host and Hypervisor(主機及虛擬化)、Interface(網絡卡介面)、Network Filter(網路防火牆)、Networking(網路)、Node Device(節點裝置驅動)、Secret、Snapshot(快照)、Storage Pool(儲存池或儲存策略)、Storage Volume(儲存卷)、Virsh itself(virsh shell自身相關)這些組,如果檢視某一組幫助資訊,我們可以使用virsh help +組名;比如檢視storage volume組相關命令有哪些,可以使用virsh help volume;

[root@node1 ~]# virsh help volume
 Storage Volume (help keyword 'volume'):
    vol-clone                      克隆卷。
    vol-create-as                  從一組變數中建立卷
    vol-create                     從一個 XML 檔案建立一個卷
    vol-create-from                生成卷,使用另一個卷作為輸入。
    vol-delete                     刪除卷
    vol-download                   將卷內容下載到檔案中
    vol-dumpxml                    XML 中的卷資訊
    vol-info                       儲存卷資訊
    vol-key                        為給定金鑰或者路徑返回卷金鑰
    vol-list                       列出卷
    vol-name                       為給定金鑰或者路徑返回卷名
    vol-path                       為給定金鑰或者路徑返回卷路徑
    vol-pool                       為給定金鑰或者路徑返回儲存池
    vol-resize                     創新定義卷大小
    vol-upload                     將檔案內容上傳到卷中
    vol-wipe                       擦除卷

[root@node1 ~]# 

  如果檢視組裡的某個命令的用法,可以使用virsh help +命令即可

[root@node1 ~]# virsh help vol-clone
  NAME
    vol-clone - 克隆卷。

  SYNOPSIS
    vol-clone <vol> <newname> [--pool <string>] [--prealloc-metadata] [--reflink]

  DESCRIPTION
    Clone an existing volume within the parent pool.

  OPTIONS
    [--vol] <string>  卷名稱、金鑰或者路徑
    [--newname] <string>  克隆名稱
    --pool <string>  池名或 uuid
    --prealloc-metadata  預先分配的元資料(用於 qcow2 而不是整個分配)
    --reflink        use btrfs COW lightweight copy


[root@node1 ~]# 

  2、virsh管理虛擬機器相關命令

  virsh list:列出當前宿主機上的虛擬機器列表,預設不加任何選項表示列出當前處於執行狀態的虛擬機器列表(活躍的)

[root@node1 ~]# virsh help list  
  NAME
    list - 列出域

  SYNOPSIS
    list [--inactive] [--all] [--transient] [--persistent] [--with-snapshot] [--without-snapshot] [--state-running] [--state-paused] [--state-shutoff] [--state-other] [--autostart] [--no-autostart] [--with-managed-save] [--without-managed-save] [--uuid] [--name] [--table] [--managed-save] [--title]

  DESCRIPTION
    返回域列表

  OPTIONS
    --inactive       列出不活躍的域
    --all            不活躍和活躍的域列表
    --transient      列出臨時域
    --persistent     列出持久域
    --with-snapshot  列出現有快照的域
    --without-snapshot  列出沒有快照的域
    --state-running  執行狀態的域列表
    --state-paused   列出暫停狀態的域
    --state-shutoff  列出關閉狀態的域
    --state-other    列出其他狀態的域
    --autostart      列出啟用 autostart 的域
    --no-autostart   列出禁用 autostart 的域
    --with-managed-save  列出有管理的儲存狀態的域
    --without-managed-save  列出沒有管理的儲存狀態的域
    --uuid           只列出 uuid
    --name           只列出域名
    --table          列出表格(預設)
    --managed-save   標記有管理的儲存狀態的域
    --title          show domain title


[root@node1 ~]# virsh list
 Id    名稱                         狀態
----------------------------------------------------

[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 -     centos7.0                      關閉

[root@node1 ~]#

  virsh create:從一個 XML 檔案建立一個域(虛擬機器)

[root@node1 ~]# virsh help create
  NAME
    create - 從一個 XML 檔案建立一個域

  SYNOPSIS
    create <file> [--console] [--paused] [--autodestroy] [--pass-fds <string>] [--validate]

  DESCRIPTION
    建立一個域

  OPTIONS
    [--file] <string>  檔案包括一個 XML 域描述
    --console        建立後附加到控制檯
    --paused         生成後讓虛擬機器保持暫停狀態
    --autodestroy    virsh 斷開連線時自動銷燬虛擬機器
    --pass-fds <string>  向虛擬機器傳遞檔案描述符 N、M......
    --validate       validate the XML against the schema


[root@node1 ~]# 

  virsh define:從指定配置檔案中建立虛擬,但不執行,create是建立並執行;

[root@node1 ~]# virsh help define 
  NAME
    define - 從一個 XML 檔案定義(但不開始)一個域

  SYNOPSIS
    define <file> [--validate]

  DESCRIPTION
    定義一個域。

  OPTIONS
    [--file] <string>  檔案包括一個 XML 域描述
    --validate       validate the XML against the schema


[root@node1 ~]# 

  示例:複製centos7的配置檔案,修改裡面的個別引數,用virsh create 建立一個虛擬機器

[root@node1 ~]# cd /etc/libvirt/qemu/
[root@node1 qemu]# ls
c1.xml  centos7.0.xml  networks  
[root@node1 qemu]# diff centos7.0.xml c1.xml 
9,10c9
<   <name>centos7.0</name>
<   <uuid>56a1ecab-ef53-42f8-b7eb-6b4019ea3ee4</uuid>
---
>   <name>c1</name>
41c40
<       <source file='/var/lib/libvirt/images/centos7.0.qcow2'/>
---
>       <source file='/kvm/images/c1.qcow2'/>
74c73
<       <mac address='52:54:00:e3:8d:11'/>
---
>       <mac address='52:54:00:e3:8e:01'/>
[root@node1 qemu]# 

  提示:預設kvm上的虛擬機器的配置檔案都儲存在/etc/libvirt/qemu/目錄下,以虛擬機器名稱命名的配置檔案;上面主要修改了一些比較私密的配置,比如虛擬機器名稱、磁碟映象檔案存放位置,mac地址;

  使用virsh 基於c1.xml建立虛擬

[root@node1 qemu]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 -     centos7.0                      關閉

[root@node1 qemu]# virsh create c1.xml 
錯誤:從 c1.xml 建立域失敗
錯誤:Cannot access storage file '/kvm/images/c1.qcow2' (as uid:107, gid:107): 沒有那個檔案或目錄

[root@node1 qemu]# 

  提示:上述錯誤說沒有找到我們指定磁碟檔案;

  建立c1的磁碟檔案

[root@node1 qemu]# ll /kvm/images/
總用量 0
[root@node1 qemu]# qemu-img create -f qcow2 /kvm/images/c1.qcow2 20G                
Formatting '/kvm/images/c1.qcow2', fmt=qcow2 size=21474836480 encryption=off cluster_size=65536 lazy_refcounts=off 
[root@node1 qemu]# ll -h /kvm/images/
總用量 196K
-rw-r--r-- 1 root root 193K 8月  15 13:23 c1.qcow2
[root@node1 qemu]#

  提示:qemu-img create 表示使用qemu建立一個磁碟檔案,-f指定檔案格式,常用的磁碟格式有raw,cow,qcow2;當然qemu-img支援建立很多格式的磁碟檔案,這個命令的主要作用就是對磁碟檔案的管理,比如建立磁碟,轉換磁碟格式,檢查磁碟,對磁碟做快照等等操作;

  檢視新建磁碟資訊

[root@node1 qemu]# qemu-img info /kvm/images/c1.qcow2 
image: /kvm/images/c1.qcow2
file format: qcow2
virtual size: 20G (21474836480 bytes)
disk size: 196K
cluster_size: 65536
Format specific information:
    compat: 1.1
    lazy refcounts: false
[root@node1 qemu]# 

  再次使用virsh 來基於c1.xml檔案來建立虛擬機器

[root@node1 qemu]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 -     centos7.0                      關閉

[root@node1 qemu]# virsh create c1.xml 
域 c1 被建立(從 c1.xml)

[root@node1 qemu]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 1     c1                             running
 -     centos7.0                      關閉

[root@node1 qemu]# 

  提示:可以看到基於c1.xml檔案中描述的資訊,我們把c1虛擬機器建立並啟動起來了;這裡需要注意,我們在建立虛擬機器時,在其配置檔案中並沒有指定映象檔案在哪裡,所以我們現在只建立了一個類似沒有安裝系統的虛擬機器;

  用virt-manager驗證,看看c1虛擬機器是否有系統執行?

  提示:可以看到我們建立的虛擬機器上沒有執行系統。通常我們使用virsh來快速建立虛擬機器,在建立磁碟檔案時,首先把系統裝進我們磁盤裡,這樣基於xml配置檔案就可以很快速的啟動一臺虛擬機器;通常我們會把這個磁碟檔案做成一個模板,啟動虛擬機器時,直接拷貝模板命名為虛擬機器名稱,拷貝配置檔案修改私密資訊,然後用virsh工具基於這個改好的配置檔案建立虛擬機器即可;

  測試:拷貝centos7的磁碟檔案,命名為c2,然後拷貝centos7.0.xml的配置檔案命名為c2.xml,修改c2.xml中的私有配置,然後基於這個配置檔案來建立虛擬機器

[root@node1 qemu]# cp /var/lib/libvirt/images/centos7.0.qcow2 /kvm/images/c2.qcow2
[root@node1 qemu]# ls /kvm/images/
c1.qcow2  c2.qcow2
[root@node1 qemu]# ls
c1.xml  c2.xml  centos7.0.xml  networks
[root@node1 qemu]# diff centos7.0.xml c2.xml 
9,10c9
<   <name>centos7.0</name>
<   <uuid>56a1ecab-ef53-42f8-b7eb-6b4019ea3ee4</uuid>
---
>   <name>c2</name>
41c40
<       <source file='/var/lib/libvirt/images/centos7.0.qcow2'/>
---
>       <source file='/kvm/images/c2.qcow2'/>
74c73
<       <mac address='52:54:00:e3:8d:11'/>
---
>       <mac address='52:54:00:e3:85:21'/>
[root@node1 qemu]# virsh list  --all
 Id    名稱                         狀態
----------------------------------------------------
 1     c1                             running
 -     centos7.0                      關閉

[root@node1 qemu]# virsh create c2.xml 
域 c2 被建立(從 c2.xml)

[root@node1 qemu]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 1     c1                             running
 2     c2                             running
 -     centos7.0                      關閉

[root@node1 qemu]# 

  驗證:啟動圖形介面virt-manager,檢視c2是否啟動,並有系統在執行?

  提示:可以看到現在c2啟動以後,就有系統執行著,並且和centos7.0一模一樣;

   virsh console:從宿主機連線指定虛擬的序列控制檯

[root@node1 qemu]# virsh help console 
  NAME
    console - 連線到客戶會話

  SYNOPSIS
    console <domain> [--devname <string>] [--force] [--safe]

  DESCRIPTION
    連線客戶真實序列控制檯

  OPTIONS
    [--domain] <string>  domain name, id or uuid
    --devname <string>  字元裝置名稱
    --force          強制控制檯連線(斷開已連線的會話)
    --safe           只有在支援安全控制檯處理時方可連線


[root@node1 qemu]# virsh console c2
連線到域 c2
換碼符為 ^]

  提示:用virsh console c2命令連線c2的控制檯,一直處於卡死的狀態,這是因為centos7上預設沒有允許ttyS0;

  在宿主機用ssh連線至虛擬機器(當然svn或者使用virt-manager也行),修改核心引數,然後重啟虛擬機器

[root@node1 qemu]# ssh 192.168.122.168
The authenticity of host '192.168.122.168 (192.168.122.168)' can't be established.
ECDSA key fingerprint is SHA256:heUVB8InZ+56B+vMgUz+B7Uus4EgklEU9DVeywf1Z7s.
ECDSA key fingerprint is MD5:0b:b1:75:a4:2b:ba:cf:f1:ac:51:cb:76:2a:74:89:42.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.122.168' (ECDSA) to the list of known hosts.
[email protected]'s password: 
Permission denied, please try again.
[email protected]'s password: 
Last failed login: Sat Aug 15 03:06:50 EDT 2020 from 192.168.122.1 on ssh:notty
There was 1 failed login attempt since the last successful login.
Last login: Sat Aug 15 02:40:23 2020
[root@localhost ~]# 
[root@localhost ~]# grep "ttyS0" /etc/securetty 
ttyS0
[root@localhost ~]# grubby --update-kernel=ALL --args="console=ttyS0"
[root@localhost ~]# reboot
PolicyKit daemon disconnected from the bus.
We are no longer a registered authentication agent.
Connection to 192.168.122.168 closed by remote host.
Connection to 192.168.122.168 closed.
[root@node1 qemu]#

  提示:連線虛擬機器後,需要看看/etc/securetty這個檔案中是否有ttyS0,如果沒有就加上,再更改核心引數;如果客戶機上centos6,也是一樣的步驟,不過在centos6上除了要確定/etc/securetty這個檔案是否有ttyS0,還需要確認/etc/inittab檔案中是否有S0:12345:respawn:/sbin/agetty ttyS0 115200這項配置,修改核心引數需要修改/etc/grup2.cfg,在啟動核心的引數最後加console=ttyS0 儲存重啟客戶機即可;

  驗證:現在使用virsh console c2命令看看是否能夠連線至c2的控制檯?

[root@node1 qemu]# virsh console c2
連線到域 c2
換碼符為 ^]


CentOS Linux 7 (Core)
Kernel 3.10.0-693.el7.x86_64 on an x86_64

localhost login: root
Password: 
Last failed login: Sat Aug 15 03:08:51 EDT 2020 on ttyS0
There was 1 failed login attempt since the last successful login.
Last login: Sat Aug 15 03:06:53 from 192.168.122.1
[root@localhost ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 52:54:00:e3:85:21 brd ff:ff:ff:ff:ff:ff
    inet 192.168.122.168/24 brd 192.168.122.255 scope global dynamic eth0
       valid_lft 2883sec preferred_lft 2883sec
    inet6 fe80::4c39:5a0f:9800:6314/64 scope link 
       valid_lft forever preferred_lft forever
[root@localhost ~]# 
[root@node1 qemu]# 

  提示:可以看到在宿主機上我們可以直接使用virsh console命令來連線指定客戶機的序列控制檯;退出控制檯回到宿主機需要使用Ctrl鍵+有中括號;

  virsh shutdown:關閉指定虛擬機器

[root@node1 ~]# virsh help shutdown
  NAME
    shutdown - 關閉一個域

  SYNOPSIS
    shutdown <domain> [--mode <string>]

  DESCRIPTION
    在目標域中執行關閉行為。

  OPTIONS
    [--domain] <string>  domain name, id or uuid
    --mode <string>  shutdown mode: acpi|agent|initctl|signal|paravirt


[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 1     c1                             running
 2     c2                             running
 -     centos7.0                      關閉

[root@node1 ~]# virsh shutdown c1
域 c1 被關閉

[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 1     c1                             running
 2     c2                             running
 -     centos7.0                      關閉

[root@node1 ~]#

  提示:使用shutdown子命令,有時候會關不掉,我們需要使用destroy子命令來強制關機;

  強制對c1進行關機

[root@node1 ~]# virsh list  --all
 Id    名稱                         狀態
----------------------------------------------------
 1     c1                             running
 2     c2                             running
 -     centos7.0                      關閉

[root@node1 ~]# virsh destroy c1
域 c1 被刪除

[root@node1 ~]# virsh list  --all
 Id    名稱                         狀態
----------------------------------------------------
 2     c2                             running
 -     c1                             關閉
 -     centos7.0                      關閉

[root@node1 ~]# 

  提示:強制刪除有點類似我們使用kill -9強制殺死一個程序一樣,其實kvm上的虛擬在宿主機機上的表現形式就是一個程序,如下所示;

  提示:我們在宿主機上檢視程序就可以知道當前宿主機上就運行了臺虛擬機器,從上面的資訊我們也不難理解virsh其實也就是呼叫qemu來建立虛擬機器的;

  virsh start:啟動指定非活動虛擬機器(開機)

[root@node1 ~]# virsh help start
  NAME
    start - 開始一個(以前定義的)非活躍的域

  SYNOPSIS
    start <domain> [--console] [--paused] [--autodestroy] [--bypass-cache] [--force-boot] [--pass-fds <string>]

  DESCRIPTION
    啟動域,可以從最後一個 managedsave
  state,如果沒有 managedsave state,
    也可以從全新引導中啟動。

  OPTIONS
    [--domain] <string>  非活躍域的名稱
    --console        建立後附加到控制檯
    --paused         生成後讓虛擬機器保持暫停狀態
    --autodestroy    virsh 斷開連線時自動銷燬虛擬機器
    --bypass-cache   載入時避免檔案系統快取
    --force-boot     採用忽略所有管理儲存的方式強制重新整理引導
    --pass-fds <string>  向虛擬機器傳遞檔案描述符 N、M......


[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 2     c2                             running
 -     c1                             關閉
 -     centos7.0                      關閉

[root@node1 ~]# virsh start centos7.0 
域 centos7.0 已開始

[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 2     c2                             running
 3     centos7.0                      running
 -     c1                             關閉

[root@node1 ~]# 

  virsh suspend:掛起一個虛擬機器

[root@node1 ~]# virsh help suspend
  NAME
    suspend - 掛起一個域

  SYNOPSIS
    suspend <domain>

  DESCRIPTION
    掛起一個執行的域。

  OPTIONS
    [--domain] <string>  domain name, id or uuid


[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 2     c2                             running
 3     centos7.0                      running
 -     c1                             關閉

[root@node1 ~]# virsh suspend centos7.0 
域 centos7.0 被掛起

[root@node1 ~]# virsh list --all        
 Id    名稱                         狀態
----------------------------------------------------
 2     c2                             running
 3     centos7.0                      暫停
 -     c1                             關閉

[root@node1 ~]# 

  提示:suspend操作是把指定虛擬機器掛起,所謂掛起就是把執行狀態的虛擬機器暫停,並把當前執行狀態儲存到記憶體,有點類似時間停止的感覺,外部客戶端對它訪問它也不會響應;如果此時宿主機掉電,那麼之前儲存在記憶體的執行狀態資料也將隨之丟失;

  virsh resume:恢復指定被掛起的虛擬機器;

[root@node1 ~]# virsh help resume
  NAME
    resume - 重新恢復一個域

  SYNOPSIS
    resume <domain>

  DESCRIPTION
    重新恢復一個以前被掛起的域。

  OPTIONS
    [--domain] <string>  domain name, id or uuid


[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 2     c2                             running
 3     centos7.0                      暫停
 -     c1                             關閉

[root@node1 ~]# virsh resume centos7.0 
域 centos7.0 被重新恢復

[root@node1 ~]# virsh list --all       
 Id    名稱                         狀態
----------------------------------------------------
 2     c2                             running
 3     centos7.0                      running
 -     c1                             關閉

[root@node1 ~]# 

  virsh save:把指定的虛擬機器執行狀態資訊儲存至指定檔案,有點類似vmware 中的掛起操作,vmware的掛起操作是把執行狀態儲存到磁碟,宿主機掉電,它不會的丟失資料;

[root@node1 ~]# virsh help save
  NAME
    save - 把一個域的狀態儲存到一個檔案

  SYNOPSIS
    save <domain> <file> [--bypass-cache] [--xml <string>] [--running] [--paused] [--verbose]

  DESCRIPTION
    儲存執行中的域 的 RAM 狀態

  OPTIONS
    [--domain] <string>  domain name, id or uuid
    [--file] <string>  資料存到什麼地方
    --bypass-cache   儲存時避免檔案系統快取
    --xml <string>   包含為目標更新的 XML 的檔名
    --running        設定要在還原中執行的域
    --paused         設定要在還原中暫停的域
    --verbose        顯示儲存程序


[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 2     c2                             running
 3     centos7.0                      running
 -     c1                             關閉

[root@node1 ~]# virsh save c2 ./c2.bin --paused       

儲存到 c2 的域 ./c2.bin 

[root@node1 ~]# ls
c2.bin  redis-5.0.8.tar.gz
[root@node1 ~]# virsh list --all                
 Id    名稱                         狀態
----------------------------------------------------
 3     centos7.0                      running
 -     c1                             關閉
 -     c2                             關閉

[root@node1 ~]# 

  virsh restore:從指定檔案恢復虛擬機器(該檔案是使用save命令儲存下來的虛擬機器執行狀態資訊檔案)

[root@node1 ~]# virsh help restore 
  NAME
    restore - 從一個存在一個檔案中的狀態恢復一個域

  SYNOPSIS
    restore <file> [--bypass-cache] [--xml <string>] [--running] [--paused]

  DESCRIPTION
    恢復一個域。

  OPTIONS
    [--file] <string>  恢復的狀態
    --bypass-cache   恢復時避免檔案系統快取
    --xml <string>   包含為目標更新的 XML 的檔名
    --running        將域恢復為執行狀態
    --paused         將域恢復為暫停狀態


[root@node1 ~]# virsh list --all   
 Id    名稱                         狀態
----------------------------------------------------
 3     centos7.0                      running
 -     c1                             關閉
 -     c2                             關閉

[root@node1 ~]# virsh restore ./c2.bin 
從 ./c2.bin 恢復域

[root@node1 ~]# virsh list --all       
 Id    名稱                         狀態
----------------------------------------------------
 3     centos7.0                      running
 4     c2                             暫停
 -     c1                             關閉

[root@node1 ~]# 

  提示:恢復後端c2變成了暫停狀態,這是因為我們在儲存狀態資訊時,指定了恢復時的狀態;當然我們在恢復時也可以使用選項來指定我們要把虛擬機器恢復到什麼狀態;

  virsh reboot:重啟指定虛擬機器,如同在指定虛擬機器上執行reboot命令一樣;

[root@node1 ~]# virsh help reboot
  NAME
    reboot - 重新啟動一個域

  SYNOPSIS
    reboot <domain> [--mode <string>]

  DESCRIPTION
    在目標域中執行重新啟動命令。

  OPTIONS
    [--domain] <string>  domain name, id or uuid
    --mode <string>  shutdown mode: acpi|agent|initctl|signal|paravirt


[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 3     centos7.0                      running
 4     c2                             暫停
 -     c1                             關閉

[root@node1 ~]# virsh reboot centos7.0 
域 centos7.0 正在被重新啟動

[root@node1 ~]#

  virsh reset:對指定虛擬機器執行強制重啟,有點類似按機箱上的重置按鈕;

[root@node1 ~]# virsh help reset
  NAME
    reset - 重新設定域

  SYNOPSIS
    reset <domain>

  DESCRIPTION
    如同使用電源按鈕重新設定目標域

  OPTIONS
    [--domain] <string>  domain name, id or uuid


[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 3     centos7.0                      running
 4     c2                             暫停
 -     c1                             關閉

[root@node1 ~]# virsh  reset centos7.0 
重新設定域 centos7.0

[root@node1 ~]#

  virsh dumpxml:以xml格式輸出指定虛擬機器的詳細配置(把對應虛擬機器的配置檔案內容輸出到標準輸出);

[root@node1 ~]# virsh help dumpxml
  NAME
    dumpxml - XML 中的域資訊

  SYNOPSIS
    dumpxml <domain> [--inactive] [--security-info] [--update-cpu] [--migratable]

  DESCRIPTION
    把域資訊作為一個 XML 輸出到 stdout。

  OPTIONS
    [--domain] <string>  domain name, id or uuid
    --inactive       顯示不活躍定義的 XML
    --security-info  包括 XML 轉儲中與安全性相關的資訊
    --update-cpu     根據主機 CPU 更新虛擬機器 CPU
    --migratable     為遷移提供 XML 可用性


[root@node1 ~]# virsh dumpxml c1
<domain type='kvm'>
  <name>c1</name>
  <uuid>c2bd061d-1628-4901-a459-e1cde62ed5b3</uuid>
  <memory unit='KiB'>2097152</memory>
  <currentMemory unit='KiB'>2097152</currentMemory>
  <vcpu placement='static'>2</vcpu>
  <os>
    <type arch='x86_64' machine='pc-i440fx-rhel7.0.0'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
    <apic/>
  </features>
  <cpu mode='custom' match='exact' check='partial'>
    <model fallback='allow'>Broadwell</model>
  </cpu>
  <clock offset='utc'>
    <timer name='rtc' tickpolicy='catchup'/>
    <timer name='pit' tickpolicy='delay'/>
    <timer name='hpet' present='no'/>
  </clock>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>destroy</on_crash>
  <pm>
    <suspend-to-mem enabled='no'/>
    <suspend-to-disk enabled='no'/>
  </pm>
  <devices>
    <emulator>/usr/libexec/qemu-kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/kvm/images/c1.qcow2'/>
      <target dev='vda' bus='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x07' function='0x0'/>
    </disk>
    <disk type='file' device='cdrom'>
      <driver name='qemu' type='raw'/>
      <target dev='hda' bus='ide'/>
      <readonly/>
      <address type='drive' controller='0' bus='0' target='0' unit='0'/>
    </disk>
    <controller type='usb' index='0' model='ich9-ehci1'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x7'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci1'>
      <master startport='0'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0' multifunction='on'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci2'>
      <master startport='2'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x1'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci3'>
      <master startport='4'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x2'/>
    </controller>
    <controller type='pci' index='0' model='pci-root'/>
    <controller type='ide' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
    </controller>
    <controller type='virtio-serial' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/>
    </controller>
    <interface type='network'>
      <mac address='52:54:00:e3:8e:01'/>
      <source network='default'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
    <serial type='pty'>
      <target type='isa-serial' port='0'>
        <model name='isa-serial'/>
      </target>
    </serial>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
    <channel type='unix'>
      <target type='virtio' name='org.qemu.guest_agent.0'/>
      <address type='virtio-serial' controller='0' bus='0' port='1'/>
    </channel>
    <channel type='spicevmc'>
      <target type='virtio' name='com.redhat.spice.0'/>
      <address type='virtio-serial' controller='0' bus='0' port='2'/>
    </channel>
    <input type='tablet' bus='usb'>
      <address type='usb' bus='0' port='1'/>
    </input>
    <input type='mouse' bus='ps2'/>
    <input type='keyboard' bus='ps2'/>
    <graphics type='spice' autoport='yes'>
      <listen type='address'/>
      <image compression='off'/>
    </graphics>
    <sound model='ich6'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
    </sound>
    <video>
      <model type='qxl' ram='65536' vram='65536' vgamem='16384' heads='1' primary='yes'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </video>
    <redirdev bus='usb' type='spicevmc'>
      <address type='usb' bus='0' port='2'/>
    </redirdev>
    <redirdev bus='usb' type='spicevmc'>
      <address type='usb' bus='0' port='3'/>
    </redirdev>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x08' function='0x0'/>
    </memballoon>
    <rng model='virtio'>
      <backend model='random'>/dev/urandom</backend>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x09' function='0x0'/>
    </rng>
  </devices>
</domain>

[root@node1 ~]# virsh dumpxml c1 > c1.xml.bak
[root@node1 ~]# diff c1.xml.bak /etc/libvirt/qemu/c1.xml 
0a1,7
> <!--
> WARNING: THIS IS AN AUTO-GENERATED FILE. CHANGES TO IT ARE LIKELY TO BE
> OVERWRITTEN AND LOST. Changes to this xml configuration should be made using:
>   virsh edit centos7.0
> or other application using the libvirt API.
> -->
> 
3d9
<   <uuid>c2bd061d-1628-4901-a459-e1cde62ed5b3</uuid>
119d124
< 
[root@node1 ~]# 

  提示:可以看到到處都配置檔案和原有配置檔案沒有本質的不同,除了註釋相差就只是uuid,如果我們在建立虛擬機器時指定了uuid,匯出的配置和原配置檔案都是一樣的;

  virsh undefine:刪除指定虛擬機器(會連同配置檔案一併刪除)

[root@node1 ~]# virsh help undefine 
  NAME
    undefine - 取消定義一個域

  SYNOPSIS
    undefine <domain> [--managed-save] [--storage <string>] [--remove-all-storage] [--delete-snapshots] [--wipe-storage] [--snapshots-metadata] [--nvram] [--keep-nvram]

  DESCRIPTION
    取消定義一個域或者將持久轉換為臨時。

  OPTIONS
    [--domain] <string>  domain name, id or uuid
    --managed-save   刪除域管理的狀態檔案
    --storage <string>  刪除關聯的儲存卷(用逗號分開的目標或者源路徑列表)(檢視 domblklist)
    --remove-all-storage  刪除關聯的儲存卷(小心使用)
    --delete-snapshots  delete snapshots associated with volume(s), requires --remove-all-storage (must be supported by storage driver)
    --wipe-storage   擦除刪除卷中的資料
    --snapshots-metadata  如果不活躍則刪除所有域快照元資料
    --nvram          remove nvram file, if inactive
    --keep-nvram     keep nvram file, if inactive


[root@node1 ~]# ll /kvm/images/
總用量 20975172
-rw-r--r-- 1 root root      197120 8月  15 13:23 c1.qcow2
-rw------- 1 qemu qemu 21478375424 8月  15 16:30 c2.qcow2
[root@node1 ~]# ll /etc/libvirt/qemu/
總用量 24
-rw------- 1 root root 4531 8月  15 14:22 c1.xml
-rw------- 1 root root 4531 8月  15 14:34 c2.xml
-rw------- 1 root root 4609 8月  14 00:10 centos7.0.xml
drwx------ 3 root root   42 8月  13 23:31 networks
[root@node1 ~]# virsh undefine c1
域 c1 已經被取消定義

[root@node1 ~]# ll /etc/libvirt/qemu/
總用量 16
-rw------- 1 root root 4531 8月  15 14:34 c2.xml
-rw------- 1 root root 4609 8月  14 00:10 centos7.0.xml
drwx------ 3 root root   42 8月  13 23:31 networks
[root@node1 ~]# ll /kvm/images/      
總用量 20975172
-rw-r--r-- 1 root root      197120 8月  15 13:23 c1.qcow2
-rw------- 1 qemu qemu 21478375424 8月  15 16:30 c2.qcow2
[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 3     centos7.0                      running
 4     c2                             暫停

[root@node1 ~]#

  提示:預設使用undefine只會把對應配置檔案和虛擬機器例項刪除,如果還需要刪除儲存卷,可以在後面加上對應的選項指定即可;

  virsh autostart :設定指定虛擬機器為隨宿主機啟動而自動啟動

[root@node1 ~]# virsh help autostart   
  NAME
    autostart - 自動開始一個域

  SYNOPSIS
    autostart <domain> [--disable]

  DESCRIPTION
    設定一個域在啟動時自動開始.

  OPTIONS
    [--domain] <string>  domain name, id or uuid
    --disable        禁止自動啟動


[root@node1 ~]# virsh list --all
 Id    名稱                         狀態
----------------------------------------------------
 3     centos7.0                      running
 4     c2                             暫停

[root@node1 ~]# virsh autostart c2   
域 c2標記為自動開始

[root@node1 ~]# virsh autostart c2 --disable 
域 c2取消標記為自動開始

[root@node1 ~]# 

&n