Coder Social home page Coder Social logo

sethmlarson / virtualbox-python Goto Github PK

View Code? Open in Web Editor NEW
348.0 16.0 75.0 2.71 MB

Complete implementation of VirtualBox's COM API with a Pythonic interface.

Home Page: https://pypi.org/project/virtualbox

License: Apache License 2.0

Python 100.00%
virtualbox python virtual-machine vm virtualbox-vm

virtualbox-python's Introduction

virtualbox-python

NOTE: โš ๏ธ I am no longer actively maintaining this project. If you have a vested interest in seeing it continued to be maintained please reach out to me via email. Complete implementation of VirtualBox's COM API with a Pythonic interface.

Installation

Go to VirtualBox's downloads page (https://www.virtualbox.org/wiki/Downloads) and download the VirtualBox SDK. Within the extracted ZIP file there is a directory called "installer". Open a console within the installer directory and run python vboxapisetup.py install using your system Python. This installs vboxapi which is the interface that talks to VirtualBox via COM.

Next is to install this library:

To get the latest released version of virtualbox from PyPI run the following:

$ python -m pip install virtualbox

or to install the latest development version from GitHub:

$ git clone https://github.com/sethmlarson/virtualbox-python
$ cd virtualbox-python
$ python setup.py install

Getting Started

Listing Available Machines

>>> import virtualbox
>>> vbox = virtualbox.VirtualBox()
>>> [m.name for m in vbox.machines]
["windows"]

Launching a Machine

>>> session = virtualbox.Session()
>>> machine = vbox.find_machine("windows")
>>> # progress = machine.launch_vm_process(session, "gui", "")
>>> # For virtualbox API 6_1 and above (VirtualBox 6.1.2+), use the following:
>>> progress = machine.launch_vm_process(session, "gui", [])
>>> progress.wait_for_completion()

Querying the Machine

>>> session.state
SessionState(2)  # locked
>>> machine.state
MachineState(5)  # running
>>> height, width, _, _, _, _ = session.console.display.get_screen_resolution()

Interacting with the Machine

>>> session.console.keyboard.put_keys("Hello, world!")
>>> guest_session = session.console.guest.create_session("Seth Larson", "password")
>>> guest_session.directory_exists("C:\\Windows")
True
>>> proc, stdout, stderr = guest_session.execute("C:\\\\Windows\\System32\\cmd.exe", ["/C", "tasklist"])
>>> print(stdout)
Image Name                   PID Session Name     Session#    Mem Usage
========================= ====== ================ ======== ============
System Idle Process            0 Console                 0         28 K
System                         4 Console                 0        236 K
smss.exe                     532 Console                 0        432 K
csrss.exe                    596 Console                 0      3,440 K
winlogon.exe                 620 Console                 0      2,380 K
services.exe                 664 Console                 0      3,780 K
lsass.exe                    676 Console                 0      6,276 K
VBoxService.exe              856 Console                 0      3,972 K
svchost.exe                  900 Console                 0      4,908 K
svchost.exe                 1016 Console                 0      4,264 K
svchost.exe                 1144 Console                 0     18,344 K
svchost.exe                 1268 Console                 0      2,992 K
svchost.exe                 1372 Console                 0      3,948 K
spoolsv.exe                 1468 Console                 0      4,712 K
svchost.exe                 2000 Console                 0      3,856 K
wuauclt.exe                  400 Console                 0      7,176 K
alg.exe                     1092 Console                 0      3,656 K
wscntfy.exe                 1532 Console                 0      2,396 K
explorer.exe                1728 Console                 0     14,796 K
wmiprvse.exe                1832 Console                 0      7,096 K
VBoxTray.exe                1940 Console                 0      3,196 K
ctfmon.exe                  1948 Console                 0      3,292 K
cmd.exe                     1284 Console                 0      2,576 K
tasklist.exe                 124 Console                 0      4,584 K

Registering Event Handlers

>>> def test(event):
>>>    print("scancode received: %r" % event.scancodes)
>>>
>>> session.console.keyboard.set_on_guest_keyboard(test)
140448201250560
scancode received: [35]
scancode received: [23]
scancode received: [163]
scancode received: [151]
scancode received: [57]

Powering-Down a Machine

>>> session.console.power_down()

License

Apache-2.0

virtualbox-python's People

Contributors

acsc-cyberlab avatar d4rkc4t avatar dd-ssc avatar dontcare avatar dwattttt avatar eisensheng avatar iondex avatar maxfragg avatar mjdorma avatar nightrune avatar nilp0inter avatar olssonsimon avatar sethmichaellarson avatar sethmlarson avatar toblu302 avatar wndhydrnt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

virtualbox-python's Issues

Failed to find attribute display in <virtualbox.library_ext.console.IConsole object

import virtualbox
vbox = virtualbox.VirtualBox()
print("VM(s):\n + %s" % "\n + ".join([vm.name for vm in vbox.machines]))
vm = vbox.find_machine('Windows')
session = vm.create_session()
h, w, _, _, _, _= session.console.display.get_screen_resolution(0)
png = session.console.display.take_screen_shot_png_to_array(0, h, w)

gives the follwing error:

raise AttributeError("Failed to find attribute %s in %s" % (name, self))
AttributeError: Failed to find attribute display in <virtualbox.library_ext.console.IConsole object at 0x00000237D28EE710>
Win32 exception occurred releasing IUnknown at 0xd2ac9730

