Giter VIP home page Giter VIP logo

pve2-api-php-client's Introduction

This class provides the building blocks for someone wanting to use PHP to talk to Proxmox's API. Relatively simple piece of code, just provides a get/put/post/delete abstraction layer as methods on top of Proxmox's REST API, while also handling the Login Ticket headers required for authentication.

See http://pve.proxmox.com/wiki/Proxmox_VE_API for information about how this API works. API spec available at https://pve.proxmox.com/pve-docs/api-viewer/index.html

Requirements:

PHP 5/7/8 with cURL (including SSL/TLS) support.

Usage:

Example - Return status array for each Proxmox Host in this cluster.

require_once("./pve2-api-php-client/pve2_api.class.php");

# You can try/catch exception handle the constructor here if you want.
$pve2 = new PVE2_API("hostname", "username", "realm", "password");
# realm above can be pve, pam or any other realm available.

if ($pve2->login()) {
    foreach ($pve2->get_node_list() as $node_name) {
        print_r($pve2->get("/nodes/".$node_name."/status"));
    }
} else {
    print("Login to Proxmox Host failed.\n");
    exit;
}

Example - Create a new Linux Container (LXC) on the first host in the cluster.

require_once("./pve2-api-php-client/pve2_api.class.php");

# You can try/catch exception handle the constructor here if you want.
$pve2 = new PVE2_API("hostname", "username", "realm", "password");
# realm above can be pve, pam or any other realm available.

if ($pve2->login()) {

    # Get first node name.
    $nodes = $pve2->get_node_list();
    $first_node = $nodes[0];
    unset($nodes);

    # Create a Linux Container (LXC) on the first node in the cluster.
    $new_container_settings = array();
    $new_container_settings['ostemplate'] = "local:vztmpl/debian-6.0-standard_6.0-4_amd64.tar.gz";
    $new_container_settings['vmid'] = "1234";
    $new_container_settings['cpus'] = "2";
    $new_container_settings['description'] = "Test VM using Proxmox 2.0 API";
    $new_container_settings['disk'] = "8";
    $new_container_settings['hostname'] = "testapi.domain.tld";
    $new_container_settings['memory'] = "1024";
    $new_container_settings['nameserver'] = "4.2.2.1";

    // print_r($new_container_settings);
    print("---------------------------\n");

    print_r($pve2->post("/nodes/".$first_node."/lxc", $new_container_settings));
    print("\n\n");
} else {
    print("Login to Proxmox Host failed.\n");
    exit;
}

Example - Modify DNS settings on an existing container on the first host.

require_once("./pve2-api-php-client/pve2_api.class.php");

# You can try/catch exception handle the constructor here if you want.
$pve2 = new PVE2_API("hostname", "username", "realm", "password");
# realm above can be pve, pam or any other realm available.

if ($pve2->login()) {

    # Get first node name.
    $nodes = $pve2->get_node_list();
    $first_node = $nodes[0];
    unset($nodes);

    # Update container settings.
    $container_settings = array();
    $container_settings['nameserver'] = "4.2.2.2";

    # NOTE - replace XXXX with container ID.
    var_dump($pve2->put("/nodes/".$first_node."/lxc/XXXX/config", $container_settings));
} else {
    print("Login to Proxmox Host failed.\n");
    exit;
}

Example - Delete an existing container.

require_once("./pve2-api-php-client/pve2_api.class.php");

# You can try/catch exception handle the constructor here if you want.
$pve2 = new PVE2_API("hostname", "username", "realm", "password");
# realm above can be pve, pam or any other realm available.

if ($pve2->login()) {
    # NOTE - replace XXXX with node short name, and YYYY with container ID.
    var_dump($pve2->delete("/nodes/XXXX/lxc/YYYY"));
} else {
    print("Login to Proxmox Host failed.\n");
    exit;
}

Licensed under the MIT License. See LICENSE file.

pve2-api-php-client's People

Contributors

cpuid avatar danhunsaker avatar lsthompson avatar lucapiccio avatar spamhome avatar thomaslamprecht avatar ypilpre 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pve2-api-php-client's Issues

API parameter update

the disk size parameter no longer exist in the official API of proxmox 4.1 for creating container.
It changed to something like this
diskname:vmid/vm-vmid-disk-1.raw,size=8G

Any updates?

Hey, thanks for the great project! We're planning to use the library on our project (FOSSBilling, a fork of BoxBilling made by the latest team) but noticed the library hasn't received any updates recently.

Is there any chance of it receiving updates in the future, or are we completely out of luck?

We also are planning to contribute upstream from time to time. But if you aren't planning to maintain the project it will not be of much use.

We will be looking forward for your reply. For quicker communication, here is our Discord server. Have a nice day.

Getting API last error

Hello,
I want to get the last error when using the API call.
Are there a way to do this?

make port as variable .

i think is usefful if you add the proxmox port as a variable , so we can controle it out side the class , as the actual scenario we need to change the port in the class php file .

