Open a VM Console with python

Jun 13, 2024
3
0
1
Hi all,
I have a small control center for Proxmox Server where I can start and stop VMs and view some information.
Now I want to launch a VM’s console directly. Unfortunately, I always get a 401: No Ticket error in an empty noVNC window.
The application is written in Delphi, but a Python example showing how to do this would be very helpful.

Thank you very much in advance.
 
I have tested below code to open a console on browser using python:
Python:
import requests
import urllib.parse
import webbrowser

PVE_HOST = "127.0.0.1:8006"
USER = "root@pam"
PASSWORD = "PASSWORD"
NODE = "NODENAME"
VMID = "102"

auth_url = f"https://{PVE_HOST}/api2/json/access/ticket"
auth_res = requests.post(auth_url, data={'username': USER, 'password': PASSWORD}, verify=False).json()

ticket = auth_res['data']['ticket']
csrf_token = auth_res['data']['CSRFPreventionToken']


vnc_url = f"https://{PVE_HOST}/api2/json/nodes/{NODE}/qemu/{VMID}/vncproxy"
headers = {'CSRFPreventionToken': csrf_token}
cookies = {'PVEAuthCookie': ticket}

vnc_res = requests.post(vnc_url, headers=headers, cookies=cookies, verify=False).json()
vnc_ticket = vnc_res['data']['ticket']

params = {
    'console': 'kvm',
    'novnc': 1,
    'vmid': VMID,
    'vmname': 'MyVM',
    'node': NODE,
    'vncticket': vnc_ticket
}

final_url = f"https://{PVE_HOST}/?{urllib.parse.urlencode(params)}"
webbrowser.open(final_url)
print(f"Open this URL: {final_url}")

See also:
https://pve.proxmox.com/wiki/Proxmox_VE_API