Guest User

Untitled

a guest
Feb 7th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Keyboard to scancode mapping for US keyboard layout.
  4. """
  5.  
  6. from itertools import chain
  7.  
  8. keys_base = (
  9. '`1234567890-='
  10. 'qwertyuiop[]\\'
  11. 'asdfghjkl;\''
  12. 'zxcvbnm,./ \n'
  13. )
  14.  
  15. keys_shift = (
  16. '~!@#$%^&*()_+'
  17. 'QWERTYUIOP{}|'
  18. 'ASDFGHJKL:"'
  19. 'ZXCVBNM<>?'
  20. )
  21.  
  22. # not using `bytes`, manual conversion with ord for python 2/3 compat
  23. scancode_down_base = (
  24. '\x29\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d'
  25. '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x2b'
  26. '\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28'
  27. '\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x39\x1c'
  28. )
  29.  
  30. LSHIFT = '\x2a'
  31.  
  32. key_scancode_map = {}
  33.  
  34. # initial scancode
  35. for key, init_scancode in zip(keys_base, scancode_down_base):
  36. key_scancode_map[key] = (
  37. ord(init_scancode),
  38. ord(init_scancode) + 0x80,
  39. )
  40.  
  41. # for the ones with shift
  42. for key, init_scancode in zip(keys_shift, scancode_down_base):
  43. key_scancode_map[key] = (
  44. ord(LSHIFT), ord(init_scancode),
  45. ord(init_scancode) + 0x80, ord(LSHIFT) + 0x80,
  46. )
  47.  
  48.  
  49. def keyboardputscancode(chars):
  50. """
  51. Return a space separated list of scancodes in hexadecimal numbers
  52. from the characters provided by chars. Naturally, only characters
  53. in the mapping are supported.
  54. """
  55.  
  56. return ' '.join('%x' % i for i in chain(
  57. *(key_scancode_map[c] for c in chars)))
  58.  
  59.  
  60. def main():
  61. """
  62. Make use of the keyboardputscancode function to provide a quick way
  63. to get commands inputed into a VirtualBox vm through the controlvm
  64. keyboardputscancode feature. Example usage:
  65.  
  66. VBoxManage controlvm $VBOX_NAME keyboardputscancode \
  67. $(echo whoami | python scancode.py)
  68.  
  69. If the raw console was activated, whoami will be executed.
  70.  
  71. Do note that there may be limitations in place with how long the
  72. command may be inputed at once. If a sufficiently long command is
  73. required, break them up into multiple commands. For example:
  74.  
  75. VBoxManage controlvm $VBOX_NAME keyboardputscancode \
  76. $(echo -n '/etc/init.d/apache ' | python scancode.py)
  77. VBoxManage controlvm $VBOX_NAME keyboardputscancode \
  78. $(echo restart | python scancode.py)
  79.  
  80. Note the -n flag for the first echo command to avoid sending a
  81. newline character through to the console.
  82. """
  83.  
  84. import sys
  85. sys.stdout.write(keyboardputscancode(sys.stdin.read()))
  86.  
  87.  
  88. if __name__ == '__main__':
  89. main()
Add Comment
Please, Sign In to add comment