Description of some functions of the pysphere VMware control module


Obtaining virtual machine objects for virtual machine operations
  After you connect to the server normally, you can use the following two methods to obtain virtual machine objects.

  • get_vm_by_path
  • get_vm_by_name

  The virtual machine path can be obtained from "Virtual Machine Configuration File" in the Options tab of "Edit settings..." in the right-click information of the virtual machine.

! Note that
  it is recommended to use the virtual machine path to the virtual machine object. For a virtual machine, the path is unique, and the name may be repeated. Of course, we will talk about how to use the qualification parameters to reduce the repetition later, but once there is a repeated result , the function returns only the first result found.


>from pysphere import VIServer
>server = VIServer()
>server.connect("192.168.100.100", "[email protected]
", "vmware")
>vm1 = server.get_vm_by_path("[DataStore1] Ubantu/Ubantu-10 .vmx")
>vm2 = server.get_vm_by_name("Windows XP Professional") How
  to use additional qualifications

>vm1 = server.get_vm_by_path("[DataStore1] Ubuntu/Ubuntu-10.vmx", "DEVELOPMENT")
>vm2 = server.get_vm_by_name("Windows XP Professional", "IT")
  The qualification is that datacenter
gets virtual machine status

>print vm1.get_status()
  returns the result as string type 
* 'POWERED ON' 
* 'POWERED OFF' 
* 'SUSPENDED' 
* 'POWERING ON' 
* 'POWERING OFF' 
* 'SUSPENDING' 
* 'RESETTING' 
* 'BLOCKED ON MSG' 
* 'REVERTING TO SNAPSHOT'
  The first three are the basic states, and the virtual machine will generally be in these three states. 

Servers such as "VMware Server/ESX/ESXi" do not support query history actions, they will only return the basic status. 

You can also use parameters to limit the return to only the basic status

>print vm1.get_status(basic_status=True)
  You can also query whether the virtual machine is in a certain status

>print vm1.is_powering_off()
>print vm1.is_powered_off()
>print vm1.is_powering_on()
>print vm1.is_powered_on()
>print vm1.is_suspending()
>print vm1.is_suspended()
>print vm1.is_resetting()
>print vm1.is_blocked_on_msg()
>print vm1.is_reverting()
to get the virtual machine Basic properties

  • get_properties
  • get_property(property_name)

  get_properties returns a python dictionary type data containing all available properties at query time. 

get_property returns the value of a specified property, or None if the property does not exist

>vm1.get_properties()
{'guest_id': 'ubuntuGuest',
'path': '[DataStore1] Ubuntu/Ubuntu-10.vmx',
' guest_full_name': 'Ubuntu Linux (32-bit)',
'name': 'Ubuntu 10.10 Desktop 2200',
'mac_address': '00:50:56:aa:01:a7'
}

>print vm1.get_property('mac_address ') 
'00:50:56:aa:01:a7'
  For some reason, when pysphere creates a virtual machine instance, all attribute values ​​are cached, and the cache is updated every time an attribute is requested, and these attributes are It changes from time to time. If you need to get the latest property value, you need to add the from_cache=False parameter

> print vm1.get_property('ip_address', from_cache=False)
> print vm1.




* guest_full_name 
* hostname 
* ip_address 
* mac_address 
* net
get resource pool name
  Execute the following statement to get the resource pool name of the virtual machine


> print vm1.get_resource_pool_name() 
Linux VMs
change the virtual machine power state
  Execute the following statement to operate the virtual machine power

> vm1. power_on()
>vm1.reset()
>vm1.suspend() #since pysphere 0.1.5
>vm1.power_off()
  By default, the above statements will be executed synchronously, that is to say, this method will not exit until the virtual machine is finished. . 

If asynchronous execution is required, the sync_run=False parameter needs to be added. Under asynchrony, the method returns a task object, which is used to query the execution progress and results. 

The use of task objects will be explained later.

>task1 = vm1.power_on(sync_run=False)
>task2 = vm2.reset(sync_run=False)
>task3 = vm2.suspend(sync_run=False) #since pysphere 0.1.5
>task4 = vm3.power_off(sync_run=False)
  In addition, there is a host parameter, I don't understand what it is worth, please leave a message for those who know it.

>vm1.power_on(host="esx3.example.com")
operation
  snapshot There are three operations for snapshot: restore, create, delete.
  1) Let's take a look at recovery first. 

