【vSphere | Python】vSphere Automation SDK for Python Ⅵ—— VM Guest Processes APIs

12. VM APIs

12.1 VM Guest Processes APIs

Processes process

The Processes service provides operations for managing processes in the guest operating system.

The operating system for the script demonstration is Centos 7.

Operations

  • List Guest Processes
  • Get Guest Processes
  • Create Guest Processes
  • Delete Guest Processes

(1)List Guest Processes

key method :vm.guest.Processes.list(vm, credentials)

Method Description : Lists the processes running in the guest operating system, and the most recently completed processes started by Processes.create.

Parameter description : vm: VM identifier; credentials: Guest operating system authentication data.

"credentials": {
    
    
		"interactive_session": false,  // 
		"password": "string", /
		"saml_token": "string", //
		"type": "USERNAME_PASSWORD", // 
    //
		"user_name": "string"
	}
  • interactive_session: If set, the action will interact with the desktop session logged in in the guest. This requires that the logged-in user matches that specified by the credentials. Currently only supported USERNAME_PASSWORD.
  • password: This field is optional and only USERNAME_PASSWORDmeaningful when the value of Credentials.type is present.
  • saml_token: SAML Bearer Token, the field is optional, it is only meaningful when the value of Credentials.type is SAML_BEARER_TOKEN.
  • type: The type of credential. Two authentication types are currently supported: USERNAME_PASSWORDand SAML_BEARER_TOKEN .
    • USERNAME_PASSWORD: Contains the necessary information to authenticate inside the guest operating system using username and password. This authentication method is stateless. To use USERNAME_PASSWORD, you need to fill in the user name and password for logging in to the operating system.
    • SAML_BEARER_TOKEN: Contains the necessary information to authenticate in the guest OS using a SAML token. SAML Bearer Token credentials rely on a guest alias that ties the guest account to the subject and certificate encoded in the SAML Bearer Token obtained from the VMware SSO server.
  • user_name: This field is optional, for SAML_BEARER_TOKEN, this is the guest user to associate with the certificate. For USERNAME_PASSWORD, this is the username to log into the operating system. If no SAML_BEARER_TOKENuser is specified, a guest-dependent mapping will determine what guest user account to apply.

Method return value :

  • command: complete process command
  • name: The name of the process.
  • owner: Process owner.
  • pid: ID of the process.
  • started: The time the process started.

Screenplay:

import time
from vSphere_Automation_SDK.Connect_to_vCenter_Server import vsphere_client
credentials = {
    
    
        "interactive_session": False,
        "password": "password",
        # "saml_token": "string",
        "type": "USERNAME_PASSWORD",
        "user_name": "root"
    }
vm = "vm-13247856"
start_time = time.time()
try:
    b = vsphere_client.vcenter.vm.guest.Processes.list(vm, credentials)
    for k,v in enumerate(b):
    	print(
              "Name:".ljust(17),v.name,
            "\nPID:".ljust(20),v.pid,
            "\nOwner:".ljust(18),v.owner,
            "\nCommand:".ljust(14),v.command,
            "\nStarted:".ljust(20),v.started,
            "\n--------------------------------------------"
        )

except Exception as err:
    for i in err.messages:
        id = i.id,
        default_message = i.default_message
        args = i.args
        params = i.params
        localized = i.localized
    print("\033[1;31m Encountered an error, Please see the following information \033[0m",
          "\n\tError Class:", id,
          "\n\tMessage:", default_message,
          "\n\tArgs:", args,
          "\n\tParams:", params,
          "\n\tLocalized:", localized,
          "\nError Data:", err.data,
          "\nError Type:", err.error_type
          )
end_time = time.time()
run_time = end_time - start_time
print("Used Time:".ljust(43), run_time)

Script rendering (part):

insert image description here

insert image description here

(2)Get Guest Processes

key method :vm.guest.Processes.get(vm, credentials,pid)

Method Description : Returns the status of processes running in the guest operating system, including processes started by Processes.create that may have recently completed.

Parameter description : vm: VM identifier; credentials: Guest operating system authentication data; pid: Process number

​ For credentialsspecific information, please refer to the List Guest Processes section

Method return value :

  • command: complete process command
  • name: The name of the process.
  • owner: Process owner.
  • Exit Code: If the process was started with Processes.create, you can get the exit code of the process if you query within 5 minutes of it completing.
  • started: The time the process started.
  • finished: If the process is started with Processes.create, then if you query within 5 minutes after it completes, you will be able to get the completion time of the process.

Screenplay:

import time
from vSphere_Automation_SDK.Connect_to_vCenter_Server import vsphere_client
credentials = {
    
    
        "interactive_session": False,
        "password": "password",
        # "saml_token": "string",
        "type": "USERNAME_PASSWORD",
        "user_name": "root"
    }
vm = "vm-13247856"
pid = 1
start_time = time.time()
try:
    b = vsphere_client.vcenter.vm.guest.Processes.get(vm, credentials,pid)
    print( "Name:".ljust(17),b.name,
            "\nOwner:".ljust(18),b.owner,
            "\nCommand:".ljust(14),b.command,
            "\nStarted:".ljust(19),b.started,
            "\nFinished:".ljust(18),b.finished ,
            "\nExit Code:".ljust(17),b.exit_code ,)

