Giter Site home page Giter Site logo

proxmox-api's Introduction

Proxmox Api

NPM Version Typescript Api to manage proxmox servers.

Mapping 100% of available calls, contains all api documentation in typing file. code size < 10Ko including docs

Usage

intellisense

Overview

to use this API take the Path you want to call, and replace:

  • the / by .
  • the ${variable} by .(variable)
  • append the http method you want to call with a $ at the end (.$get(), .$post(), .$put() or .$delete())

that it.

Example

To call GET /cluster/acme/account/{name} you will call promox.cluster.acme.account.$(name).$get()

To call GET /api2/json/cluster/backup/{id}/included_volumes you will call promox.cluster.backup.{id}.included_volumes.$get()

To call GET /api2/json/nodes you will call promox.nodes.$get()

The provided typing will assist you within intelisense, so you do not need to read any external doc.

Code sample

  • NPM Version an hotplug usb service based on this API.
npm install proxmox-api
import proxmoxApi from "proxmox-api";

// authorize self signed cert if you do not use a valid SSL certificat
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

async function test() {
    // connect to proxmox
    const promox = proxmoxApi({host: '127.0.0.1', password: 'password', username: 'user1@pam'});
    // list nodes
    const nodes = await promox.nodes.$get();
    // iterate cluster nodes
    for (const node of nodes) {
        const theNode = promox.nodes.$(node.node);
        // list Qemu VMS
        const qemus = await theNode.qemu.$get({full:true});
        // iterate Qemu VMS
        for (const qemu of qemus) {
            // do some suff.
            const config = await theNode.qemu.$(qemu.vmid).config.$get();
            console.log(`vm: ${config.name}, memory: ${config.memory}`);
            // const vnc = await theNode.qemu.$(qemu.vmid).vncproxy.$post();
            // console.log('vnc:', vnc);
            // const spice = await theNode.qemu.$(qemu.vmid).spiceproxy.$post();
            // console.log('spice:', spice);
        }
    }    
}

test().catch(console.error);

Initialisation alternatives:

  • keeping access to ProxmoxEngine object (that can be use to share a ticket, or to access it)
import proxmoxApi, { ProxmoxEngine } from "proxmox-api";

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

async function test() {
    // connect to proxmox
    const engine = new ProxmoxEngine({host: '127.0.0.1', password: 'password', username: 'user1@pam'});
    const promox = proxmoxApi(engine);
}
  • Using Api token
import proxmoxApi from "proxmox-api";

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

async function test() {
    // connect to proxmox
    const promox = proxmoxApi({host: '127.0.0.1', tokenID: 'USER@REALM!TOKENID', tokenSecret: '12345678-1234-1234-1234-1234567890ab'});
}

Notes

  • if the call path contains a hyphen, you will need to use the ['field'] syntax ex:
await theNode.qemu.$(vmid).agent['get-fsinfo'].$get()

Changelog

V0.1.3

  • add authTimeout option, to limit authentification time.
  • add queryTimeout option to limit non auth request timeout.

proxmox-api's People

Contributors

bnjunge avatar davidthewatson avatar urielch 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

Watchers

 avatar  avatar  avatar

proxmox-api's Issues

support for version 7

I'm using PVE, version 7, they which includes a new API endpoint that deals with downloading ISOs, download_url documented here

I think this package could use an update to include new mapping.

Following the convention, the API should work like so:

const nodes = await pve.nodes.$get();
    // iterate cluster nodes
    for (const node of nodes) {
      const theNode = pve.nodes.$(node.node);
      theNode.storage.$('local').download_url.$post({
        url: 'https://download.iso'
      })
    }

Problem with load an ES module in the package.json

Hi @UrielCh and @bnjunge, Currently I am developing my project using the proxmox-api package. I think this project contributed to my project. However, I have a warning here.

