| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2018, Ansible Project |
| 5 |
# Copyright: (c) 2018, Diane Wang <[email protected]> |
| 6 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 8 |
|
| 9 |
from __future__ import absolute_import, division, print_function |
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
|
| 13 |
DOCUMENTATION = r''' |
| 14 |
--- |
| 15 |
module: vmware_guest_sendkey |
| 16 |
short_description: Send USB HID codes to the Virtual Machine's keyboard. |
| 17 |
description: |
| 18 |
- This module is used to send keystrokes to given virtual machine. |
| 19 |
author: |
| 20 |
- Diane Wang (@Tomorrow9) <[email protected]> |
| 21 |
options: |
| 22 |
name: |
| 23 |
description: |
| 24 |
- Name of the virtual machine. |
| 25 |
- This is a required parameter, if parameter O(uuid) or O(moid) is not supplied. |
| 26 |
type: str |
| 27 |
uuid: |
| 28 |
description: |
| 29 |
- UUID of the instance to gather facts if known, this is VMware's unique identifier. |
| 30 |
- This is a required parameter, if parameter O(name) or O(moid) is not supplied. |
| 31 |
type: str |
| 32 |
moid: |
| 33 |
description: |
| 34 |
- Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance. |
| 35 |
- This is required if O(name) or O(uuid) is not supplied. |
| 36 |
type: str |
| 37 |
folder: |
| 38 |
description: |
| 39 |
- Destination folder, absolute or relative path to find an existing guest. |
| 40 |
- This is a required parameter, only if multiple VMs are found with same name. |
| 41 |
- The folder should include the datacenter. ESXi server's datacenter is ha-datacenter. |
| 42 |
- 'Examples:' |
| 43 |
- ' folder: /ha-datacenter/vm' |
| 44 |
- ' folder: ha-datacenter/vm' |
| 45 |
- ' folder: /datacenter1/vm' |
| 46 |
- ' folder: datacenter1/vm' |
| 47 |
- ' folder: /datacenter1/vm/folder1' |
| 48 |
- ' folder: datacenter1/vm/folder1' |
| 49 |
- ' folder: /folder1/datacenter1/vm' |
| 50 |
- ' folder: folder1/datacenter1/vm' |
| 51 |
- ' folder: /folder1/datacenter1/vm/folder2' |
| 52 |
type: str |
| 53 |
cluster: |
| 54 |
description: |
| 55 |
- The name of cluster where the virtual machine is running. |
| 56 |
- This is a required parameter, if O(esxi_hostname) is not set. |
| 57 |
- O(esxi_hostname) and O(cluster) are mutually exclusive. |
| 58 |
type: str |
| 59 |
esxi_hostname: |
| 60 |
description: |
| 61 |
- The ESXi hostname where the virtual machine is running. |
| 62 |
- This is a required parameter, if O(cluster) is not set. |
| 63 |
- O(esxi_hostname) and O(cluster) are mutually exclusive. |
| 64 |
type: str |
| 65 |
datacenter: |
| 66 |
description: |
| 67 |
- The datacenter name to which virtual machine belongs to. |
| 68 |
type: str |
| 69 |
string_send: |
| 70 |
description: |
| 71 |
- The string will be sent to the virtual machine. |
| 72 |
- This string can contain valid special character, alphabet and digit on the keyboard. |
| 73 |
- If both O(keys_send) and O(string_send) are specified, keys in O(keys_send) list will be sent in front of the O(string_send). |
| 74 |
type: str |
| 75 |
keys_send: |
| 76 |
description: |
| 77 |
- The list of the keys will be sent to the virtual machine. |
| 78 |
- 'Valid values are C(ENTER), C(ESC), C(BACKSPACE), C(TAB), C(SPACE), C(CAPSLOCK), C(HOME), C(DELETE), C(END), C(CTRL_ALT_DEL), |
| 79 |
C(CTRL_C), C(CTRL_X) and C(F1) to C(F12), C(RIGHTARROW), C(LEFTARROW), C(DOWNARROW), C(UPARROW), C(WINDOWS).' |
| 80 |
- If both O(keys_send) and O(string_send) are specified, keys in O(keys_send) list will be sent in front of the O(string_send). |
| 81 |
type: list |
| 82 |
default: [] |
| 83 |
elements: str |
| 84 |
sleep_time: |
| 85 |
description: |
| 86 |
- Sleep time in seconds between two keys or string sent to the virtual machine. |
| 87 |
- API is faster than actual key or string send to virtual machine, this parameter allow to control |
| 88 |
delay between keys and/or strings. |
| 89 |
type: int |
| 90 |
default: 0 |
| 91 |
extends_documentation_fragment: |
| 92 |
- vmware.vmware.base_options |
| 93 |
|
| 94 |
''' |
| 95 |
|
| 96 |
EXAMPLES = r''' |
| 97 |
- name: Send list of keys to virtual machine |
| 98 |
community.vmware.vmware_guest_sendkey: |
| 99 |
hostname: "{{ vcenter_hostname }}" |
| 100 |
username: "{{ vcenter_username }}" |
| 101 |
password: "{{ vcenter_password }}" |
| 102 |
datacenter: "{{ datacenter_name }}" |
| 103 |
folder: "{{ folder_name }}" |
| 104 |
name: "{{ vm_name }}" |
| 105 |
keys_send: |
| 106 |
- TAB |
| 107 |
- TAB |
| 108 |
- ENTER |
| 109 |
delegate_to: localhost |
| 110 |
register: keys_num_sent |
| 111 |
|
| 112 |
- name: Send list of keys to virtual machine using MoID |
| 113 |
community.vmware.vmware_guest_sendkey: |
| 114 |
hostname: "{{ vcenter_hostname }}" |
| 115 |
username: "{{ vcenter_username }}" |
| 116 |
password: "{{ vcenter_password }}" |
| 117 |
datacenter: "{{ datacenter_name }}" |
| 118 |
folder: "{{ folder_name }}" |
| 119 |
moid: vm-42 |
| 120 |
keys_send: |
| 121 |
- CTRL_ALT_DEL |
| 122 |
delegate_to: localhost |
| 123 |
register: ctrl_alt_del_sent |
| 124 |
|
| 125 |
- name: Send a string to virtual machine |
| 126 |
community.vmware.vmware_guest_sendkey: |
| 127 |
hostname: "{{ vcenter_hostname }}" |
| 128 |
username: "{{ vcenter_username }}" |
| 129 |
password: "{{ vcenter_password }}" |
| 130 |
datacenter: "{{ datacenter_name }}" |
| 131 |
folder: "{{ folder_name }}" |
| 132 |
name: "{{ vm_name }}" |
| 133 |
string_send: "user_logon" |
| 134 |
delegate_to: localhost |
| 135 |
register: keys_num_sent |
| 136 |
''' |
| 137 |
|
| 138 |
RETURN = r''' |
| 139 |
sendkey_info: |
| 140 |
description: display the keys and the number of keys sent to the virtual machine |
| 141 |
returned: always |
| 142 |
type: dict |
| 143 |
sample: { |
| 144 |
"virtual_machine": "test_vm", |
| 145 |
"keys_send": [ |
| 146 |
"SPACE", |
| 147 |
"DOWNARROW", |
| 148 |
"DOWNARROW", |
| 149 |
"ENTER" |
| 150 |
], |
| 151 |
"string_send": null, |
| 152 |
"keys_send_number": 4, |
| 153 |
"returned_keys_send_number": 4, |
| 154 |
} |
| 155 |
''' |
| 156 |
|
| 157 |
import time |
| 158 |
try: |
| 159 |
from pyVmomi import vim, vmodl |
| 160 |
except ImportError: |
| 161 |
pass |
| 162 |
|
| 163 |
from ansible.module_utils.basic import AnsibleModule |
| 164 |
from ansible.module_utils.common.text.converters import to_native |
| 165 |
from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi |
| 166 |
from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec |
| 167 |
|
| 168 |
|
| 169 |
class PyVmomiHelper(PyVmomi): |
| 170 |
def __init__(self, module): |
| 171 |
super(PyVmomiHelper, self).__init__(module) |
| 172 |
self.change_detected = False |
| 173 |
self.num_keys_send = 0 |
| 174 |
# HID usage tables https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf |
| 175 |
# define valid characters and keys value, hex_code, key value and key modifier |
| 176 |
self.keys_hid_code = [ |
| 177 |
(('a', 'A'), '0x04', [('a', []), ('A', ['LEFTSHIFT'])]), |
| 178 |
(('b', 'B'), '0x05', [('b', []), ('B', ['LEFTSHIFT'])]), |
| 179 |
(('c', 'C'), '0x06', [('c', []), ('C', ['LEFTSHIFT'])]), |
| 180 |
(('d', 'D'), '0x07', [('d', []), ('D', ['LEFTSHIFT'])]), |
| 181 |
(('e', 'E'), '0x08', [('e', []), ('E', ['LEFTSHIFT'])]), |
| 182 |
(('f', 'F'), '0x09', [('f', []), ('F', ['LEFTSHIFT'])]), |
| 183 |
(('g', 'G'), '0x0a', [('g', []), ('G', ['LEFTSHIFT'])]), |
| 184 |
(('h', 'H'), '0x0b', [('h', []), ('H', ['LEFTSHIFT'])]), |
| 185 |
(('i', 'I'), '0x0c', [('i', []), ('I', ['LEFTSHIFT'])]), |
| 186 |
(('j', 'J'), '0x0d', [('j', []), ('J', ['LEFTSHIFT'])]), |
| 187 |
(('k', 'K'), '0x0e', [('k', []), ('K', ['LEFTSHIFT'])]), |
| 188 |
(('l', 'L'), '0x0f', [('l', []), ('L', ['LEFTSHIFT'])]), |
| 189 |
(('m', 'M'), '0x10', [('m', []), ('M', ['LEFTSHIFT'])]), |
| 190 |
(('n', 'N'), '0x11', [('n', []), ('N', ['LEFTSHIFT'])]), |
| 191 |
(('o', 'O'), '0x12', [('o', []), ('O', ['LEFTSHIFT'])]), |
| 192 |
(('p', 'P'), '0x13', [('p', []), ('P', ['LEFTSHIFT'])]), |
| 193 |
(('q', 'Q'), '0x14', [('q', []), ('Q', ['LEFTSHIFT'])]), |
| 194 |
(('r', 'R'), '0x15', [('r', []), ('R', ['LEFTSHIFT'])]), |
| 195 |
(('s', 'S'), '0x16', [('s', []), ('S', ['LEFTSHIFT'])]), |
| 196 |
(('t', 'T'), '0x17', [('t', []), ('T', ['LEFTSHIFT'])]), |
| 197 |
(('u', 'U'), '0x18', [('u', []), ('U', ['LEFTSHIFT'])]), |
| 198 |
(('v', 'V'), '0x19', [('v', []), ('V', ['LEFTSHIFT'])]), |
| 199 |
(('w', 'W'), '0x1a', [('w', []), ('W', ['LEFTSHIFT'])]), |
| 200 |
(('x', 'X'), '0x1b', [('x', []), ('X', ['LEFTSHIFT'])]), |
| 201 |
(('y', 'Y'), '0x1c', [('y', []), ('Y', ['LEFTSHIFT'])]), |
| 202 |
(('z', 'Z'), '0x1d', [('z', []), ('Z', ['LEFTSHIFT'])]), |
| 203 |
(('1', '!'), '0x1e', [('1', []), ('!', ['LEFTSHIFT'])]), |
| 204 |
(('2', '@'), '0x1f', [('2', []), ('@', ['LEFTSHIFT'])]), |
| 205 |
(('3', '#'), '0x20', [('3', []), ('#', ['LEFTSHIFT'])]), |
| 206 |
(('4', '$'), '0x21', [('4', []), ('$', ['LEFTSHIFT'])]), |
| 207 |
(('5', '%'), '0x22', [('5', []), ('%', ['LEFTSHIFT'])]), |
| 208 |
(('6', '^'), '0x23', [('6', []), ('^', ['LEFTSHIFT'])]), |
| 209 |
(('7', '&'), '0x24', [('7', []), ('&', ['LEFTSHIFT'])]), |
| 210 |
(('8', '*'), '0x25', [('8', []), ('*', ['LEFTSHIFT'])]), |
| 211 |
(('9', '('), '0x26', [('9', []), ('(', ['LEFTSHIFT'])]), |
| 212 |
(('0', ')'), '0x27', [('0', []), (')', ['LEFTSHIFT'])]), |
| 213 |
(('-', '_'), '0x2d', [('-', []), ('_', ['LEFTSHIFT'])]), |
| 214 |
(('=', '+'), '0x2e', [('=', []), ('+', ['LEFTSHIFT'])]), |
| 215 |
(('[', '{'), '0x2f', [('[', []), ('{', ['LEFTSHIFT'])]), |
| 216 |
((']', '}'), '0x30', [(']', []), ('}', ['LEFTSHIFT'])]), |
| 217 |
(('\\', '|'), '0x31', [('\\', []), ('|', ['LEFTSHIFT'])]), |
| 218 |
((';', ':'), '0x33', [(';', []), (':', ['LEFTSHIFT'])]), |
| 219 |
(('\'', '"'), '0x34', [('\'', []), ('"', ['LEFTSHIFT'])]), |
| 220 |
(('`', '~'), '0x35', [('`', []), ('~', ['LEFTSHIFT'])]), |
| 221 |
((',', '<'), '0x36', [(',', []), ('<', ['LEFTSHIFT'])]), |
| 222 |
(('.', '>'), '0x37', [('.', []), ('>', ['LEFTSHIFT'])]), |
| 223 |
(('/', '?'), '0x38', [('/', []), ('?', ['LEFTSHIFT'])]), |
| 224 |
('ENTER', '0x28', [('', [])]), |
| 225 |
('ESC', '0x29', [('', [])]), |
| 226 |
('BACKSPACE', '0x2a', [('', [])]), |
| 227 |
('TAB', '0x2b', [('', [])]), |
| 228 |
('SPACE', '0x2c', [(' ', [])]), |
| 229 |
('CAPSLOCK', '0x39', [('', [])]), |
| 230 |
('F1', '0x3a', [('', [])]), |
| 231 |
('F2', '0x3b', [('', [])]), |
| 232 |
('F3', '0x3c', [('', [])]), |
| 233 |
('F4', '0x3d', [('', [])]), |
| 234 |
('F5', '0x3e', [('', [])]), |
| 235 |
('F6', '0x3f', [('', [])]), |
| 236 |
('F7', '0x40', [('', [])]), |
| 237 |
('F8', '0x41', [('', [])]), |
| 238 |
('F9', '0x42', [('', [])]), |
| 239 |
('F10', '0x43', [('', [])]), |
| 240 |
('F11', '0x44', [('', [])]), |
| 241 |
('F12', '0x45', [('', [])]), |
| 242 |
('HOME', '0x4a', [('', [])]), |
| 243 |
('DELETE', '0x4c', [('', [])]), |
| 244 |
('END', '0x4d', [('', [])]), |
| 245 |
('CTRL_ALT_DEL', '0x4c', [('', ['CTRL', 'ALT'])]), |
| 246 |
('CTRL_C', '0x06', [('', ['CTRL'])]), |
| 247 |
('CTRL_X', '0x1b', [('', ['CTRL'])]), |
| 248 |
('RIGHTARROW', '0x4f', [('', [])]), |
| 249 |
('LEFTARROW', '0x50', [('', [])]), |
| 250 |
('DOWNARROW', '0x51', [('', [])]), |
| 251 |
('UPARROW', '0x52', [('', [])]), |
| 252 |
('WINDOWS', '0xe3', [('', [])]), |
| 253 |
] |
| 254 |
|
| 255 |
@staticmethod |
| 256 |
def hid_to_hex(hid_code): |
| 257 |
return int(hid_code, 16) << 16 | 0o0007 |
| 258 |
|
| 259 |
def get_hid_from_key(self, key): |
| 260 |
if key == ' ': |
| 261 |
return '0x2c', [] |
| 262 |
for keys_name, key_code, keys_value in self.keys_hid_code: |
| 263 |
if isinstance(keys_name, tuple): |
| 264 |
for keys in keys_value: |
| 265 |
if key == keys[0]: |
| 266 |
return key_code, keys[1] |
| 267 |
else: |
| 268 |
if key == keys_name: |
| 269 |
return key_code, keys_value[0][1] |
| 270 |
|
| 271 |
def get_key_event(self, hid_code, modifiers): |
| 272 |
key_event = vim.UsbScanCodeSpecKeyEvent() |
| 273 |
key_modifier = vim.UsbScanCodeSpecModifierType() |
| 274 |
key_modifier.leftAlt = False |
| 275 |
key_modifier.leftControl = False |
| 276 |
key_modifier.leftGui = False |
| 277 |
key_modifier.leftShift = False |
| 278 |
key_modifier.rightAlt = False |
| 279 |
key_modifier.rightControl = False |
| 280 |
key_modifier.rightGui = False |
| 281 |
key_modifier.rightShift = False |
| 282 |
# rightShift, rightControl, rightAlt, leftGui, rightGui are not used |
| 283 |
if "LEFTSHIFT" in modifiers: |
| 284 |
key_modifier.leftShift = True |
| 285 |
if "CTRL" in modifiers: |
| 286 |
key_modifier.leftControl = True |
| 287 |
if "ALT" in modifiers: |
| 288 |
key_modifier.leftAlt = True |
| 289 |
key_event.modifiers = key_modifier |
| 290 |
key_event.usbHidCode = self.hid_to_hex(hid_code) |
| 291 |
|
| 292 |
return key_event |
| 293 |
|
| 294 |
def get_sendkey_facts(self, vm_obj, returned_value=0): |
| 295 |
sendkey_facts = dict() |
| 296 |
if vm_obj is not None: |
| 297 |
sendkey_facts = dict( |
| 298 |
virtual_machine=vm_obj.name, |
| 299 |
keys_send=self.params['keys_send'], |
| 300 |
string_send=self.params['string_send'], |
| 301 |
keys_send_number=self.num_keys_send, |
| 302 |
returned_keys_send_number=returned_value, |
| 303 |
) |
| 304 |
|
| 305 |
return sendkey_facts |
| 306 |
|
| 307 |
def send_key_events(self, vm_obj, key_queue, sleep_time=0): |
| 308 |
""" |
| 309 |
Send USB HID Scan codes individually to prevent dropping or cobblering |
| 310 |
""" |
| 311 |
send_keys = 0 |
| 312 |
for item in key_queue: |
| 313 |
usb_spec = vim.UsbScanCodeSpec() |
| 314 |
usb_spec.keyEvents.append(item) |
| 315 |
send_keys += vm_obj.PutUsbScanCodes(usb_spec) |
| 316 |
# Sleep in between key / string send event |
| 317 |
time.sleep(sleep_time) |
| 318 |
return send_keys |
| 319 |
|
| 320 |
def send_key_to_vm(self, vm_obj): |
| 321 |
key_event = None |
| 322 |
num_keys_returned = 0 |
| 323 |
key_queue = [] |
| 324 |
if self.params['keys_send']: |
| 325 |
for specified_key in self.params['keys_send']: |
| 326 |
key_found = False |
| 327 |
for keys in self.keys_hid_code: |
| 328 |
if (isinstance(keys[0], tuple) and specified_key in keys[0]) or \ |
| 329 |
(not isinstance(keys[0], tuple) and specified_key == keys[0]): |
| 330 |
hid_code, modifiers = self.get_hid_from_key(specified_key) |
| 331 |
key_event = self.get_key_event(hid_code, modifiers) |
| 332 |
key_queue.append(key_event) |
| 333 |
self.num_keys_send += 1 |
| 334 |
key_found = True |
| 335 |
break |
| 336 |
if not key_found: |
| 337 |
self.module.fail_json(msg="keys_send parameter: '%s' in %s not supported." |
| 338 |
% (specified_key, self.params['keys_send'])) |
| 339 |
|
| 340 |
if self.params['string_send']: |
| 341 |
for char in self.params['string_send']: |
| 342 |
key_found = False |
| 343 |
for keys in self.keys_hid_code: |
| 344 |
if (isinstance(keys[0], tuple) and char in keys[0]) or char == ' ': |
| 345 |
hid_code, modifiers = self.get_hid_from_key(char) |
| 346 |
key_event = self.get_key_event(hid_code, modifiers) |
| 347 |
key_queue.append(key_event) |
| 348 |
self.num_keys_send += 1 |
| 349 |
key_found = True |
| 350 |
break |
| 351 |
if not key_found: |
| 352 |
self.module.fail_json(msg="string_send parameter: '%s' contains char: '%s' not supported." |
| 353 |
% (self.params['string_send'], char)) |
| 354 |
|
| 355 |
if key_queue: |
| 356 |
try: |
| 357 |
num_keys_returned = self.send_key_events(vm_obj=vm_obj, key_queue=key_queue, sleep_time=self.module.params.get('sleep_time')) |
| 358 |
self.change_detected = True |
| 359 |
except vmodl.RuntimeFault as e: |
| 360 |
self.module.fail_json(msg="Failed to send key %s to virtual machine due to %s" % (key_event, to_native(e.msg))) |
| 361 |
|
| 362 |
sendkey_facts = self.get_sendkey_facts(vm_obj, num_keys_returned) |
| 363 |
if num_keys_returned != self.num_keys_send: |
| 364 |
results = {'changed': self.change_detected, 'failed': True, 'sendkey_info': sendkey_facts} |
| 365 |
else: |
| 366 |
results = {'changed': self.change_detected, 'failed': False, 'sendkey_info': sendkey_facts} |
| 367 |
|
| 368 |
return results |
| 369 |
|
| 370 |
|
| 371 |
def main(): |
| 372 |
argument_spec = base_argument_spec() |
| 373 |
argument_spec.update( |
| 374 |
name=dict(type='str'), |
| 375 |
uuid=dict(type='str'), |
| 376 |
moid=dict(type='str'), |
| 377 |
folder=dict(type='str'), |
| 378 |
datacenter=dict(type='str'), |
| 379 |
esxi_hostname=dict(type='str'), |
| 380 |
cluster=dict(type='str'), |
| 381 |
keys_send=dict(type='list', default=[], elements='str', no_log=False), |
| 382 |
string_send=dict(type='str'), |
| 383 |
sleep_time=dict(type='int', default=0), |
| 384 |
) |
| 385 |
|
| 386 |
module = AnsibleModule( |
| 387 |
argument_spec=argument_spec, |
| 388 |
required_one_of=[ |
| 389 |
['name', 'uuid', 'moid'] |
| 390 |
] |
| 391 |
) |
| 392 |
|
| 393 |
pyv = PyVmomiHelper(module) |
| 394 |
vm = pyv.get_vm() |
| 395 |
if not vm: |
| 396 |
vm_id = (module.params.get('uuid') or module.params.get('name') or module.params.get('moid')) |
| 397 |
module.fail_json(msg='Unable to find the specified virtual machine : %s ' % vm_id) |
| 398 |
|
| 399 |
result = pyv.send_key_to_vm(vm) |
| 400 |
if result['failed']: |
| 401 |
module.fail_json(**result) |
| 402 |
module.exit_json(**result) |
| 403 |
|
| 404 |
|
| 405 |
if __name__ == '__main__': |
| 406 |
main() |