Giter Site home page Giter Site logo

mrkampf / proxmoxve Goto Github PK

View Code? Open in Web Editor NEW
48.0 3.0 25.0 396 KB

The is a PHP 8 ProxmoxVe API client. With it you can easily and quickly retrieve information from your Proxmox server or cluster.

License: GNU General Public License v3.0

PHP 100.00%
proxmoxve composer php php-library php7 proxmox-ve proxmox-apis proxmox proxmox-cluster api api-client php8 proxmox-api

proxmoxve's Introduction

ProxmoxVE API

This PHP 8+ Proxmox library allows, to interact with your Proxmox PVE server and cluster via API.

Latest Stable Version Total Downloads Latest Unstable Version License

You find any errors, typos or you detect that something is not working as expected please open an issue. I'll try to release a fix asap.

Getting Started

Recommended installation is using Composer. If you do not have Composer, what are you waiting for?

In the root of your project, execute the following:

$ composer require mrkampf/proxmox-ve

Or add this to your composer.json file:

{
    "require": {
        "mrkampf/proxmox-ve": "^0.4.4"
    }
}

Then perform the installation:

$ composer install --no-dev

Example


From version 3.1

<?php
// Require the autoloader
require_once 'vendor/autoload.php';

// Use the library namespace
use Proxmox\PVE;

// Then simply pass your credentials when creating the API client object.
$proxmox = new PVE("hostname", "username", "password", 8006, "pve", false);
// Note: Use "pam" instead of "pve" if you're using Standard Linux PAM authentication.

// Read all nodes
print_r($proxmox->nodes()->get());

// Read all LXC
print_r($proxmox->nodes()->lxc()->get());

// Read all LXC for a node
print_r($proxmox->nodes()->node("node_name")->lxc()->get());

// Read all qemu
print_r($proxmox->nodes()->qemu()->get());

// Read all QEMU for a node
print_r($proxmox->nodes()->node("node_name")->qemu()->get());

API Token Support

<?php
// Require the autoloader
require_once 'vendor/autoload.php';

// Use the library namespace
use Proxmox\API;

// Then simply pass your credentials when creating the API client object.
$proxmox = new API("hostname", "USER@REALM!TOKENID", "aaaaaaaaa-bbb-cccc-dddd-ef0123456789", 8006, false);

// Read all nodes
print_r($proxmox->nodes()->get());

// Read all LXC
print_r($proxmox->nodes()->lxc()->get());

// Read all LXC for a node
print_r($proxmox->nodes()->node("node_name")->lxc()->get());

// Read all qemu
print_r($proxmox->nodes()->qemu()->get());

// Read all QEMU for a node
print_r($proxmox->nodes()->node("node_name")->qemu()->get());

Example for lazy login

<?php
// Require the autoloader
require_once 'vendor/autoload.php';

// Use the library namespace
use Proxmox\PVE;

//Example for lazy login
$proxmox = new PVE("hostname", "username", "password", 8006, "pve", false, true);

//Login
$proxmox->getApi()->login();

// Read all nodes
print_r($proxmox->nodes()->get());

Example for custom http client

<?php
// Require the autoloader
require_once 'vendor/autoload.php';

// Use the library namespace
use Proxmox\PVE;

$customGuzzleHttpClient = new GuzzleHttp\Client();

//Example for lazy login
$proxmox = new PVE("hostname", "username", "password", 8006, "pve", false, false, $customGuzzleHttpClient);

// Read all nodes
print_r($proxmox->nodes()->get());

For version 3.1

WARNING: The array options is after version 3.0 no longer supported!
<?php
// Require the autoloader
require_once 'vendor/autoload.php';

// Use the library namespace
use Proxmox\PVE;

/**
 * Connect established (For version 3.0) 
 * 
 * authType and port defaults to 'pam' and '8006' but you can specify them like so
 * 
 * !!! WARNING !!!
 * This variant is after version 3.0 no longer supported
 * 
*/
$credentials = [
    'hostname' => '127.0.0.1',
    'username' => 'root',
    'password' => 'example',
    'authType' => 'pam',
    'port' => '8006',
];

// Then simply pass your credentials when creating the API client object.
$proxmox = new PVE($credentials);

//Read all nodes
print_r($proxmox->nodes()->get());

//Read all lxc
print_r($proxmox->nodes()->lxc()->get());

//Read all qemu
print_r($proxmox->nodes()->qemu()->get());