[1] (node:8232) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
[1] (Use `node --trace-warnings ...` to show where the warning was created)
[1] C:\Users\user\project\node_modules\proxmox-api\dist\esm\index.js:16
[1] export { proxmoxApi as default } from './constructor.js';
[1] ^^^^^^
[1] 
[1] SyntaxError: Unexpected token 'export'
[1]     at internalCompileFunction (node:internal/vm:73:18)
[1]     at wrapSafe (node:internal/modules/cjs/loader:1178:20)
[1]     at Module._compile (node:internal/modules/cjs/loader:1220:27)
[1]     at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
[1]     at Module.load (node:internal/modules/cjs/loader:1119:32)
[1]     at Module._load (node:internal/modules/cjs/loader:960:12)
[1]     at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:169:29)
[1]     at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
[1]
[1] Node.js v18.16.1
[1] [nodemon] app crashed - waiting for file changes before starting...

It is not complicated to solve. I added this in the package.json file and then solved it. I wonder if can I merge this into your project. Or is there any alternative way around it? Thanks

{
  "name": "proxmox-api",
  "type": "module",
  "version": "1.0.2",
  ...
}

0.3.0 Breaks support for API Keys and Secrets

Upgrading from 0.2.0 to 0.3.0 causes every request to throw Error: login failed with 401: authentication failure when authenticating using tokenId and tokenSecret.

Downgrading back to 0.2.0 works.

[cause]: Error: Auth https://{REDACTED}:8006/api2/json/access/ticket Failed! with Exception: Error: login failed with 401: authentication failure

Agent "exec-status" Error 400 Parameter verification failed.

I got this error with exec-status

GET https://192.168.1.2:8006/api2/json/nodes/pve/qemu/102/agent/exec-status?pid=2688

return Error 400 Parameter verification failed.:

{\"errors\":{\"pid\":\"property is missing and it is not optional\"},\"data\":null}"

Replication problems

create agent exec and retrive pid
and call agent exec-status should replicate an error
but try to access that URL with browser will result like it's seem to be

net[n] is typed only with net0, net1, net2, net3.

I am writing a script to assign network interfaces, however I noticed that the api documentation uses net[n] as the parameter. I confirmed that the api does take something like 'net4' when adding a 5th interface.

This does not seem possible with the current typing. Perhaps this could be covered with something like a template?

type netType = `net${number}`
type configObject = {
    [netName: netType]: string
}
const config: configObject = {
    'net2': 'test'
}

$post and $put request send data as querystrings

Mutation requests $post, $put send query strings for data instead of using the body.

Something went wrong Error: post https://{REDACTED}:8006/api2/json/nodes/ceres/qemu/901/clone?full=1&name=26d534a50eb5&newid=105 return Error 400 Parameter verification failed.: {"data":null,"errors":{"newid":"property is missing and it is not optional"}}
    at ProxmoxEngine.doRequest (/app/node_modules/proxmox-api/dist/ProxmoxEngine.js:159:23)
const newid = await ctx.proxmox.cluster.nextid.$get();
const vm = await ctx.proxmox.nodes
  .$(node!)
  .qemu.$(template.vmid)
  .clone.$post({
    full: true,
    name: `${randomBytes(6).toString('hex')}`,
    newid,
  });

ReferenceError: AbortController is not defined

Good afternoon,

I am trying to use this library to connect to our Proxmox server, but I get this error here:

Error: FaILED to call GET http://my-node:8006/api2/json/version
    at ProxmoxEngine.doRequest (file:///home/bogi158/Desktop/Workspace/test/ansible/node_modules/proxmox-api/dist/esm/ProxmoxEngine.js:163:27) {
  cause: ReferenceError: AbortController is not defined
      at ProxmoxEngine.doRequest (file:///home/bogi158/Desktop/Workspace/test/ansible/node_modules/proxmox-api/dist/esm/ProxmoxEngine.js:118:32)
router.get("/test", async function (req, res, next) {
  try {
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    const client = Proxmox({
      schema: "http",
      host: process.env.PROXMOX_HOST,
      port: 8006,
      debug: true,
      tokenID: process.env.PROXMOX_USER + "!" + process.env.API_TOKEN_ID,
      tokenSecret: process.env.API_TOKEN_SECRET,
    });
    const version = await client.version.$get();
    res.send(version);
  } catch (e) {
    console.error(e);
    res.status(500).send(e);
  }
});

The error appears during the getVersion call, so the login seems like it is working, but the actual API calls do not.
I think the problem is that I am connecting to a https endpoint but the certificates are self-signed and it is giving an error. The login works in curl if I skip ssl verification.
Unfortunately the dev environment have only self-signed certificates so I need to be able to skip the ssl verification. Is it possible? I am using process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; but seems like it is not working.

Hyphen in URL

Hey there!

I've ran into a problem with the Qemu Agent. When i try to call /nodes/{node}/qemu/{vmid}/agent/get-fsinfo Typescript will interpret the hyphen as a subtract and throw an error. Do you have an idea how i can fix this or some kind of workaround?

Greetings from germany!

image
image

Fix all issue

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/proxmox-api/dist/esm/model.d.ts b/node_modules/proxmox-api/dist/esm/model.d.ts
index cb5cfa9..bf339f4 100644
--- a/node_modules/proxmox-api/dist/esm/model.d.ts
+++ b/node_modules/proxmox-api/dist/esm/model.d.ts
@@ -2735,7 +2735,7 @@ export declare namespace Proxmox {
         /**
          * Used memory in bytes (when type in node,qemu,lxc).
          */
-        mem?: string;
+        mem?: number;
         /**
          * Name of the resource.
          */
diff --git a/node_modules/proxmox-api/package.json b/node_modules/proxmox-api/package.json
index f2ac123..aa8b2c5 100644
--- a/node_modules/proxmox-api/package.json
+++ b/node_modules/proxmox-api/package.json
@@ -50,5 +50,6 @@
     "url": "https://github.com/UrielCh/proxmox-api/issues"
   },
   "homepage": "https://urielch.github.io/proxmox-api/",
-  "files": ["dist", "src"]
+  "files": ["dist", "src"],
+  "type": "module"
 }
\ No newline at end of file

This issue body was partially generated by patch-package.

Support for No Port

Is it possible to disable/remove the port? My Proxmox proxy doesn't have the port, just a URL.

API key auth

Thanks for providing this API!

Is it possible to authenticate with API keys instead of username/password ?

custom-patch

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/proxmox-api/dist/esm/model.d.ts b/node_modules/proxmox-api/dist/esm/model.d.ts
index cb5cfa9..bf339f4 100644
--- a/node_modules/proxmox-api/dist/esm/model.d.ts
+++ b/node_modules/proxmox-api/dist/esm/model.d.ts
@@ -2735,7 +2735,7 @@ export declare namespace Proxmox {
         /**
          * Used memory in bytes (when type in node,qemu,lxc).
          */
-        mem?: string;
+        mem?: number;
         /**
          * Name of the resource.
          */

This issue body was partially generated by patch-package.

Precision on usage

Hi I would like so precision on the usage of the hot-plug. As If you add an usb mouse with id 123:456 , the vm boot and you can plug or unplug the mouse and it will be catch back by proxmox.. So is your api bypass something or help if we change port or so .. or act on a port ?
thanks

proxmoxApi is not a function

When running the code from the example (with the for loop removed), here's an exact copy of the code I'm running:

require('dotenv').config();
const proxmoxApi = require("proxmox-api");

// authorize self signed cert if you do not use a valid SSL certificat
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

async function test() {
    // connect to proxmox
    const promox = proxmoxApi({host: process.env.HOST, password: process.env.PASSWORD, username: process.env.USER});
    // list nodes
    const nodes = await promox.nodes.$get();
    console.log(nodes)    
}

test().catch(console.error);

But when I run this code I get this error:
TypeError: proxmoxApi is not a function

Can we change the license from GPL-3.0

Is there a reason why the library is set to use GPL-3.0 becuse this will making the usage of the library a problem if someone uses it as all the code needs to be made public

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.