deleteConfig fix not needed anymore

I'm using the latest virtualbox version and the current delete_config functions is not working.
It calls the "delete" function as described in the comment.
But know the original works.

I changed 'delete' to 'deleteConfig' and it works

import_vboxapi contextmanager fails to find pywin32 packages if python not installed in C:\PythonXX

Python isn't installed in C:\pythonXX on my system, so the extra packages defined on line 40 are not found, and ImportError is re-raised at line 71 even tho all the necessary packages are installed. Calling virtualbox.VirtualBox() again does not throw the exception because 'C:\\Program Files\\Oracle\\VirtualBox\\sdk\\install' is added to the path on the first call.

In [2]:

import virtualbox
In [3]:

vbapi = virtualbox.VirtualBox()
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-3-eb9fceae80cf> in <module>()
----> 1 vbapi = virtualbox.VirtualBox()

C:\Python27\ipythonenv\lib\site-packages\virtualbox\library_ext\vbox.pyc in __init__(self, interface, manager)
     15             self._i = manager.get_virtualbox()._i
     16         else:
---> 17             manager = virtualbox.Manager()
     18             self._i = manager.get_virtualbox()._i
     19 

C:\Python27\ipythonenv\lib\site-packages\virtualbox\__init__.pyc in __init__(self, mtype, mparams)
    101             raise RuntimeError("Can not create a new manager following a system exit.")
    102         if pid not in _managers:
--> 103             with import_vboxapi() as vboxapi:
    104                 self.manager = vboxapi.VirtualBoxManager(mtype, mparams)
    105 

C:\Python27\ArcGIS10.1\Lib\contextlib.pyc in __enter__(self)
     15     def __enter__(self):
     16         try:
---> 17             return self.gen.next()
     18         except StopIteration:
     19             raise RuntimeError("generator didn't yield")