except Exception as err:
    for i in err.messages:
        id = i.id,
        default_message = i.default_message
        args = i.args
        params = i.params
        localized = i.localized
    print("\033[1;31m Encountered an error, Please see the following information \033[0m",
          "\n\tError Class:", id,
          "\n\tMessage:", default_message,
          "\n\tArgs:", args,
          "\n\tParams:", params,
          "\n\tLocalized:", localized,
          "\nError Data:", err.data,
          "\nError Type:", err.error_type
          )
end_time = time.time()
run_time = end_time - start_time
print("Used Time:".ljust(43), run_time)

Script renderings:

insert image description here

(3)Create Guest Processes

key method :vm.guest.Processes.create(vm, credentials,spec)

Method Description : Starts (creates) a process in the guest operating system. Processes started in this way can be queried for their status using Processes.list or Processes.get. When a process completes, its exit code and end time will be available within 5 minutes of completion.

Parameter description : vm: VM identifier; credentials: guest operating system authentication data; spec: parameters describing the program to be launched.

​ For credentialsspecific information, please refer to the List Guest Processes section

"spec": {
    
    
		"path": "string"
	}
  • path: The absolute path of the program to start. For the Linux operating system, /bin/bash is used to start the program.

    For Solaris guest operating systems, if /bin/bash exists, it is used to start the program, otherwise /bin/sh is used. If you use /bin/sh, then the process ID returned by Processes.create will be the ID of the shell used to start the program, not the program itself, because /bin/sh and /bin/bash work differently. This PID can still be used to watch the process with Processes.list to find its exit code and elapsed time.

    For Windows, no shell is used. Using a simple batch file instead of c:\windows\system32\cmd.exe /c will allow stdio redirection to work if passed in the Processes.CreateSpec.arguments parameter.

Method return value : process number.

Screenplay:

We first create a script named sleep.sh in the /root directory of Centos, the script content is:sleep 100000

import time
from vSphere_Automation_SDK.Connect_to_vCenter_Server import vsphere_client
credentials = {
    
    
        "interactive_session": False,
        "password": "password",
        # "saml_token": "string",
        "type": "USERNAME_PASSWORD",
        "user_name": "root"
    }
vm = "vm-13247856"
spec= {
    
    
		"path": "/root/sleep.sh"
	}
start_time = time.time()
try:
    b = vsphere_client.vcenter.vm.guest.Processes.create(vm, credentials,spec)
    print(b)

except Exception as err:
    for i in err.messages:
        id = i.id,
        default_message = i.default_message
        args = i.args
        params = i.params
        localized = i.localized
    print("\033[1;31m Encountered an error, Please see the following information \033[0m",
          "\n\tError Class:", id,
          "\n\tMessage:", default_message,
          "\n\tArgs:", args,
          "\n\tParams:", params,
          "\n\tLocalized:", localized,
          "\nError Data:", err.data,
          "\nError Type:", err.error_type
          )
end_time = time.time()
run_time = end_time - start_time
print("Used Time:".ljust(43), run_time)

Script renderings:

insert image description here

The get method gets the result:

insert image description here

(4)Delete Guest Processes

key method :vm.guest.Processes.delete(vm, credentials, pid)

Method Description : Terminates the process in the guest operating system. On Posix clients, the process receives a TERM signal. If this does not terminate the process, the KILL signal is sent. If a process is stuck, it may still be running.

Parameter description : vm: VM identifier; credentials: Guest operating system authentication data; pid: Process number

​ For credentialsspecific information, please refer to the List Guest Processes section

Method return value : N/A

Screenplay:

import time
from vSphere_Automation_SDK.Connect_to_vCenter_Server import vsphere_client
credentials = {
    
    
        "interactive_session": False,
        "password": "password",
        # "saml_token": "string",
        "type": "USERNAME_PASSWORD",
        "user_name": "root"
    }
vm = "vm-13247856"
pid = 2510
start_time = time.time()
try:
    b = vsphere_client.vcenter.vm.guest.Processes.delete(vm, credentials, pid)
    print("%s has been deleted"%pid)

except Exception as err:
    for i in err.messages:
        id = i.id,
        default_message = i.default_message
        args = i.args
        params = i.params
        localized = i.localized
    print("\033[1;31m Encountered an error, Please see the following information \033[0m",
          "\n\tError Class:", id,
          "\n\tMessage:", default_message,
          "\n\tArgs:", args,
          "\n\tParams:", params,
          "\n\tLocalized:", localized,
          "\nError Data:", err.data,
          "\nError Type:", err.error_type
          )
end_time = time.time()
run_time = end_time - start_time
print("Used Time:".ljust(43), run_time)

Script effect:

We delete the process created by the create method, and delete it and then use the get method to view it.

insert image description here

View the progress within 5 minutes:

insert image description here

View in 5 minutes:
insert image description here

References

vCenter REST APIs v7.0U3
vSphere-Python-Automation-Scripts/v1/

For other blog posts in this column, please pay attention to the column, there will be more content about vSphere Python automation: vSphere python automation

Guess you like

Origin blog.csdn.net/NOWSHUT/article/details/130093398