proxmoxve's People

Contributors

dependabot[bot] avatar ericwang401 avatar kingmotro avatar kluvi avatar mrkampf avatar okynos avatar sriccio avatar statio avatar talhaquddoos 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

Watchers

 avatar  avatar  avatar

proxmoxve's Issues

/api2/json/nodes/{node}/storage/{storage}/file-restore/download

Method get() in the Proxmox\Api\Nodes\Node\Storage\Storage\FileRestore\Download have to return not arrey, it have to return row data from response. Because /api2/json/nodes/{node}/storage/{storage}/file-restore/download return not json arrey as other method it return 'any'.

So in the Api class I propose to add one more method which will return ResponseInterface or iterator with headers

Snapshot Rollbacks & Deletion Not Working

Describe the bug
Trying to use the snapname class does not work (which results in rollback + deletion not working).

To Reproduce

  1. Create a Proxmox instance
  2. Attempt to use snapname

Desktop (please complete the following information):

  • OS: Windows

Additional context
Here's what we've tried:
$this->proxmox($server, $cluster)->qemu()->vmid($server->vmid)->snapshot()->snapname($snapname)->postRollback();
This appears to not work, as we get Class \"proxmox\\Api\\nodes\\qemu\\snapshot\\snapname\" not found.

When moving the postRollback function to the snapshot class itself (snapshot.php) and adding parameters for the name, it appears to work fine.

$this->proxmox($server, $cluster)->qemu()->vmid($server->vmid)->snapshot()->postRollback($snapname);

We added this function to snapshot.php:

public function postRollback($name){
        return connection::processHttpResponse(connection::postAPI($this->httpClient,$this->apiURL.$name.'/rollback/',$this->cookie));
    }

Here's the full code to the project that we're working on:
https://github.com/StratumPanel/Stratum-Panel
Code is in app/Services/Servers/SnapshotService.php

Supply parameters to GET requests

Hello,

First, thank you for the lib. Look very nice.

I would like to ask if there is a way to specify parameters for GET requests.

For example, the /cluster/resources GET method allows a type parameter to be passed to limit the results to one kind of object.
https://pve.proxmox.com/pve-docs/api-viewer/#/cluster/resources

The parameters are query parameters, I would imagine there is a way to add them to the Guzzzle get call if they are passed to get function ?.

Something like:

$proxmox->cluster->resources->get(['type' => 'vm']);

Does it sound reasonable or maybe there is a better way to handle this ?

Kind regards.

Add compatibility for all minor version of PHP 7.4

Is your feature request related to a problem? Please describe.
When trying to install the package with Composer the following Exception appears:
mrkampf/proxmox-ve requires php ^8.0|7.4|^8.1 which does not match your installed version 7.4.30.

Describe the solution you'd like
Change packagist requirements to match all patches of PHP 7.4, like it's already done with PHP 8.0 and 8.1

Describe alternatives you've considered
If the following changes are not possible, maybe add a disclaimer in the project README ?

DDoS Security Vulnerability

Describe the bug
When the ProxmoxVE package tries to reach an unresponsive Proxmox server, it never times out.

This could be a valid IP address, but the server on the other end could be down.

When this happens, PHP-FPM is stuck waiting for GuzzleHttp to timeout or return a response, which prevents the web server from answering any other traffic.

This is problematic because a single browser could try to ping an unresponsive Proxmox server and take down an entire web server because the request will never time out.

The root cause of this issue is that get, post, delete, put, and getCSRFToken in Proxmox/Helper/Api.php LACK a timeout option, so GuzzleHttp will wait INDEFINITELY for the Proxmox server to respond.

To Reproduce
Steps to reproduce the behavior:

  1. Supply a valid IP address that is unresponsive
  2. Send a request to fetch for server status on a QEMU instance

Expected behavior
The request should time out within somewhere between 10-20 seconds.

Screenshots
https://i.imgur.com/pnbAAbT.gif

I tried to show laravel.log, but there is not any logs because the requests haven't timed out yet.

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: Chrome
  • Version: Chrome 97, Windows 21h2

Server (please complete the following information):

  • OS: Ubuntu
  • Version: 20.04
  • Software: Nginx, PHP 8.1

Additional context
To fix this issue, add a header specifying a timeout.

A STRONGLY recommended way to fix this is allow the developer to configure GuzzleHttp options.

This will let any person who's using this package to set a custom timeout option and also add any other headers they might need.

Documentation