C:\Python27\ipythonenv\lib\site-packages\virtualbox\__init__.pyc in import_vboxapi()
     32     """
     33     try:
---> 34         import vboxapi
     35     except ImportError:
     36         system = platform.system()

ImportError: No module named vboxapi

In [4]:

vbapi = virtualbox.VirtualBox()

Bug spotted

In clone() (library_ext/machine.py), there is a wrong check of snapshot_name_or_id for if it's in a list of [str, unicode], instead of checking whether it's an instance of str or unicode (which is the check I believe the author intended to do).

Unable to import appliance!

Im new to pyvbox
I tried to import an ovf file but get this error
virtualbox.library.OleErrorFail: 0x80004005 (Cannot interpret appliance without reading it first (call read() before interpret()))

this is the code

import virtualbox
vbox = virtualbox.VirtualBox()
apl = vbox.create_appliance()
apl.read('~/Documents/ubuntu.ova')

why before reading completion , interpret is called!

ValueError screen_id @ get_screen_resolution

Environment:
-Python 2.7.10+
-Debian 8.2
-pyvbox 0.2.2
-5.0.10_Debian

I'm trying to make a screenshot but it seems that I can't find the screen ID...

In [1]: import virtualbox

In [2]: vbox = virtualbox.VirtualBox()

In [3]: vm = vbox.find_machine('Win7_64')

In [4]: vm.launch_vm_process()
Out[4]: <virtualbox.library_ext.progress.IProgress at 0x7f650efecbd0>

In [5]: session = vm.create_session()

In [6]: h, w, _, _, _, _ = session.console.display.get_screen_resolution(0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-a9fefd67fff5> in <module>()
----> 1 h, w, _, _, _, _ = session.console.display.get_screen_resolution(0)

/usr/local/lib/python2.7/dist-packages/virtualbox/library.pyc in get_screen_resolution(self, screen_id)
  20849             raise TypeError("screen_id can only be an instance of type baseinteger")
  20850         (width, height, bits_per_pixel, x_origin, y_origin) = self._call("getScreenResolution",
> 20851                      in_p=[screen_id])
  20852         return (width, height, bits_per_pixel, x_origin, y_origin)
  20853 

ValueError: too many values to unpack

thanks

xixel

Remove machine not working

This is in python 3.5.2

code:

import virtualbox

vbox = virtualbox.VirtualBox()
vm = vbox.find_machine(<name of your machine>)
vm.remove(delete=True)

output:

if self.state >= library.MachineState.running:
TypeError: unorderable types: MachineState() >= MachineState()

Extend test suite to support Python 3.x

ENVIRONMENT
  • Operating System: Any
  • Python version: 3.x
  • VirtualBox version: Any
  • VirtualBox SDK version: Any
  • pyvbox version: Any
  • Happens in latest master branch?
SUMMARY

Can't run the test suite in Python 3.x

EXPECTED RESULTS

Runs test suite

ACTUAL RESULTS

Errors with NameErrors due to usage of basestring.

IMachine export / export_to / exportTo

I installed pyvbox 0.2.2 using pip install ... on Mac OS X 10.10 and ran into an error

Traceback (most recent call last):
      ...
    description = target_vm.export_to(appliance, appliance_folder)
  File "/Users/<username>/.virtualenvs/pyvbox/lib/python2.7/site-packages/virtualbox/library_ext/machine.py", line 192, in export_to
    in_p=[appliance, location])
  File "/Users/<username>/.virtualenvs/pyvbox/lib/python2.7/site-packages/virtualbox/library_base.py", line 171, in _call
    method = self._search_attr(name)
  File "/Users/<username>/.virtualenvs/pyvbox/lib/python2.7/site-packages/virtualbox/library_base.py", line 152, in _search_attr
    raise AttributeError("Failed to find attribute %s in %s" % (name, self))
AttributeError: Failed to find attribute export in <VM name>

when trying to export an appliance. The comment next to the export_to(...) function in question

    # BUG: xidl describes this function as exportTo.  The interface seems
    #      to export plain "export" instead... 

seems to indicate there is/was a mix-up with function names.

I had to change the code in line 191 from self._call("export", ... to self._call("exportTo", ... to fix the error. My speculation is that the mentioned bug existed previously (i.e. for earlier versions of VirtualBox), but has now been fixed; I'm not entirely sure which parts this concerns, though.

I have installed the latest VirtualBox 5.0.8 r103449 and I presume pyvbox picks up stuff from that.

If you could kindly tell me how to get the version of the underlying VirtualBox Python modules, I'd be happy to try and provide a pull request with version-specific handling.

Pool machine creation hangs, session is not returned

Virtual environment:
Linux machine (RedHat based), a new pool machine is being created (non existed before).

Test code (just a piece):
--- 8< ---
pool = virtualbox.pool.MachinePool("Some Linux Machine")
session = pool.acquire("john", "john1234", "gui")
--- 8< ---

Problem is that it will timeout on this operation and never return a session object, problem seem to be in:
guest.py -> IGuest -> create_session -> line: "session.file_query_info(test_file)" (test for "/bin/sh" file)

It keeps raising exception with error message something like: "object exists but it not a file", the problem is that "/bin/sh" is a link to "bash".

GuestSession failed to start

python 2.7.6
pyvbox 1.0.0
Host OS - Ubuntu 14.04
Guest OS - Windows7, x32
VirtualBox 5.0.16

Hello. I am trying to run program on the guest OS. This is what I do:

vbox = virtualbox.VirtualBox()
session = virtualbox.Session()
vm = vbox.find_machine('Windows7')
vm.launch_vm_process(session, 'gui', '').wait_for_completion()

session = vm.create_session()
time.sleep(35)
gs = session.console.guest.create_session('win7', '')
process, stdout, stderr = gs.execute('C:\\Windows\\System32\\cmd.exe', ['/C', 'tasklist'])
print stdout

VM starts normally, but then:

File "runonguest.py", line 39, in
gs = session.console.guest.create_session('win7', '')
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library_ext/guest.py", line 24, in create_session
raise SystemError("GuestSession failed to start")
SystemError: GuestSession failed to start

What I am doing wrong?
Thank you.

IGuest.create_session() fails with an empty password

ENVIRONMENT
  • Operating System: Any
  • Python version: Any
  • VirtualBox version: 5.1.x
  • VirtualBox SDK version: 5.1.x
  • pyvbox version: 1.0.0
  • Happens in latest master branch?
SUMMARY

When creating an IGuestSession via IGuest.create_session() if a zero-length password is given an error will be raised. This was found originally by @aGGeRReS in issue #47. Proposed fix is to throw a better error message if this error is caught and an empty password is used.

STEPS TO REPRODUCE
vbox = virtualbox.VirtualBox()
session = virtualbox.Session()
vm = vbox.find_machine('Windows7')
vm.launch_vm_process(session, 'gui', '').wait_for_completion()

session = vm.create_session()
gs = session.console.guest.create_session('win7', '')
EXPECTED RESULTS

To login to the Guest Session with an empty password.

ACTUAL RESULTS

Raises an exception

gs = session.console.guest.create_session('win7', '')
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library_ext/guest.py", line 24, in create_session
raise SystemError("GuestSession failed to start")
SystemError: GuestSession failed to start

MachineState as key value

Test:

import virtualbox
import threading

def on_machine_state_changed(event):
    d1 = { virtualbox.pool.MachineState.first_online : "first_online", }
    d2 = { int(virtualbox.pool.MachineState.first_online) : "first_online", }
    print( "{} {} {} {}".format(event.state, repr(event.state), event.state in d1, int(event.state) in d2) )

def thread_routine(cv_stop_thread):
    vbox = virtualbox.pool.VirtualBox()
    callback_id = vbox.register_on_machine_state_changed(on_machine_state_changed)
    cv_stop_thread.acquire()
    cv_stop_thread.wait()
    cv_stop_thread.release()
    virtualbox.events.unregister_callback(callback_id)

def main():
    cv_stop_thread = threading.Condition()
    thread = threading.Thread(target=thread_routine, args=(cv_stop_thread, ))
    thread.start()
    raw_input("Press <ENTER>...")
    cv_stop_thread.acquire()
    cv_stop_thread.notify()
    cv_stop_thread.release()
    thread.join()

if __name__ == "__main__":
    main()

Output (without casting to int does not work):

FirstOnline MachineState(5) False True

A simple case is working properly:

>>> d = {virtualbox.pool.MachineState.first_online: "first_online", }
>>> virtualbox.pool.MachineState.first_online in d
True

Environment:

Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import virtualbox
>>> virtualbox.version.__version__
'0.2.2'

Vboxapi module not found

Hi
Last week, I have installed pyvbox on my ubuntu machine. Whenever import the virtualbox module, throws an error vboxapi module not found. I tried to intsall the package using pip(pip install vboxapi).
"Could not find a version that satisfies the requirement vboxapi (from versions)"
Please let me know, How can i install the vboxapi package using pip.

Move CHANGELOG to project root

There's no change log that shows the history of the module. Would be a good idea to start tracking changes now that we're 1.0.0.

unable to create full machine clone

Sorry if i'm missing this. But using the API below I'm able to create what I think are linked clones

self.clone = virtualbox.library.IMachine.clone(self.BASE,
mode=self.CLONE_MODE,
groups=["/pool"],
basefolder=self.data_dir)

CLONE_MODE is (1) or machine_state.

What mode/option combo creates a full machine clone. I can seem to find it

pyvbox unusable (on archlinux at least)

Hi,

it seems like pyvbox is currently unusable at least on archlinux if run inside a virtualenv. There are a few issues actually underneath this issue that prevents it from working properly.

For the first issue the arch linux packaging team should be blamed for. The virtualbox-sdk relevant packages are installed inside site-packages instead of dist-packages. From the code it looks like Pyvbox should support multiple modules pathes to look inside. It doesn't fail gracefully if the desired modul path itself doesn't exist at all though.

The second issue arouses from the sys.path manipulation and reversion. The vboxapi module modifies the sys.path so that Python can find the VirtualBox relevant binary modules. The import_vboxapi function reverts those changes to sys.path after the vboxapi module has been imported though. So the next call to vboxapi.VirtualBoxManager will fail because it can't find the binary modules anymore.

If allowed/desired I wold like to take care of these issues and provide a pull request when it's done.

gs.execute with stdin does not work properly

/usr/local/lib/python2.7/dist-packages/pyvbox-0.1->py2.7.egg/virtualbox/library_ext/guest_session.pyc in execute(self, command, >arguments, stdin, environment, flags, priority, affinity, timeout_ms)
59 while index < len(stdin):
60 index += process.write(0, [library.ProcessInputFlag.none],
---> 61 stdin[index:], 0)
62 process.write(0, [library.ProcessInputFlag.end_of_file], 0)
63

/usr/local/lib/python2.7/dist-packages/pyvbox-0.1-py2.7.egg/virtualbox/library.pyc in >write(self, handle, flags, data, timeout_ms)
13748 raise TypeError("handle can only be an instance of type baseinteger")
13749 if not isinstance(flags, baseinteger):
13750 raise TypeError("flags can only be an instance of type baseinteger")
13751 if not isinstance(data, list):
13752 raise TypeError("data can only be an instance of type list")

TypeError: flags can only be an instance of type baseinteger

i get this error, when ever trying to use execute with input.

calling process.write() manualy with 0 instead of [library.ProcessInputFlag.none] seams to work, but then i get a type error for the stdin, no matter what i put there, it really should be a string, right?
I'm not really sure, but it looks like the error checks in the process.write() don't work properly.
And the following process.write(0, [library.ProcessInputFlag.end_of_file], 0) will probably fail as well, since write takes exactly 5 arguments and omitting stdin will probably crash as well.

alter groups on an existing machine (IMachine)

Attempting to adjust the group for an already registered virtual machine, see example below:

import virtualbox
vbox = virtualbox.VirtualBox()
machine = vbox.find_machine('win7')
-> <virtualbox.library_ext.machine.IMachine at 0x7f08108ed350>
machine.groups
-> [u'/']
type(machine.groups)
-> list

At ths point the list cannot be appended, replace, pop etc.

How to take a screenshot

I want to take a screenshot and save it as png format. I tried take_screen_shot_to_array. But I don't know how to put the last argument, bitmap_format. Please give me a example.

gs.execute - Can not find enumeration where value=None

The code:

process, stdout, stderr = gs.execute('C:\Windows\System32\cmd.exe', ['/C', 'tasklist'])

Returns this error:

Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library_ext/guest_session.py", line 54, in execute
process.wait_for(int(library.ProcessWaitResult.start), 0)
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library.py", line 13666, in wait_for
reason = ProcessWaitResult(reason)
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library.py", line 121, in init
raise ValueError("Can not find enumeration where value=%s" % value)
ValueError: Can not find enumeration where value=None

How to clone VM?

Hey!
Very useful module!
But there is one problem.
What if have 1 clean machine that i need to clone, naming clones lets say 01...NN ?

xpcom.Exception: 0x80070005 (The object functionality is limited)

Hi,

I'm working on #15 , writing some tests and I found this:

>>> import virtualbox
>>> [m.name for m in virtualbox.VirtualBox().machines]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "virtualbox/library.py", line 8782, in name
    ret = self._get_attr("name")
  File "virtualbox/library_base.py", line 144, in _get_attr
    attr = self._search_attr(name, prefix='get')
  File "virtualbox/library_base.py", line 135, in _search_attr
    attr = getattr(self._i, attr_name, None)
  File "/usr/lib/virtualbox/sdk/bindings/xpcom/python/xpcom/client/__init__.py", line 374, in __getattr__
    return getattr(interface, attr)
  File "/usr/lib/virtualbox/sdk/bindings/xpcom/python/xpcom/client/__init__.py", line 460, in __getattr__
    return XPTC_InvokeByIndex(self._comobj_, method_index, args)
xpcom.Exception: 0x80070005 (The object functionality is limited)

I'm using the current HEAD of your repository. But I also tested with the last PyPI version with same results.

I don't know if there is something wrong in my setup. Any hints?

More Python3 issues

Importing with ipython3 (v 0.13.2) fails, since the pythonic_name creation for enums in library seams not to work

/usr/local/lib/python3.3/dist-packages/pyvbox-0.1.2-py3.3.egg/virtualbox/__init__.py in <module>()
      9 from threading import current_thread
     10 
---> 11 from virtualbox.library_ext import library
     12 
     13 __doc__ = library.__doc__

/usr/local/lib/python3.3/dist-packages/pyvbox-0.1.2-py3.3.egg/virtualbox/library_ext/__init__.py in <module>()
      2 
      3 import virtualbox
----> 4 from virtualbox import library
      5 
      6 """