if you want to i can send you a pull request of the change .

Update root password in LXC container

I can set a root password when creating a container using the API, but, i can't find a method to update this password.
Otherwise, i will use ssh commands

$pve2->get request

Hi, I have a problem with get request.
I try to create a vnc iframe and when I send the request I get this result : bool(false).

`$pve2->login();

    if ($pve2->login()) {
        
        $config = $pve2->post("/nodes/test/lxc/100/vncproxy", array()); 
        
        $websocket = $pve2->get("/nodes/test/lxc/100/vncwebsocket",
        [
            'port' => $config['data']['port'],
            'vncticket' => $config['data']['ticket']
        ]);

    } else {
        
        print("Login to Proxmox Host failed.\n");
        exit;
        
    }`

Can you help me ?
Thank you

Best regards,
Proxene

Support for /png/

It would be a good idea to add the support of rrd graph (with /png/ instead of /Json/)

"Common Tasks" mentioned in TODO

This isn't an issue, per se, so much as an inquiry. What tasks would be considered common/useful enough to provide such wrappers for? I'd be happy to implement this child class, but I need to know what I'd be writing to do it. Listed in the TODO already are:

  • Create VM
  • Create container
  • Change container settings

I can assume that I should also add (as it's implied)

  • Change VM settings

But what else should be supported?

[Security] cURL SSL/TLS Verification -> option; Verbose Logging -> option/disabled

I found several security flaws in the action function.

SSL/TLS Verification Disabled

https://github.com/CpuID/pve2-api-php-client/blob/b9ef9cb4f040cf71bfa5281b1e31bfae7a984474/pve2_api.class.php#L219C20-L219C20

curl_setopt($prox_ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($prox_ch, CURLOPT_SSL_VERIFYHOST, false);

This makes the requests vulnerable to Man-in-the-Middle (MITM) attacks, where an attacker can intercept and potentially alter the communication between the client and the server.

Potential Information Disclosure & Lack of Data Sanitization

Also described in #45
The function logs extensive details about the responses it receives, including headers and potentially sensitive data. If the logs are improperly secured or misconfigured, it could lead to information disclosure. Below is the code segment responsible for this:

error_log("----------------------------------------------\n" .

error_log("----------------------------------------------\n" .
  "FULL RESPONSE:\n\n{$action_response}\n\nEND FULL RESPONSE\n\n" .
  "Headers:\n\n{$header_response}\n\nEnd Headers\n\n" .
  "Data:\n\n{$body_response}\n\nEnd Data\n\n" .
  "RESPONSE ARRAY:\n\n{$action_response_export}\n\nEND RESPONSE ARRAY\n" .
  "----------------------------------------------");

The data received from the API response in the action function is directly logged and used without any visible sanitization or validation, making it potentially susceptible to security vulnerabilities, especially if this data is used elsewhere in the application.

Potential Inconsistent Return Types

For “PUT” HTTP method, it returns a Boolean true if the HTTP response is 200, but for other HTTP methods, it returns the ‘data’ part of the response. This inconsistency might lead to bugs or unexpected behavior in the parts of the application that use this function, indirectly causing security flaws.

In addition to the observed flaws, manually parsing HTTP responses, as seen in this function, is not a best practice, as it is error-prone and can lead to security vulnerabilities; it is generally safer and more efficient to use well-established libraries or built-in functions for processing HTTP responses, which are designed to handle various edge cases and anomalies in a secure manner.

Login to Proxmox Host failed.

I'm 100% sure all the details are correct but i keep getting Login to Proxmox Host failed.

Version: 3.4-3/2fc72fee

It only works when i enter the full ip of the host, But when i enter the hostname it doesnt work

issue while creating vm

I am trying to use your api...But i'm facing a problem here...when i try to create a vm in proxmox, the vm could not be created....when i check the logs it showed me

error 500 no options specified....

Can you please help me out...:)

port is not accepted

when i call the class i get

Uncaught exception 'PVE2_Exception' with message 'Port must be an integer between 1 and 65535.'

my code is

include("pve2_api.class.php");
$pve2 = new PVE2_API($hostname, $user , $realm , $pasword , $port);

when i remove port it work perfectly . because the class has the port 8006 if empty .

the case here is because the port is saved in database as a string , what we should do is convert it in intiger

(int)$port .

so i think is better to update the README file to include the HOWTO , or remove

no support for optional settings in GET request

some GET request support additional setting , but in the class no support for this .

GET exemple with additional setting

pvesh get /cluster/resources -type vm
pvesh get /nodes/localhost/storage/local/content -content vztmpl
pvesh get /nodes/localhost/bootlog -limit 3 -start 5
pvesh get /nodes/localhost/rrd -cf average

update documentation

please update the documentation ofthe readme file , because it has wrong way of using the class , if ($pve2->constructor_success()) is no longer used . also the port should be menstioned to be intiger . and add exemple with get params .

thanks for all your effort

Get UPID as a response (where request launched worker/runner)

Hello,
I need to update php client to always get a UPID for a valid request. It's valid for POST requests only. PUT returns boolean 1 if it's valid.
Is it possible to do this.
FYI: i updated the code to return the http error when something is wrong for debugging purpose

Collaborator

Hey @danhunsaker,

Not sure if you noticed, I've added you as a collaborator :) Nice work so far, thanks again.

Regards, Nathan (CpuID).

Setting disk capacity on CT creation

I'm using the api for creating LXC container.
When i set rootfs to choose the storage disk and it's size like this
$new_container_settings['rootfs']=local:112/vm-112-disk-1.raw,size=40
I get a container created but the root disk appear to be empty in proxmox admin console
Note that when i create a container with the admin interface i get the same parameter just like as i wrote in the API.
Are there a missing parameter or a configuration to do?
$new_container_settings['disk'] no longer works on PVE 4.1

add a node to cluster

after login I use this url /api2/json/cluster/config/nodes/{node} to POST a node
and it return:

POST /cluster/config/nodes/' not implemented

my version is up to date and is 5.2

Suddenly login always fails whereas nothing changed in the code : Howto solve

Well, this is not a bug report but more about unexpected behavior.

Proxmox by default has SSL certificates which are binded to the ip address. If you install proper domain certificate name aka : myballs.mydomain.com to let VPS users login and access console in a green fashion, login with the IP address stops to work.

In the code you have to replace $hostname by the FQDN. Then login works again.

A solid code to keep login in case of change would be :

function promox_get_pve2_connection($fqdn,$ip,$password) {
  $pve2 = new PVE2_API($fqdn, "root", "pam", $password);
  if ($pve2->login()) {
    return $pve2;
  }
  else { // We try with IP address
    $pve2 = new PVE2_API($ip, "root", "pam", $password);
    if ($pve2->login()) {
      return $pve2;
    }
    else { // We are really dead
      print("Login to Proxmox Host failed.\n");
    }
  }
}

PHP Fatal error: Call to undefined method PVE2_API::constructor_success()

Have this error..
[code]

constructor_success()) { /\* Optional - enable debugging. It print()'s any results currently */ $pve2->set_debug(true); ``` if ($pve2->login()) { foreach ($pve2->get_node_list() as $node_name) { print_r($pve2->get("/nodes/".$pve_node."/status")); } } else { print("Login to Proxmox Host failed.\n"); exit; } } else { print("Could not create PVE2_API object.\n"); exit; } ``` ... ?>

[/code]

php -v
PHP 5.4.43 (cli) (built: Jul 11 2015 00:05:29)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies
OS: CentOS 6.5 i386

VM Shutdown and start - POST Proccess

Hello,

I can't run my code, can you tell where you made a mistake?

public function post_vm_acKapat($nodeIsmi, $vmID,$paracik)
		{
			
			$gosteramcana = $this->post("/nodes/$nodeIsmi/qemu/$vmID/status/start", $paracik);
			if ($gosteramcana == null) {
				return false;
			} else {
				echo "VM is starting.";
			}
		}
if ($pve2->login()) {
		$paraciks = array(
			"node" => "prox",
			"vmid" => "104"
		);
		$pve2->post_vm_acKapat('prox', 104, $paraciks);
	} else {
		print("Login to Proxmox Host failed.\n");
		exit;
	}

I spent 3 hours but..
Also, thank you for this project.

Clone KVM Template

Hi There!

I'm trying to clone a KVM template (template id: 100) This is the code i made but the only output im getting is "boolean false"

image

image

Printing "FULL REPONSE" every time

Hi, I think you forgot to delete / comment line 233-238 because at every (get, put, post delete) action the script returns an full response from curl.

image

Error in class

There is missing a key to close a method, and this make that the class doesn't work.

Create VM via API complains that {vmid}.conf file is not existing

The error message is :
PHP message: This API Request Failed. HTTP Response - 500 HTTP Error - HTTP/1.1 500 Configuration file 'nodes/teleonomy-1/qemu-server/103.conf' does not exist" while reading response header from upstream, client: 192.168.1.8, server: dev.teleonomy.net, request: "POST /devel/php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.0-fpm.sock:", host: "dev.teleonomy.net", referrer: "http://dev.teleonomy.net/devel/php"

By command line, it works :
pvesh create /nodes/teleonomy-1/qemu -memory 8192 -sockets 2 -cores 2 -net0 virtio,bridge=vmbr0 -net1 virtio,bridge=vmbr1 -vmid 103 -ostype l26 -virtio0 media=disk,volume=local:103/vm-103-disk-1.qcow2

That gets 200Ok.
But via API, no.
The settings array can be be seen at : https://www.teleonomy.net/sites/default/files/settings.png

The POSTing URL via API is : /nodes/teleonomy-1/qemu/103/config

I have spent 8 hours on this, and cannot find WTF is wrong ...

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.