---
# System prepended metadata

title: VM構築 by CLI

---

# VM構築 by CLI
## パッケージのインストール
```
apt -y install qemu-kvm libvirt-bin virtinst bridge-utils libosinfo-bin libguestfs-tools virt-top
```
## ディスク用ディレクトリの作成
```
mkdir -p /var/kvm/images
```
## ブリッジの作成
```
brctl addbr br0
ip a add 192.168.x.x/16 dev br0
brctl addif br0 eno1 && ip r del default via 192.168.1.1 dev eno1 && ip l set br0 up && ip r add 192.168.0.0/16 dev br0&& ip r add default via 192.168.0.1 dev br0
```

## 作成
https://www.server-world.info/query?os=Ubuntu_18.04&p=kvm&f=2
```
virt-install \
--name xxx \
--ram 2048 \
--disk path=/var/kvm/images/xxx.img,size=50 \
--vcpus 2 \
--os-type linux \
--os-variant ubuntu20.04 \
--network bridge=br0 \
--graphics none \
--console pty,target_type=serial \
--location 'http://jp.archive.ubuntu.com/ubuntu/dists/bionic/main/installer-amd64/' \
--extra-args 'console=ttyS0,115200n8 serial'
```

一行で
```
virt-install --name Mapper2 --ram 2048 --disk path=/var/kvm/images/Mapper2.img,size=50 --vcpus 2 --os-type linux --os-variant ubuntu18.04 --network bridge=br0 --graphics none --console pty,target_type=serial --location 'http://jp.archive.ubuntu.com/ubuntu/dists/bionic/main/installer-amd64/' --extra-args 'console=ttyS0,115200n8 serial'
```

↓の設定をしないとコンソール接続出来ない
```
guestmount -d ubuntu1804 -i /mnt
```
```
ln -s /mnt/lib/systemd/system/getty@.service /mnt/etc/systemd/system/getty.target.wants/getty@ttyS0.service
```
```
umount /mnt
```

## 起動
```
virsh start --console
```

## NICを追加
virsh edit <KVM名>で以下を追加
```
<interface type='bridge'>
      <source bridge='br1'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x0a' function='0x0'/>
</interface>
```

## 基本操作
https://qiita.com/TsutomuNakamura/items/22d9d2629a8eb9360865

## 削除・強制停止
https://access.redhat.com/documentation/ja-jp/red_hat_enterprise_linux/7/html/virtualization_deployment_and_administration_guide/sect-virsh-delete