-
Notifications
You must be signed in to change notification settings - Fork 0
/
kvm-screenshot.py
51 lines (48 loc) · 1.23 KB
/
kvm-screenshot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/bin/env python
# -*- coding: utf-8 -*-
"""
使用 libvirt 抓取 KVM 虚拟机的缩略图(待验证)
from http://www.oschina.net/code/snippet_1988449_49174
"""
import libvirt
import os
import uuid
try:
from PIL import Image
print("PIL")
except ImportError:
import Image
def handler(stream, buf, opaque):
fd = opaque
os.write(fd, buf)
THUMBNAIL_SIZE =(256, 256)
thumbnail = '/home/hcc/test/screenshot/test-' + str(uuid.uuid4())
command = "touch " + thumbnail
print(command)
os.system(command)
fd = os.open(thumbnail, os.O_WRONLY | os.O_TRUNC | os.O_CREAT, 0644)
try:
conn = libvirt.open('qemu:///system')
d1 = conn.lookupByName('test')
print(d1.info())
print(d1.name())
stream = conn.newStream(0)
d1.screenshot(stream, 0, 0)
stream.recvAll(handler, fd)
if os.path.getsize(thumbnail) == 0:
image = Image.new("RGB", THUMBNAIL_SIZE, 'black')
image.save(thumbnail)
else:
print("else")
im = Image.open(thumbnail)
im.thumbnail(THUMBNAIL_SIZE)
im.save(thumbnail,'PNG')
except libvirt.libvirtError:
try:
stream.abor()
except:
pass
else:
stream.finish()
finally:
os.close(fd)