/usr/local/lib/python3.3/dist-packages/pyvbox-0.1.2-py3.3.egg/virtualbox/library.py in <module>()
  23192 
  23193 
> 23194 class IMachineEvent(IEvent):
  23195     """
  23196     Base abstract interface for all machine events.

/usr/local/lib/python3.3/dist-packages/pyvbox-0.1.2-py3.3.egg/virtualbox/library.py in IMachineEvent(__locals__)
  23198     __uuid__ = '92ed7b1a-0d96-40ed-ae46-a564d484325e'
  23199     __wsmap__ = 'managed'
> 23200     id = VBoxEventType.machine_event
  23201     @property
  23202     def machine_id(self):

AttributeError: type object 'VBoxEventType' has no attribute 'machine_event'

Is this package licensed under MIT or Apache-2.0?

Just noticed this difference while looking at setup.py. Within setup.py it seems that the package is licensed under Apache-2.0 but looking at the contents of LICENSE it shows that the package is licensed under MIT.

Which of these is correct? When that's determined the other should be fixed.
cc: @mjdorma

IMedium.create_base_storage() logical_size argument only accepts integers

logical_size argument is the size of the storage medium in bytes. In Python longs are also ints!

>>> isinstance(10*1024, int) # 10kb
True
>>> isinstance(10*1024*1024, int) #10mb
True
>>> isinstance(10*1024*1024*1024, int) # 10gb
False

Fix: Allow integers as well as longs to allow large hard drive sizes.

>>> isinstance(10*1024*1024*1024*1024, (int, long)) # 10tb
True

I will attach a fork which implements this fix.

Can't start guest session on new VirtualBox (ValueError: Can not find enumeration where value=None).

Like issue #14. Only I have new VirtualBox and pyvbox:
Ubuntu 14.04.01 LTS x64
VirtualBox 4.3.18 r96516
python 2.7.6
pyvbox new from repository (2da4fba)

This code:

import virtualbox
vbox = virtualbox.VirtualBox()
m = vbox.machines[0]
s = m.create_session()
s.console.guest.create_session('beta', 'beta')

results in the next backtrace:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pyvbox-0.2.0-py2.7.egg/virtualbox/library_ext/guest.py", line 20, in create_session
    if session.status == library.GuestSessionStatus.started:
  File "/usr/local/lib/python2.7/dist-packages/pyvbox-0.2.0-py2.7.egg/virtualbox/library.py", line 15821, in status
    return GuestSessionStatus(ret)
  File "/usr/local/lib/python2.7/dist-packages/pyvbox-0.2.0-py2.7.egg/virtualbox/library_base.py", line 63, in __init__
    raise ValueError("Can not find enumeration where value=%s" % value)
ValueError: Can not find enumeration where value=None

Running on Mac OS X got Segmentation fault: 11

Hello,
I used this module on OS X Yosemite in ipython after I typed vbox = virtualbox.VirtualBox() then got Segmentation fault: 11

Does someone encounter this problem? How to fix it?

Ubuntu has no this issue.

The detail message
$ ipython
Python 2.7.8 (default, Oct 18 2014, 00:36:49)
Type "copyright", "credits" or "license" for more information.

IPython 2.3.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.

In [1]: import virtualbox

In [2]: vbox = virtualbox.VirtualBox()
Segmentation fault: 11

Failed to find attribute videoCaptureFile

I tried to run example of capturing video (https://gist.github.com/mjdorma/9045317) and got the following error:

Traceback (most recent call last):
  File "capture_video.py", line 13, in <module>
    session.machine.video_capture_file = os.path.abspath("test.webm")
  File "/usr/local/lib/python2.7/dist-packages/pyvbox-0.2.2-py2.7.egg/virtualbox/library.py", line 9049, in video_capture_file
    return self._set_attr("videoCaptureFile", value)
  File "/usr/local/lib/python2.7/dist-packages/pyvbox-0.2.2-py2.7.egg/virtualbox/library_base.py", line 163, in _set_attr
    attr = self._search_attr(name, prefix='set')
  File "/usr/local/lib/python2.7/dist-packages/pyvbox-0.2.2-py2.7.egg/virtualbox/library_base.py", line 152, in _search_attr
    raise AttributeError("Failed to find attribute %s in %s" % (name, self))
AttributeError: Failed to find attribute videoCaptureFile in Windows 7

I just renamed win7 to Windows 7 .

Environment:
-Python 2.7.3
-Ubuntu 12.04.5
-pyvbox-0.2.2
-Virtual Box 4.1.18r78361

VM does not start: The session is not locked (state: Spawning)

Environment:
-Python 2.7.3
-Ubuntu 12.04.5
-pyvbox-0.2.2
-Virtual Box 4.3.30

I'm trying to launch virtual machine by means virtualbox python api but VM does not launch. Here is the log:

In [1]: import virtualbox

In [2]: vbox = virtualbox.VirtualBox()

In [3]: print("VM(s):\n + %s" % "\n + ".join([vm.name for vm in vbox.machines]))
VM(s):
 + win_7
 + eclipse_video

In [4]: session = virtualbox.Session()

In [5]: vm = vbox.find_machine('win_7')

In [6]: progress = vm.launch_vm_process(session, 'gui', '')

In [7]: h, w, _, _, _ = session.console.display.get_screen_resolution(0)
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-7-22abc05fadf4> in <module>()
----> 1 h, w, _, _, _ = session.console.display.get_screen_resolution(0)

/usr/local/lib/python2.7/dist-packages/pyvbox-0.2.2-py2.7.egg/virtualbox/library.pyc in console(self)
  24089         Console object associated with this session.
  24090         """