Is your feature request related to a problem? Please describe.
No documentation.

Describe the solution you'd like
Documentation on how to create VM, clone template, create backup, manage firewall, the basics.

Describe alternatives you've considered

Additional context

Documentation - how to get VMs

Is it possible to add an example of how to get all qemu VM's of 1 specific node?
I have been trying different approaches and none seems to work, except getting all nodes, that works out of the box ๐Ÿ‘

$pve->nodes()->node('nodeName')->qemu(); $response = $qemu->get();

Does not seem to work

/api2/json/nodes/{node}/storage

Nice work so far!

Is your feature request related to a problem? Please describe.
Is,
/api2/json/nodes/{node}/storage
not implemented?
If it is where can i find it?

Describe the solution you'd like
Implement it ;-)

Additional context
If not i would request that feature, since it is in the api, should be here as well or am i wrong?
Best regards eliasmagn

Lazy authentication

Is your feature request related to a problem? Please describe.
PVE class automatically authenticates right in the constructor, which is not necessary and may slow-down loading of application. It happens in situations, when we for some reason wanted to create instance of PVE, but does not make any calls to API.

Describe the solution you'd like
Remove $this->getApi()->login(); from PVE::__construct() and call it on first call of PVE::getCSRFPreventionToken(), PVE::getTicket() or PVE::getCookie()

how to use agent config ip address?

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

hi, tks this api is great project.
so how to use api agent config vm ip address?

Include extended guide about how to use basic functions

Hello @MrKampf,

First of all, I have to say that this repository is a piece of art! it works like a charm and it's super easy to use (Object notation).

I have a little request/improvement about the way to introduce new users to this repository. I'm currently managing a home lab with Proxmox and I built a simple web for my friends (a little background).

Being short, I started to use this plugin and I noticed that It's hard to understand at least for me.
For example, what does the $param array means? This call works but I don't understand why.
$proxmox->nodes()->node('mynode')->lxc()->vmid('XXX')->status()->postStart(array())

Finally, I want to say that I would like to open a pull request when I fully understand the code to help newcomers to introduce this plugin. Thanks for reading me.

Regards.

Can't update "sshkeys" because invalid format

Describe the bug
I can't update sshkeys because sshkeys requires ALL of the data sent in the request to be URL encoded.

The Proxmox documentation is incorrect because in the documentation here: https://pve.proxmox.com/pve-docs/api-viewer/index.html#/nodes/{node}/qemu/{vmid}/config

It says that sshkeys can be a string format in POST and PUT whereas when I tried making a POST and even tried PUT, I kept getting