There are three ways to restore a virtual machine to a snapshot.

  • revert_to_snapshot : revert to the latest snapshot
  • revert_to_named_snapshot : Revert to the first snapshot that matches the given name. The rules are unclear and need to be tested.
  • revert_to_path : Revert to the snapshot indicated by the specified path or index. The index parameter is used to specify the update number of snapshots of the same path, and the default is 0. The usage method is: vm1.revert_to_path(“/base/updated”, index=1)

  Similar to virtual machine power control, operational snapshots are performed synchronously by default. If you need to execute asynchronously, you need to execute it in the following way.

>task1 = vm1.revert_to_snapshot(sync_run=False)
>task2 = vm2.revert_to_named_snapshot("base", sync_run=False)
>task3 = vm3.revert_to_path("/base/updated", sync_run=False)
  also has a host parameter, Still don't understand, update after figuring it out


>vm1.revert_to_snapshot(host="esx1.example.com")
>vm1.revert_to_named_snapshot(host="esx2.example.com")
>vm1.revert_to_path(host="esx3.example. com")
  2) Let's take a look at deleting snapshots
  Similar to recovery, there are three ways to delete

  • delete_current_snapshot
  • delete_named_snapshot(name)
  • delete_snapshot_by_path(path, index=0)

  Different from restore, delete has a special remove_children parameter, but when this parameter is set to True, all child snapshots of the specified snapshot will be deleted.
  3) Create a snapshot
  The following statement is used to create a snapshot of the current moment

> vm1. create_snapshot("mysnapshot")
  If you need a description for this snapshot, use the description parameter to implement

>vm1.create_snapshot("mysnapshot", description="With SP2 installed")
  Creating a snapshot can also use the sync_run parameter to execute asynchronously.
  In pysphere 0.1.6 and above, two unique parameters have been added

  • memory : Defaults to True, including a full memory snapshot, if unsuccessful, the snapshot will be set to shutdown.
  • quiesce : The default value is True, and the snapshot is created according to the disk quiesce mode, which can ensure that the virtual machine and the snapshot are exactly the same when the snapshot is created. This parameter is ignored if the snapshot is taken from a shutdown state, or if VMware tools are not installed.

  4) Get the snapshot list

>snapshot_list = vm2.get_snapshots()
  This gets a snapshot list, and each snapshot instance can use the following method to get the attribute value.

  • get_name : returns the snapshot name
  • get_description : returns the snapshot description
  • get_create_time : returns the snapshot creation time
  • get_parent : Returns the parent snapshot of this snapshot, which is a snapshot instance. Returns None if it is a root snapshot.
  • get_children : Returns the child snapshots of this snapshot, which is a list of snapshots.
  • get_path : Returns the parent-child relationship of the snapshot, separated by '/'.
  • get_state : Returns the power state of the virtual machine when this snapshot was restored.

Operating the internal system of the virtual machine
  1) Power management 

Use the following commands to make the virtual machine shut down, restart, sleep

>vm1.shutdown_guest()
>vm1.reboot_guest()
>vm1.standby_guest()
  2) Log in to the system