> 24091         ret = self._get_attr("console")
  24092         return IConsole(ret)
  24093 

/usr/local/lib/python2.7/dist-packages/pyvbox-0.2.2-py2.7.egg/virtualbox/library_base.pyc in _get_attr(self, name)
    153 
    154     def _get_attr(self, name):
--> 155         attr = self._search_attr(name, prefix='get')
    156         if inspect.isfunction(attr) or inspect.ismethod(attr):
    157             return self._call_method(attr)

/usr/local/lib/python2.7/dist-packages/pyvbox-0.2.2-py2.7.egg/virtualbox/library_base.pyc in _search_attr(self, name, prefix)
    140         for i in range(3):
    141             for attr_name in attr_names:
--> 142                 attr = getattr(self._i, attr_name, self)
    143                 if attr is not self:
    144                     break

/usr/lib/virtualbox/sdk/bindings/xpcom/python/xpcom/client/__init__.py in __getattr__(self, attr)
    372                 self.QueryInterface(iid)
    373                 interface = self.__dict__['_interfaces_'][iid]
--> 374             return getattr(interface, attr)
    375         # Some interfaces may provide this name via "native" support.
    376         # Loop over all interfaces, and if found, cache it for next time.

/usr/lib/virtualbox/sdk/bindings/xpcom/python/xpcom/client/__init__.py in __getattr__(self, attr)
    458                 raise RuntimeError, "Can't get properties with this many args!"
    459             args = ( param_infos, () )
--> 460             return XPTC_InvokeByIndex(self._comobj_, method_index, args)
    461 
    462         # See if we have a method info waiting to be turned into a method.

Exception: 0x8000ffff (The session is not locked (session state: Spawning))

Thank you,
Alex

Failed to create clone

Hello everyone, I am having troubles launching a VM. When I try to start the VM like this:
import virtualbox vm = virtualbox.VirtualBox().find_machine('test') session = vm.create_session() s = virtualbox.Session() vm.launch_vm_process()

I get an error saying (The machine 'test' is already locked by a session (or being locked or unlocked))

When I try to unlock the machine, it says that it's not locked.

But then when I try to lock it, using this command: vm.create_session(lock_type=virtualbox.library.LockType.write)

I get the following error: Failed to create clone - 0x80bb0007 (The machine 'test' is already locked for a session (or being unlocked))

Can anyone help me with this?

Thanks!

Tuple vs Dict in PlatformWEBSERVICE

Pretty small error. I was attempting to use your WebServiceManager for remote control for some tests, and I happened across this bug.

Error Log:

C:\Python27\python.exe C:/Local_Sean/dBA_Sean_Sill/Clients/Eclipse_Computing/VirtualBoxTestingEnv/main.py
Traceback (most recent call last):
File "C:/Local_Sean/dBA_Sean_Sill/Clients/Eclipse_Computing/VirtualBoxTestingEnv/main.py", line 11, in
manager = virtualbox.WebServiceManager()
File "C:\Python27\lib\site-packages\virtualbox__init__.py", line 179, in init
super(WebServiceManager, self).init("WEBSERVICE", params)
File "C:\Python27\lib\site-packages\virtualbox__init__.py", line 101, in init
self.manager = vboxapi.VirtualBoxManager(mtype, mparams)
File "C:\Python27\lib\site-packages\vboxapi__init__.py", line 959, in init
self.platform = PlatformWEBSERVICE(dPlatformParams);
File "C:\Python27\lib\site-packages\vboxapi__init__.py", line 838, in init
self.user = dParams.get("user", "")
AttributeError: 'tuple' object has no attribute 'get'

Looks like PlatformWEBSERVICE was expecting a dict instead of a tuple.
I'll try to submit a patch quickly.

remove() in library_ext throws OSError

When delete_config(media) is being executed - the settings_dir directory is being deleted.
Then, the remove() method tries to delete the settings_dir by calling to shutil.rmtree(settings_dir).
It fails with an OSError, as it doesn't exist anymore.

safearray issue on windows with win32com

I tried to use pyvbox, but had some issues with win32com complaining about safearrays. It seems it only accepts base types. So if Enums are passed it complains...
I edited the function _set_attr to check if value is an instance of enum and if it is i convert it to int. Works so far on windows, i don't know if this affects linux systems

Problem creating medium

When tried to create a medium using:

vbox = virtualbox.VirtualBox()

bus = virtualbox.library.StorageBus(2)

vm.add_storage_controller("SATA", bus)

access_mode = virtualbox.library.AccessMode(2)

device_type = virtualbox.library.DeviceType(3)

medium = vbox.create_medium("VDI", vm_hd_path, access_mode, device_type)

medium.create_base_storage()

medium = vbox.open_medium(vm_hd_path, device_type, access_mode, True)

vm.attach_device(vm_hd_name, 0, 0, device_type, medium)

I got the following error:

Traceback (most recent call last):
File "environment_configuration.py", line 268, in
enviroment.method()
File "environment_configuration.py", line 211, in method
medium = vbox.create_medium("VDI", vm_hd_path, access_mode, device_type)
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library.py", line 7289, in create_medium
in_p=[format_p, location, access_mode, a_device_type_type])
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library_base.py", line 170, in _call
method = self._search_attr(name)
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library_base.py", line 151, in _search_attr
raise AttributeError("Failed to find attribute %s in %s" % (name, self))
AttributeError: Failed to find attribute createMedium in <virtualbox.library_ext.vbox.IVirtualBox object at 0x7f03459e5650>

get_screen_resolution - ValueError: need more than 3 values to unpack

The code:

h, w, d = session.console.display.get_screen_resolution(0)

returns this error:

Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library.py", line 18126, in get_screen_resolution
in_p=[screen_id])
ValueError: need more than 3 values to unpack

Python script errors using pyvbox on Windows

Hi,
After completing a script run to control a VirtualBox guest, the script ends with:

Exception RuntimeError: 'sys.meta_path must be a list of import hooks' in bound method VirtualBoxManager._ del _ of vboxapi.VirtualBoxManager object at 0x0000000002D7F0B8 ignored

I assume this is because something is still open or allocated; session.unlock_machine() doesn't help.

My question: is this a pyvbox bug, or vboxapi bug?

Example of appliance import with name changed.

Hi,

I've successfully import one appliance using the API, but I can't figure out how to change the name of the new machine at import time.

I think that I need to use IVirtualSystemDescription.get_description() and IVirtualSystemDescription.set_final_values() but I cannot figure how; maybe the documentation is too confusing at this point.

Could you give me an example or some tips?

Thank you very much!

Unable to create shared folder with pyvbox

Python       : 2.7.5
pyvbox       : 1.0.0
Host OS      : CentOS 7.2 x64
VirtualBox   : VirtualBox-5.0-5.0.20_106931_el7-1.x86_64
Guest OS     : Windows 2012 R2 x64

Unable to create a shared folder between the Host and Guest using pyvbox, trying to accomplish the same result as the following command:
vboxmanage sharedfolder add Windows2012_64_base --name exports --hostpath /tmp --automount

Code:

import virtualbox

vbox = virtualbox.VirtualBox()

vm = vbox.find_machine("Windows2012_64_base")

vm.create_shared_folder(
        name="export",
        host_path="/tmp",
        writable=True,
        automount=True
)

Output (Guest powered off)

Traceback (most recent call last):
  File "vbox_portion.py", line 81, in <module>
    automount=True
  File "/root/cc/packer/env/lib/python2.7/site-packages/virtualbox/library.py", line 12445, in create_shared_folder
    in_p=[name, host_path, writable, automount])
  File "/root/cc/packer/env/lib/python2.7/site-packages/virtualbox/library_base.py", line 172, in _call
    return self._call_method(method, in_p=in_p)
  File "/root/cc/packer/env/lib/python2.7/site-packages/virtualbox/library_base.py", line 198, in _call_method
    raise errobj
virtualbox.library.VBoxErrorInvalidVmState: 0x80bb0002 (The machine is not mutable or running (state is PoweredOff))

Output (Guest powered on)

Traceback (most recent call last):
  File "vbox_portion.py", line 81, in <module>
    automount=True
  File "/root/cc/packer/env/lib/python2.7/site-packages/virtualbox/library.py", line 12445, in create_shared_folder
    in_p=[name, host_path, writable, automount])
  File "/root/cc/packer/env/lib/python2.7/site-packages/virtualbox/library_base.py", line 172, in _call
    return self._call_method(method, in_p=in_p)
  File "/root/cc/packer/env/lib/python2.7/site-packages/virtualbox/library_base.py", line 198, in _call_method
    raise errobj
virtualbox.library.VBoxErrorInvalidVmState: 0x80bb0002 (The machine is not mutable or running (state is Running))

Let me know if there's any further detail I can provide, thanks!

restoreSnapshot trouble

Hi, I'm having a hard time restoring a machine from a snapshot. This is one of the many things that I've tried, and this has gotten me the closest:

`import virtualbox

vm = virtualbox.VirtualBox().find_machine('test')
vm.restoreSnapshot()`

but then I get the error: AttributeError: 'IMachine' object has no attribute 'restoreSnapshot'

and by reading this page on the documentation (https://www.virtualbox.org/sdkref/interface_i_machine.html#a5b696740ceccb14750718e2648d6928c) it seems as though iMachine does have an attribute of restoreSnapshot. Any ideas?

Can't start guest session (ValueError: Can not find enumeration where value=None).

Hi,

I'm trying to start a guest session but it seems that something it's not initialized properly.

My setup:

  • python 2.7.3
  • pyvbox==0.1.4
  • Debian 7.4 (Wheezy) amd64
  • virtualbox 4.1.18-dfsg-2+deb7u2 amd64 (I've tried it with 4.2 also)

The traceback:

In [1]: import virtualbox
In [2]: session = virtualbox.Session()
In [4]: vbox = virtualbox.VirtualBox()
In [5]: machine = vbox.find_machine('box20')
In [6]: machine.launch_vm_process(session, 'gui', '').wait_for_completion()  # Here I wait a few until machine boots up.
In [8]: gs=session.console.guest.create_session('Roger', '')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-67037dd6c3ec> in <module>()
----> 1 gs=session.console.guest.create_session('Roger', '')

/home/nil/Envs/bugcuckoo/local/lib/python2.7/site-packages/virtualbox/library_ext/guest.pyc in create_session(self, user, password, domain, session_name, timeout_ms)
     18                                                     session_name)
     19         for i in range(50):
---> 20             if session.status == library.GuestSessionStatus.started:
     21                 break
     22             time.sleep(0.1)

/home/nil/Envs/bugcuckoo/local/lib/python2.7/site-packages/virtualbox/library.pyc in status(self)
  15216         """
  15217         ret = self._get_attr("status")
> 15218         return GuestSessionStatus(ret)
  15219 
  15220     @property

/home/nil/Envs/bugcuckoo/local/lib/python2.7/site-packages/virtualbox/library_base.pyc in __init__(self, value)
     64     def __init__(self, value=None):
     65         if value not in self._lookup_label:
---> 66             raise ValueError("Can not find enumeration where value=%s" % value)
     67         self._value = value
     68         self.__doc__ = self._lookup_doc[self._value]

ValueError: Can not find enumeration where value=None

Thank you for this great package.

TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.

ENVIRONMENT
  • Operating System: Windows 7 64bits
  • Python version: Python 2.7.13 64bits
  • VirtualBox version: 5.1.22 r115126 (Qt5.6.2)
  • VirtualBox SDK version: vboxapi.py 109501 2016-08-03 09:51:47Z
  • pyvbox version: 1.0.0
SUMMARY

I am trying to set the network adapter type to virtualbox.library.NetworkAdapterType.i82540_em but I'm getting some error.

STEPS TO REPRODUCE

network_adapter = vm.get_network_adapter(0) # 0 - first adapter
network_adapter.adapter_type = virtualbox.library.NetworkAdapterType.i82540_em

EXPECTED RESULTS

I expect to set the network adapter type to virtualbox.library.NetworkAdapterType.i82540_em

ACTUAL RESULTS

network_adapter.adapter_type = virtualbox.library.NetworkAdapterType.i82540_em
File "C:\Python27\lib\site-packages\virtualbox\library.py", line 22755, in adapter_type
return self._set_attr("adapterType", value)
File "C:\Python27\lib\site-packages\virtualbox\library_base.py", line 166, in _set_attr
return setattr(self.i, name, value)
File "C:\Python27\lib\site-packages\vboxapi_init
.py", line 193, in _CustomSetAttr
return g_dCOMForward['setattr'](self, ComifyName(sAttr), oValue)
File "C:\Python27\lib\site-packages\win32com\client_init
.py", line 474, in setattr
self.oleobj.Invoke(*(args + (value,) + defArgs))
TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.
Win32 exception occurred releasing IUnknown at 0x005ea9c8
Win32 exception occurred releasing IUnknown at 0x0062eb28
Win32 exception occurred releasing IUnknown at 0x0062ec08

take_snapshot failed

Hello, I use IConsole.take_snapshot() to creates a new snapshot. But it is failed to find attribute takeSnapshot in <virtualbox.library_ext.console.IConsole object.

My script is:

In [1]: import virtualbox

In [2]: vbox = virtualbox.VirtualBox()

In [3]: vm = vbox.find_machine('test')

In [4]: session = virtualbox.Session()

In [5]: progress = vm.launch_vm_process(session, 'gui', '')

In [6]: session.console.pause()

In [7]: session.console.take_snapshot('a', 'aaa')

And it is failed such as:

C:\Python27\lib\site-packages\virtualbox\library.pyc in take_snapshot(self, name, description)
  13200             raise TypeError("description can only be an instance of type basestring")
  13201         progress = self._call("takeSnapshot",
> 13202                      in_p=[name, description])
  13203         progress = IProgress(progress)
  13204         return progress

C:\Python27\lib\site-packages\virtualbox\library_base.pyc in _call(self, name, in_p)
    169     def _call(self, name, in_p=[]):
    170         global vbox_error
--> 171         method = self._search_attr(name)
    172         if inspect.isfunction(method) or inspect.ismethod(method):
    173             return self._call_method(method, in_p=in_p)

C:\Python27\lib\site-packages\virtualbox\library_base.pyc in _search_attr(self, name, prefix)
    150                 time.sleep(0.1)
    151         else:
--> 152             raise AttributeError("Failed to find attribute %s in %s" % (name, self))
    153         return attr
    154

AttributeError: Failed to find attribute takeSnapshot in <virtualbox.library_ext.console.IConsole object at 0x0000000004A479B0>

My Enviroment is:

+ Python 2.7.10 64bit
+ pyvbox 0.2.2
+ VirtualBox 5.0.10
+ Windows 10 x64

Can you help me? I don't know why I will be failed. Thank you. :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.