Client error: `PUT https://redacted.app:8006/api2/json/nodes/proxmox/qemu/100/config/` resulted in a `400 Parameter verification failed.` response: {"errors":{"sshkeys":"invalid format - invalid urlencoded string: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC5fZzl0zlC47pFRj (truncated...)

To Reproduce

$proxmox = new PVE(...credentials);

$proxmox->nodes()->node(YOUR NODE)->qemu()->vmid(YOUR VMID)->config()->put(['sshkeys => 'ssh-rsa AAAAB3NzaC1yc2EAAAAD']) // key is redacted because it's too long

Expected behavior
I should get no error message. This library should be sending the body data as URL encoded.

The library should be sending the data not as JSON but like this (raw)

sshkeys=ssh-rsa%2520AAAAB3NzaC1yc2EAAAADAQABAAACAQC5fZzl0zlC47pFRjAs0TUlz8zfDWS9eoihns9wY4F81Gar6UT67QppUa1%252B6w28EGkss4yXyc

This should be exactly the data format sent over as url encoded

Screenshots
This part is causing the request to fail because it's sending as JSON whereas Proxmox wants it as URL encoded (I don't know why. I think it's pointless)
image

Desktop (please complete the following information):

  • OS: Windows 11
  • Browser Chrome
  • Version 103

Server (please complete the following information):

  • OS: Ubuntu
  • Version 20.04
  • Software Docker, PHP 8.1, Nginx, Mysql

Additional context
SSH keys updating code is here: https://github.com/ericwang401/convoy/blob/master/app/Services/Servers/CloudinitService.php#L27

Storage content error

I'm having this request json_encode($pveconn->nodes()->node($nodename)->storage()->storageId("local")->content()->get(["content"=>"vztmpl"])); and it's resulting into Uncaught Error: Call to undefined method Proxmox\\Api\\Nodes\\Node\\Storage::storageId().
I'm pretty sure I've got the request right, I've also tried every single other combination that may work but no luck.

help: How i can get all vms names

Hello i want to know how to get only the names of lxc or quemus

$data = $proxmox->nodes()->node('Debian-104-buster-64-minimal')->lxc()->get();

for example

setCSRFPreventionToken(): Argument #1 ($CSRFPreventionToken) must be of type string, null given

Describe the bug
This bug happens when the login() function at Proxmox/Helper/Api.php(168) cannot login to the host.

To Reproduce
Simulate a failed login so that getCSRFToken() returns similar response:

cURL error 7: Failed to connect to ...... port 8006: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://......:8006/api2/json/access/ticket

Expected behavior
login() function should return a result and inside it $requestResult should be checked in case of any errors, at the moment the exception in getCSRFToken() is handled and thus returning null for no reason. Later setCSRFPreventionToken() is called with null value and thus throwing an unhandled exception.

Screenshots
Sorry, I cannot provide this.

Desktop (please complete the following information):
N/A

Server (please complete the following information):
N/A

Additional context
N/A

Login will always fail?

proxmoxVE/src/proxmox/pve.php line 59, i struggle to understand this logic, its also what breaks the code.

if(is_array($json)){ //Is $json are array throw new AuthenticationException('Can\'t login with this data.'); } if(array_key_exists('data',$json)){//Is key 'data' in array throw new AuthenticationException('Can\'t login with this data.'); } $this->CSRFPreventionToken = $json['data']['CSRFPreventionToken']; //Save the CSRF token in class variable

Basically it says, if array throw error, if not, use array: $json['data']['CSRFPreventionToken']
So it will never get there?

"Can't login" error on multiple connections to same or different servers

Describe the bug
Once the pve is set once, it returns a "can't login" on every new connection.
It seems to keep a session somehow but i dont seem to be able to find an option to unset this.
Unsetting the connection var also does not seem to work.

To Reproduce

$credentials = [
            'hostname' => $proxmoxConfig->getDomain(),
            'username' => $proxmoxConfig->getUser(),
            'password' => $proxmoxConfig->getPassword(true),
            'authType' => 'pam',
            'port' => $proxmoxConfig->getPort(),
        ];

$api = new pve($credentials);
//some other code
// api works fine
// Even an unset ($api) does not work

$credentials = [
            'hostname' => $proxmoxConfig->getDomain(),
            'username' => $proxmoxConfig->getUser(),
            'password' => $proxmoxConfig->getPassword(true),
            'authType' => 'pam',
            'port' => $proxmoxConfig->getPort(),
        ];
$api = new pve($credentials);
// cant login

it happens to me with a different node that i try to connect to, or when i try to connect to the same node twice, on different levels in my code.

Expected behavior
A new fresh connection, anything else than a "Can't login" message

Even a disconnect function would work.

Call to undefined method Proxmox\Api\Nodes::qemu()

Describe the bug
The read me needs to be updated: https://github.com/MrKampf/proxmoxVE#readme and explicitly state that you require full permissions for this api call.

To Reproduce
N/A

Expected behavior
A clear and concise description of basic usage of the module.

Screenshots
N/A

Desktop (please complete the following information):
N/A

Server (please complete the following information):
N/A

Additional context
N/A

DELETE qemu not working

If i use $proxmox->nodes()->node('ix-ds-01')->qemu()->vmId($server_id)->delete(); it wont work error:

  • Closing connection 1
    --
    ย  | Server error: DELETE https://****:8006/api2/json/nodes/ix-ds-01/qemu/215/ resulted in a 501 Unexpected content for method 'DELETE' response

Rrddata

https://pve.proxmox.com/pve-docs/api-viewer/#/nodes/{node}/rrddata

    class Rrddata extends PVEPathClassBase
    
    ...

    public function get(): ?array
    {
        return $this->getPve()->getApi()->get($this->getPathAdditional());
    }

Rrddata requires timeframe.

Timeframe is a required parameter for rrddata hour | day | week | month | year enum

Without timeframe null will always be returned here.

I tried to open a PR, but cannot commit to a branch, here's my changes in Proxmox/Api/Nodes/Node/Rrddata.php

    /**
     * Read node RRD statistics
     * @link https://pve.proxmox.com/pve-docs/api-viewer/#/nodes/{node}/rrddata
     * @param array $params An array specifying the time intervals for which statistics should be retrieved.
     * Supported keys:
     * ['timeframe' =>
     * - 'hour': Retrieve statistics for the last hour.
     * - 'day': Retrieve statistics for the last day.
     * - 'week': Retrieve statistics for the last week.
     * - 'month': Retrieve statistics for the last month.
     * - 'year': Retrieve statistics for the last year.
     * ]
     * @return array|null
     */
    public function get(array $params = []): ?array
    {
        return $this->getPve()->getApi()->get($this->getPathAdditional(), $params);
    }

How to use NoVNC?

Is there any way to implement NoVNC console (with Extra Wimdow cookie session, or as iframe, websocket) ?

Kind Regards

POST returns "HTTP/1.1 401 Permission denied - invalid csrf token"

Describe the bug
I dont seem to be able to POST anything, i can get results trough GET.
The error i keep receiving is: "HTTP/1.1 401 Permission denied - invalid csrf token"

I have been trying to search for a solution but i havent found one yet, nor an option that passes the "csrftoken" in the header as mentioned in many solutions: https://forum.proxmox.com/threads/connection-problem-novnc-api.40751/

To Reproduce
$proxmox = new pve($credentials);

$response = $proxmox->nodes()->node($node)->qemu()->vmid($id)->status()->postStart(['node' => $node, 'vmid' => $id]);

Expected behavior
A VM that has been started

Need to update documentation for V4.0+

Version 3

$proxmox = new PVE("hostname", "username", "password", "pve", 8006, false);

Version 4
$proxmox = new PVE("hostname", "username", "password", 8006, "pam", false);

Use with Laravel

Can this be easily added to laravel? I don't see a Facade or ServiceProvider.

Thanks

Create new release for latest pull request #15

Is your feature request related to a problem? Please describe.
It is related to fix described in #15

Describe the solution you'd like
Is it possible if you can create a new release for this pull request?

Describe alternatives you've considered
N/A

Additional context
N/A

start()->post() is required to start a VM

Describe the bug
Calling the start or shutdown methods has no effect on the VM.
No POST request is executed to https://pve.proxmox.com/pve-docs/api-viewer/#/nodes/{node}/qemu/{vmid}/status/start.

To Reproduce

		$proxmox = new PVE($serverUrl, $rootUser, $rootPwd, $port,'pam',true);
		$proxmox->nodes()->node($parNodeName)->qemu()->vmId($vmId)->status()->start();

Expected behavior
A request is sent to https://pve.proxmox.com/pve-docs/api-viewer/#/nodes/{node}/qemu/{vmid}/status/start
The VM starts.

Screenshots

*   Trying xx.xxx.xxx.xx:8006...
* Connected to serverURL (xx.xxx.xxx.xx) port 8006 (#0)
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*  CAfile: C:\xampp8.012\apache\bin\curl-ca-bundle.crt
*  CApath: none
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: OU=PVE Cluster Node; O=Proxmox Virtual Environment; CN=PAR-XXXXX.xxxxx.xx
*  start date: Nov 19 14:50:42 2020 GMT
*  expire date: Nov 19 14:50:42 2022 GMT
*  issuer: CN=Proxmox Virtual Environment; OU=3038d24c-7779-41d5-9e4d-6ca31f302472; O=PVE Cluster Manager CA
*  SSL certificate verify result: unable to get local issuer certificate (20), continuing anyway.
> POST /api2/json/access/ticket HTTP/1.1
Host: serverURL:8006
User-Agent: GuzzleHttp/7
Content-Type: application/x-www-form-urlencoded
Accept: application/json
Accept-Encoding: gzip
Content-Length: 41

* old SSL session ID is stale, removing
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Cache-Control: max-age=0
< Connection: close
< Connection: Keep-Alive
< Date: Thu, 13 Jan 2022 11:20:12 GMT
< Pragma: no-cache
< Server: pve-api-daemon/3.0
< Content-Encoding: gzip
< Content-Length: 697
< Content-Type: application/json;charset=UTF-8
< Expires: Thu, 13 Jan 2022 11:20:12 GMT
<
* Closing connection 0

Desktop :

  • OS: Windows 10
  • PHP 8.0.12
  • PHP lib mrkampf/proxmox-ve: v 0.4.1

Server (Proxmox server):

  • OS: Debian 10 (buster)
  • proxmox-ve: 6.3-1 (running kernel: 5.4.78-2-pve)
  • Software: Apache2

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.