>vm1.login_in_guest("os_username ", "os_password")
  Any operation other than power management needs to log in to the system in advance. This operation requires vSphere 5.0 or above, and the virtual machine must have vmware tools installed.
  This operation has no return value and succeeds without exception information.
  3) File and directory operations

  • make_directory(path, create_parents=True) : Create a directory in the virtual machine according to the path parameter, and create all parent directories that do not exist by default. If the create_parents parameter is set to False, the parent directory is not automatically created, and an exception occurs if the parent directory does not exist.
  • move_directory(src_path, dst_path) : Move the directory from src_path to dst_path, generally also used for directory renaming. An exception occurs if the target directory exists.
  • delete_directory(path, recursive) : delete the directory pointed to by path. Recursive must be specified. If True, all subdirectories and files are also deleted. On the contrary, if False, if there are subdirectories or files, an exception will occur.
  • list_files(path, match_pattern=None) : Returns a list of all files and directories in the directory specified by the parameter path, including hidden ones, only one layer is displayed, and no sublayers are displayed. The match_pattern parameter is a perl-compatible regular expression with which we can filter the results. The return value of this method is a list of dictionaries, where each dictionary element contains the following three attributes.

    • path: full path to this file
    • size: file size
    • type: one of the file type directory, file, symlink
  • get_file(guest_path, local_path, overwrite=False) : Get a file from the guest_path in the virtual machine and save it to the local_path of the local machine.
  • send_file(local_path, guest_path, overwrite=False) : Send a file from the local_path of the machine to the guest_path of the virtual machine.
  • move_file(src_path, dst_path, overwrite=False) : Move a file from src_path to dst_path, generally also used for directory renaming. Exception if overwrite is set to False (default is False) and dst_path exists. If set to True, all existing files will be overwritten, except if dst_path is a directory.
  • delete_file(path) : delete the file pointed to by path.

  4) Process operations and environment variables

  • start_process(program_path, args=None, env=None, cwd=None) : Start a program in the virtual machine and return the PID. The parameter program_path is the absolute address of the program. If the program exists in the system environment variable path, you can directly fill in the program name. Program parameters:

    • args: The parameter list of the program, string list type.
    • env: List of environment variables of the program, dictionary list type.
    • cwd: The working directory of the program. is an absolute path. If not set, the default path after system login is used by default. For example, linux is /home/loginuser, and windows is c:\windows\system32.
  • terminate_process(pid) : Kill the process represented by pid.
  • list_processes()*: List all processes running on the system, including the most recent completed processes created with start_process. The result is a list of dictionaries, each of which contains the following properties: 



    • start_time: The creation time of the process.
    • end_time: The end time of the process. It refers to the process created by start_process and has ended within 5 minutes, otherwise returns None.
    • pid: The PID of the process.
    • name: Process name.
    • cmd_line: The complete command line content, including commands and parameters.
    • owner: The user the process belongs to.
    • exit_code: Process return value. It refers to the process created by start_process and has ended within 5 minutes, otherwise returns None.
  • get_environment_variables() : Read all system environment variables. The return value is a list of dictionaries.

Clone VM
  pysphere 0.1.6 provides this functionality.

>new_vm = vm1.clone("Clone Name")
  This method returns a virtual machine instance. In addition to the new virtual machine name that must be specified, the following parameters can be set:

  • sync_run : Whether to execute synchronously, the default value is True. Returns the virtual machine instance when synchronous, and returns the taskid when asynchronous.
  • folder : The target directory for the new virtual machine. If not set, it will be placed in the same directory as the source virtual machine by default.
  • resourcepool : The MOR used by the new virtual machine. If not set, the same resource pool as the source virtual machine is used by default. (I haven't figured out MOR yet, I'll add it later)
  • power_on : Whether to power on the new virtual machine after it is created, the default is True.
  • template : Whether to use the new virtual machine as a template, the default is False.
! Note
  The resourcepool parameter has no effect if a new virtual machine is used as a template. Conversely, if the source VM is a template, the resourcepool parameter must be specified.

Migrate virtual machines


> vm1.migrate()

  • sync_run : synchronous execution
  • priority : the priority, the options are default, high, low.
  • resource_pool</em>: target resource pool
  • host : target host
  • state : The power state in which the migration is performed, if and only if the virtual machine is in the specified state. The options are POWERED ON, POWERED OFF, SUSPENDED.

Handling asynchronous jobs
  There are many methods mentioned above that can specify the sync_run=False parameter for asynchronous execution. 

When executed asynchronously, the method returns an instance of VITask, which contains the following methods:

    • get_state : Returns the state of the job at the current moment. The status is as follows:

      • "error": The job exited abnormally.
      • "queued": The job is in the queue and has not been executed.
      • "running": The job is executing.
      • "success": The job has completed normally.
    • get_error_message : The error description of the job exiting abnormally.
    • wait_for_state(['error','success','running'], timeout=10) : This method waits for the job to appear in a state in the given state list. When waiting, return to this state. An exception occurs if none of the expected states occurs within the seconds specified by timeout.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325425063&siteId=291194637