Last active
October 18, 2021 21:54
-
-
Save biggers/6477183 to your computer and use it in GitHub Desktop.
Python 'sh' module example, working with Virtualbox commands & outputs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| from __future__ import print_function | |
| from pprint import pprint | |
| # install into a virtual-env: pip install sh | |
| # | |
| # References: | |
| # http://amoffat.github.com/sh | |
| # | |
| # Inspired by: | |
| # http://devdetails.com/2011/11/07/clom-python-command-line-the-easy-way/ | |
| from pprint import pprint as pp | |
| from sys import exit | |
| from sh import VBoxManage as vbm | |
| # "testing" the 'sh' Py module... | |
| # ... dump some info, on VirtualBox VMs on this Linux "host" | |
| VM_INFO_KEYS = ('name', 'ostype', 'UUID', 'CfgFile', 'SnapFldr', 'LogFldr', 'memory', 'vram', 'cpus', 'VMState', 'storagecontrollername1', 'SATA Controller', 'SharedFolderPathMachineMapping1', 'Forwarding',) | |
| def get_clean_kv(item_raw, val_spl=' ', val_strp='"'): | |
| raw_line = item_raw.strip() | |
| try: | |
| key_raw, value_raw = raw_line.split( val_spl ) | |
| key = key_raw.strip('"') | |
| value = value_raw.strip( val_strp ) | |
| return key, value | |
| except ValueError: | |
| return ('No k/v: ', raw_line) | |
| name = None | |
| for line in vbm.list.vms(_iter=True): | |
| name, uuid = get_clean_kv( line, val_spl=' ', val_strp='{}' ) | |
| print( "{} = {}".format(name, uuid) ) | |
| print() | |
| # NOTE: we use the _last_ VM-name, from above... | |
| for line in vbm.showvminfo(name, machinereadable=True, details=True, _iter=True): | |
| key, value = get_clean_kv( line, val_spl='=') | |
| if key in VM_INFO_KEYS: | |
| print("{} = {}".format( key, value )) | |
| print() | |
| #res = vbm.list.ostypes() | |
| d = dict() | |
| for line in vbm.list.ostypes( _iter=True ): | |
| t = get_clean_kv( line, val_spl=':') | |
| key, value = t | |
| v = value.strip() | |
| d[ key ] = v | |
| if key in ('Family ID',): | |
| if v in ('Linux',): | |
| pprint( d, width=240 ) | |
| d = {} | |
| continue | |
| if v == '': | |
| d = {} | |
| continue | |
| # print(res) | |
| exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment