Giter VIP home page Giter VIP logo

proxmoxer's Introduction

proxmoxer's People

Contributors

bigjools avatar chrisplo avatar developername1 avatar jmeridth avatar scap1784 avatar stappersg avatar swayf avatar tiewei avatar wdoekes avatar whirm 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

proxmoxer's Issues

Clone template?

Hi there,
Any way to clone an existing qemu template?
Tried something like :
node.qemu.clone.post(vmid=602)
But got an
ResourceException: 501 Not Implemented: b'{"data":null}'

Thanks!

Allow port specification in hostname

Right now, specifying a hostname with a port causes the API URL to have both the default port parameter and the one specified in the hostname. A module directly affected by this is the Ansible proxmox_kvm module which currently doesn't allow specifying a port.

I know the issue actually is with the Ansible module, but you might as well just add this here since it is a small change makes it more versatile.

Converting a vm to a template doesn't return Unique Task ID

Hi,

this is a small issue, but I think its worth knowing.
The following post request returns None, unlike the other requests which always return an Unique Task ID
'''
taskID = proxmox.connection.nodes("...").qemu("...").template.post()
'''
Best regards

IPv6 not supported

At least when trying to get proxmoxer runnning via the https Backend, it will fail if it is used with an IPv6 address. The port check is failing in HTTPS-Backend.

I would offer to fix this issue, but stating the not accepted PRs in this project, I will do so only if I get some kind of response beforehand.

Handling ssh-public-key

Extending the example of creating an LXC container with ssh-public-keys yields the error
SyntaxError: keyword can't be an expression

I have a patch prepared for documenting how to handle ssh-public-keys.

In this issue I can tell more then in a commit message of the upcoming pull request.

First time I encounter the SyntaxError: keyword can't be an expression
I wrongly thought it was Python detecting an arithmetic operation.
So I tried to solve it outside the Python code, request rewrites with mitmproxy and even modifying the proxmox API code.

With my patch on README.rst I hope that others can easy use proxmoxer and SSH keys in the created container.

proxmoxer/backends/https.py:78 fails on python3.4

Hi!
Here is code from proxmoxer/backends/https.py:78

        if isinstance(v, file):

The problem is that there is no 'file' class in python3.
There are some way to solve that problem:

  1. use io.IOBase:

import io

     if isinstance(v, io.IOBase):

that will drop python < 2.6
2) use separate function for each python:

import sys

if sys.version_info[0] >= 3:
    import io
    def is_file(obj): return isinstance(obj, io.IOBase)
else: 
    def is_file(obj): return isinstance(obj, file)

Unfortunatly, I cannot upload patch to make pull requests, so I write it here.

verify_ssl not in auth?

Hi,

is there a (good) reason why verify=False on https auth?

Otherwise I'd suggest:

--- proxmoxer/backends/https.py.orig	2017-03-28 11:40:27.269658645 +0200
+++ proxmoxer/backends/https.py	2017-03-28 11:41:26.152720669 +0200
@@ -38,9 +38,9 @@ class AuthenticationError(Exception):
 
 
 class ProxmoxHTTPAuth(AuthBase):
-    def __init__(self, base_url, username, password):
+    def __init__(self, base_url, username, password, verify_ssl):
         response_data = requests.post(base_url + "/access/ticket",
-                                      verify=False,
+                                      verify=verify_ssl,
                                       data={"username": username, "password": password}).json()["data"]
         if response_data is None:
             raise AuthenticationError("Couldn't authenticate user: {0} to {1}".format(username, base_url + "/access/ticket"))
@@ -98,7 +98,7 @@ class ProxmoxHttpSession(requests.Sessio
 class Backend(object):
     def __init__(self, host, user, password, port=8006, verify_ssl=True, mode='json', timeout=5):
         self.base_url = "https://{0}:{1}/api2/{2}".format(host, port, mode)
-        self.auth = ProxmoxHTTPAuth(self.base_url, user, password)
+        self.auth = ProxmoxHTTPAuth(self.base_url, user, password, verify_ssl)
         self.verify_ssl = verify_ssl
         self.mode = mode
         self.timeout = timeout

Return response content in case of non 400 response

Here is a way to retrieve the content of the response in case of non 400 response from the API ?
For example when you create a new Qemu virtual machine and the storage volume do not exist the API return a code 500 with a message like "volume do not exist"

proxmox.nodes(node['node']).openvz.get() gets 0 VMs on Proxmox 3.3-5

Hi there,

when writing proxtop [1] I noticed that your example -- from the README.rst -- to get all VMs did not work:

print("your example")
for node in proxmox.nodes.get():
    for vm in proxmox.nodes(node['node']).openvz.get():
        print("{0}. {1} => {2}" .format(vm['vmid'], vm['name'], vm['status']))
    print("--")

Yields:

your example
--
--
--

Instead, I used this:

print("my example")
for vm in proxmox.cluster.resources.get(type='vm'):
    print("{0}. {1} => {2}" .format(vm['vmid'], vm['name'], vm['status']))

Which yields:

127. private-herman => running
276. acme-bugs-bunny => stopped
443. acme-elmer-fudd => running

Thanks for the API B.T.W.! When comparing it, I favored it over the pyproxmox competition [2].

[1] https://github.com/ossobv/proxtop
[2] http://wjd.nu/notes/2015#proxmox-api-python-module

PVE 6 Beta: 'authorization on proxmox cluster failed with exception: invalid literal for float(): 6-0.1'

Source: https://forum.proxmox.com/threads/proxmox-ve-6-0-beta-released.55670/page-3#post-257027

Reason:

Yes, the "GET /nodes/{nodename}/version" call changed it's return format a bit, from PVE 5:

# pvesh get /nodes/dev5/version --output-format=json-pretty
{
   "release" : "11",
   "repoid" : "6df3d8d0",
   "version" : "5.4"
}
pvesh get /nodes/dev6/version --output-format=json-pretty
{
   "release" : "6.0",
   "repoid" : "c148050a",
   "version" : "6.0-1"
}

In short, the relase is now the main Proxmox VE relase (6.0 or 6.1 for example) repoid stayed the same and version is the full current manager version, (i.e., what the concatenation of "release" and "version" from the old 5.X call)

see https://git.proxmox.com/?p=pve-manager.git;a=commitdiff;h=b597d23d354665ddea247c3ad54ece1b84921768 for full details.

http error 500 after partial result

hi,
im using backend openssh, let proxmoxer connect to a server, and call for example /nodes (also tryed other urls with same result); i get the data of the proxmox-node im connected too, but after that i get 500 internal server error.

i think somehow proxmoxer or something on the node is trying to connect to the other nodes, and fails. but thats just a theory.

here is some output; i'm using proxmox-deploy which is a small tool also hosted on github.

$ proxmox-deploy
2017-05-03 22:33:33,003 INFO:proxmoxdeploy.cli: proxmox-deploy version 0.3 (build 7b45fa9) starting...
proxmox-deploy version 0.3 (build 7b45fa9) starting...
2017-05-03 22:33:33,014 INFO:proxmoxdeploy.cli: Asking user for configuration input
Asking user for configuration input
2017-05-03 22:33:33,014 DEBUG:proxmoxdeploy.proxmox: XXXX
XXXX
2017-05-03 22:33:33,015 INFO:proxmoxer.core: GET /nodes/pvehost01/storage
GET /nodes/pvehost01/storage
2017-05-03 22:33:38,915 DEBUG:proxmoxer.core: Status code: 500, output: [
{
"active" : 1,
"avail" : 32243920896,
"content" : "iso,images,rootdir,vztmpl",
"shared" : 0,
"storage" : "local",
"total" : 101327663104,
"type" : "dir",
"used" : 63913005056
}
]
Status code: 500, output: [
{
"active" : 1,
"avail" : 32243920896,
"content" : "iso,images,rootdir,vztmpl",
"shared" : 0,
"storage" : "local",
"total" : 101327663104,
"type" : "dir",
"used" : 63913005056
}
]
Traceback (most recent call last):
File "/home/pknoll/proxmox-deploy/run.py", line 10, in
sys.exit(main())
File "/home/pknoll/proxmox-deploy/proxmoxdeploy/cli.py", line 99, in main
(proxmox, cloudinit) = interact_with_user(args, api)
File "/home/pknoll/proxmox-deploy/proxmoxdeploy/cli.py", line 83, in interact_with_user
proxmox_answers = ask_proxmox_questions(api)
File "/home/pknoll/proxmox-deploy/proxmoxdeploy/proxmox.py", line 64, in ask_proxmox_questions
available_storage = proxmox.get_storage(chosen_node)
File "/home/pknoll/proxmox-deploy/proxmoxdeploy/proxmox.py", line 186, in get_storage
for storage in self.client.nodes(node).storage.get():
File "/usr/local/lib/python2.7/dist-packages/proxmoxer/core.py", line 84, in get
return self(args)._request("GET", params=params)
File "/usr/local/lib/python2.7/dist-packages/proxmoxer/core.py", line 79, in _request
raise ResourceException("{0} {1}".format(resp.status_code, httplib.responses[resp.status_code]))
proxmoxer.core.ResourceException: 500 Internal Server Error

pknoll@docker-mgmt-01:/usr/local/lib/python2.7/dist-packages/proxmoxer$ cat init.py
author = 'Oleg Butovich'
copyright = '(c) Oleg Butovich 2013-2017'
version = '0.2.5'

proxmox Virtual Environment 4.4-13/7ea56165

im happy to add more details if needed.

did you ever come across something like this? is it maybe a known thing and im just not googleing well enough?

thankfull for any pointers,
cheers,
fil

New version urllib3 write warning message.

In the new version write warning message to http error logs.
[Mon Nov 10 21:06:55 2014] [error] [client 192.168.7.1] /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py:730: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html (This warning will only appear once by default.)
[Mon Nov 10 21:06:55 2014] [error] [client 192.168.7.1] InsecureRequestWarning)
discussed here:
https://github.com/kennethreitz/requests/issues/2214

create fails with 501 Not Implemented

I've written a script to create VM's in proxmox:

$ cat picknode 
#!/usr/bin/env python

from proxmoxer import ProxmoxAPI
#from hurry.filesize import size
import getpass
import pprint
import re
import operator

pp = pprint.PrettyPrinter(indent=5)

apipass = getpass.getpass()

proxmox = ProxmoxAPI('proxmox1-oak.telmate.cc', user='[email protected]',
                     password=apipass, verify_ssl=False)

def discover_nodes():
    picker = {
            'staging': {}, 
            'prod': {}, 
            'db': {}, 
    }

    for node in proxmox.nodes.get():
        node_name = node['node']
        #print node_name + ":"
        mem_perc = 100*node['mem']/node['maxmem']
        #print "mem={0:.3f}%".format(mem_perc)

        if re.match(".*staging",node_name):
            picker['staging'][node_name] = mem_perc
        elif re.match(r".*db\d+-.*",node_name):
            picker['db'][node_name] = mem_perc
        else:
            picker['prod'][node_name] = mem_perc

    return picker;

#pp.pprint(picker)

def pick(env):
    picker = discover_nodes()

    if not env in picker:
        raise LookupError(env + " is not a valid environment")

    sorted_nodes = sorted(picker[env].items(), key=operator.itemgetter(1))
    #pp.pprint(sorted_nodes)

    return sorted_nodes[0][0];

def nextvmid():
    netmax = 0
    othermax = 0
    for vm in proxmox.cluster.resources.get(type='vm'):
        #pp.pprint(vm)
        vmid = vm['vmid']
        if vmid > 3300:
            # netops
            if vmid > netmax:
                netmax = vmid
        else:
            # not netops
            if vmid > othermax:
                othermax = vmid

    # handle overflow of other
    if othermax < 3300-1:
        return othermax+1
    else:
        return netmax+1

vmid = nextvmid()
print "vmid={0:d}".format(vmid)
picked = pick('prod')
print "picked {0}".format(picked)

node = proxmox.node(picked)
print type(node)
#pp.pprint(node)

node.openvz.create(vmid=vmid,
                   ostemplate='',
                   hostname='chicks-test0',
                   storage='local',
                   memory=512,
                   swap=512,
                   cpus=1,
                   disk=4,
                   password='PLACEHOLDER',
                   ip_address='10.33.8.116')

I'm really trying to create qemu VM's but I figured I would try to follow the posted example closer. Either way I get:

$ ./picknode 
Password: 
vmid=242
picked proxmox7-oak
<class 'proxmoxer.core.ProxmoxResource'>
Traceback (most recent call last):
  File "./picknode", line 91, in <module>
    ip_address='10.33.8.116')
  File "/home/chicks/Documents/proxmox-api/venv.proxmox/local/lib/python2.7/site-packages/proxmoxer/core.py", line 96, in create
    return self.post(*args, **data)
  File "/home/chicks/Documents/proxmox-api/venv.proxmox/local/lib/python2.7/site-packages/proxmoxer/core.py", line 87, in post
    return self(args)._request("POST", data=data)
  File "/home/chicks/Documents/proxmox-api/venv.proxmox/local/lib/python2.7/site-packages/proxmoxer/core.py", line 79, in _request
    raise ResourceException("{0} {1}".format(resp.status_code, httplib.responses[resp.status_code]))
proxmoxer.core.ResourceException: 501 Not Implemented

I'm running PVE manager version pve-manager/3.4-13/4c74557.

get vm config of current config

HI,
I try to get the config of the current vm in stead of pending ones

pve api says
current - boolean - 0 - Get current values (instead of pending values).

so I did
vm_config = self.proxmox.nodes(node_name).qemu(vm_id).config.get(current="true")

but it fails...
only 0 and 1 are accepted from current. But True should be supported too or not ?
Please point me to my fault.

Unable to use dashed API commands.

In recent versions of the Proxmox API, several commands containing dashes have appeared, specially in the qemu->agent section. I'm unable to use them, since python sees the dash as a substraction operator.
It would be great if proxmoxer converted underscore params to dashes, so we could call it like this:
...qemu(100).agent.network_get_interfaces.get()
And be converted to this:
...qemu/{vmid}/agent/network-get-interfaces

How to add a disk to already created VM?

Hi there folks, I'm facing issues when trying to add a new additional hard disk to an already created VM. I browsed through https://pve.proxmox.com/pve-docs/api-viewer/ and understood the structure but getting 501 Not Implemented: {"data":null}
Here is my code:

vmIds = array('i', [208])

headIds = array('i', [3302])

vmIdIdx = 0

for HEAD in headIds:
    vmId = vmIds[vmIdIdx]
    headId = 'proxmox-' + str(HEAD)
    print('proxmox-node -->' + headId, ' | VMID -->' + str(vmId))

    qemu_node = proxmox.nodes(headId)
    vm_config_old = qemu_node.qemu(vmIds[vmIdIdx]).config.get()
    print('Host details before adding disk')
    pp.pprint(vm_config_old)

#     pp.pprint(qemu_node.storage.get(storage='xxx-xxxx-vol-xx1')) # This line prints fine
    qemu_node.storage.content.create(filename='var/lib/docker-config',
                                     vmid=vmId, node=headId,
                                     storage='xxx-xxxx-vol-xx1', size='32767M', format='qcow2')
    vm_config_new = qemu_node.qemu(vmIds[vmIdIdx]).config.get()
    print('Host details after adding disk')
    pp.pprint(vm_config_new)
    vmIdIdx = vmIdIdx + 1

Here is the error:

Traceback (most recent call last):
  File "add_disk_to_tr1_vm.py", line 47, in <module>
    storage='netapp-prod-vol-ds1', size='32767M', format='qcow2')
  File "/usr/local/lib/python2.7/site-packages/proxmoxer/core.py", line 96, in create
    return self.post(*args, **data)
  File "/usr/local/lib/python2.7/site-packages/proxmoxer/core.py", line 87, in post
    return self(args)._request("POST", data=data)
  File "/usr/local/lib/python2.7/site-packages/proxmoxer/core.py", line 79, in _request
    resp.content))
proxmoxer.core.ResourceException: 501 Not Implemented: {"data":null}

Any pointers will be helpful.
Thanks.

KeyError: 599

Proxmox can return HTTP status 599, which is not defined in any RFC, but fairly commonly used. Proxmoxer doesn't handle this correctly as it has no safeguards around looking up the httpstatus code in http.client. Code can be found in core.py lines 77-79

if resp.status_code >= 400:
            raise ResourceException("{0} {1}: {2}".format(resp.status_code, httplib.responses[resp.status_code],
                                                          resp.content))

suggestion would be to check if resp.status_code is in httplib.responses, and if not, throw a different error

Documentation on arguments and options

Hello

I would like to know where I can find the list of arguments, notably for "netif" like in:

    net0='name=eth0,bridge=vmbr0,ip=192.168.22.1/20,gw=192.168.16.1')

401 Unauthorized errors

As mentioned in #26 I also have 401 Unauthorized errors due to the session timing out.

File "/home/gerard/.local/lib/python3.6/site-packages/proxmoxer/core.py", line 79, in _request
    resp.content))
proxmoxer.core.ResourceException: 401 Unauthorized: b''

Is it possible to implement a fix for this? There are already some suggestions mentioned in that issue.

What is the status of this project?

What is the current status of this project? Is it still being actively maintained?

There hasn't been a commit to master since September 2018 and there are 10 pull requests waiting since July 2018.

Proxmox api change?

After updating proxmox to 5.2-8 all of my proxmoxer-python scripts are not working anymore:
Example with python3
2018-09-13 10:46:12,698 INFO:proxmoxer.core: GET /nodes/moritz/storage/backup/content 2018-09-13 10:46:12,699 DEBUG:paramiko.transport: [chan 0] Max packet in: 32768 bytes 2018-09-13 10:46:14,363 DEBUG:proxmoxer.core: Status code: 500, output: ┌─────────┬────────────┬───────────────────────────────────────────────────────────────────────────────────────────┬────────┬──────┬──────┐ │ format │ size │ volid │ parent │ used │ vmid │ ├─────────┼────────────┼───────────────────────────────────────────────────────────────────────────────────────────┼────────┼──────┼──────┤
the same with pyton2
2018-09-13 11:25:06,789 INFO:proxmoxer.core: GET /nodes/moritz/storage/backup/content 2018-09-13 11:25:06,789 DEBUG:paramiko.transport: [chan 0] Max packet in: 32768 bytes ... 2018-09-13 11:25:08,309 DEBUG:paramiko.transport: [chan 0] EOF received (0) Traceback (most recent call last): File "/usr/local/bin/vm_kontrolle_backup.py", line 17, in <module> backup = node.storage('backup').content.get() File "/usr/local/lib/python2.7/dist-packages/proxmoxer/core.py", line 84, in get return self(args)._request("GET", params=params) File "/usr/local/lib/python2.7/dist-packages/proxmoxer/core.py", line 74, in _request resp = self._store["session"].request(method, url, data=data or None, params=params) File "/usr/local/lib/python2.7/dist-packages/proxmoxer/backends/base_ssh.py", line 46, in request stdout, stderr = self._exec(full_cmd) File "/usr/local/lib/python2.7/dist-packages/proxmoxer/backends/ssh_paramiko.py", line 59, in _exec stdout = session.makefile('rb', -1).read().decode() 2018-09-13 11:25:08,310 DEBUG:paramiko.transport: [chan 0] EOF sent (0) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
I've also tried older versions of proxmoxer

Please add missing files to the released tarball

Hello.

I've noticed that the tarball released on pypi (https://pypi.python.org/pypi/proxmoxer) is missing the LICENSE file; besides being useful to check the actual terms of the license, this incidentally makes that tarball non redistributable, as it's missing the notice required by the license itself.

I think it would also be nice to include the tests directory in the tarball: while not everybody needs them, I often find them useful as documentation and to check that a module has been correctly installed (and they would make my life easier when packaging proxmoxer for debian).

Thanks in advance.

i want create contener and i get this error

node.lxc.create(vmid=202,ostemplate='local:vztmpl/mini.iso',hostname='otine',storage='local',memory=512,swap=512,cores=1,password='secret',net0='name=eth0,bridge=vmbr0,ip=192.168.22.1/20,gw=192.168.16.1')
File "C:\Users\power\PycharmProjects\last\venv\lib\site-packages\proxmoxer\core.py", line 96, in create
return self.post(*args, **data)
File "C:\Users\power\PycharmProjects\last\venv\lib\site-packages\proxmoxer\core.py", line 87, in post
return self(args)._request("POST", data=data)
File "C:\Users\power\PycharmProjects\last\venv\lib\site-packages\proxmoxer\core.py", line 79, in _request
resp.content))
proxmoxer.core.ResourceException: 500 Internal Server Error: b'{"data":null}'

Handling config object of vm

First, I am pretty new to Python and Proxmox, so I am not sure if this is an issue or just my experience. I apologize in advance for any offense.

I am using the base sample code to get to the /node/nodename/qemu/vmname/config so that I can pull the net0 key in the dictionary and parse the value.

Here is my code.

for node in proxmox.nodes.get():
for vm in proxmox.nodes(node['node']).qemu.get():
print('nodes/{0}/qemu/{1}/config'.format(node['node'], vm['vmid']))
f = proxmox.get('nodes/{0}/qemu/{1}/config'.format(node['node'], vm['vmid']))
print (f)

Here is my output:

nodes/pve5/qemu/116/config
<proxmoxer.core.ProxmoxResource object at 0x0000000003FB04A8>

If I run the same in pvesh, I get the dictionary object back, no problem, but I don't want to install pvesh onto the vms.

root@pve3:~# pvesh get /nodes/pve5/qemu/116/config
200 OK
{
"bootdisk" : "scsi0",
"cores" : 4,
"digest" : "73af400d29537a6d223403db60b68b7e52c781a9",
"ide2" : "none,media=cdrom",
"memory" : 4096,
"name" : "dat03.int.wscnet.com",
"net0" : "virtio=16:E3:62:B7:2F:48,bridge=vmbr0",
"net1" : "virtio=36:EE:1F:7A:9E:86,bridge=vmbr1",
"numa" : 0,
"ostype" : "l26",
"scsi0" : "pme-vms1:116/vm-116-disk-1.qcow2,size=32G",
"scsi1" : "local-lvm:vm-116-disk-1,size=100G",
"scsihw" : "virtio-scsi-pci",
"smbios1" : "uuid=0b9dab19-a871-48d4-8105-2b698fa9fac8",
"sockets" : 1
}

Is there something that I need to add to my GET request:
proxmox.get('nodes/{0}/qemu/{1}/config'.format(node['node'], vm['vmid']))

In order to get the config dictionary? I have also tried several different ways of getting to the dictionary.
For example, print(f.dict), just gives me

{'_store': {'session': <proxmoxer.backends.https.ProxmoxHttpSession object at 0x00000000035390B8>, 'serializer': <proxmoxer.backends.https.JsonSerializer object at 0x00000000030764A8>, 'base_url': 'https://pve1.int.wscnet.com:8006/api2/json/get/nodes/pve5/qemu/117/config'}}
nodes/pve5/qemu/116/config

I have searched all over and have not found a single example of people attempting this, which I could leverage.

Thanks in advance,

Bill Callahan

Problems with version 5.3

Hi,
I get with the newest proxmox version the following errors:

Traceback (most recent call last):
  File "/root/proxmox-dokuwiki-exporter.py", line 27, in <module>
    for node in proxmox.nodes.get():
  File "/root/.local/lib/python3.5/site-packages/proxmoxer/core.py", line 84, in get
    return self(args)._request("GET", params=params)
  File "/root/.local/lib/python3.5/site-packages/proxmoxer/core.py", line 79, in _request
    resp.content))
proxmoxer.core.ResourceException: 500 Internal Server Error: 

As message In the server error I get a full graph of my cluster (here redacted). what the hell?!

The line that triggers this error is this one here: for node in proxmox.nodes.get():

problems with custom post request.

i have some problems with custom post request
code example

    nextid = proxmox.cluster.nextid.get()
    node5 = proxmox.nodes('proxmox5')
    node5.qemu.create(
        '/api2/json/nodes/proxmox5/qemu/%s/clone' % template_id,
        data={'newid': nextid}
    )

answer:

proxmoxer.core.ResourceException: 400 Bad Request: b'{"data":null,"errors":{"data":"property is not defined in schema and the schema does not allow additional properties","newid":"property is missing and it is not optional"}}'

problem in data parameter.

/api2/json/nodes/proxmox5/qemu/100/clone {'data': {'newid': '102'}}

but need

/api2/json/nodes/proxmox5/qemu/100/clone {'newid': '102'}

500 internal server

Hello,
I have this code:

for node in proxmox.nodes.get():                     
    for vm in proxmox.nodes(node['node']).qemu.get():
        print(vm)

Why do I get a 500 internal server error for some servers?

2018-11-23 15:51:06,709 INFO:proxmoxer.core: GET /nodes/cloud-19/qemu                                            
2018-11-23 15:51:06,710 DEBUG:paramiko.transport: [chan 10] Max packet in: 32768 bytes                           
2018-11-23 15:51:06,712 DEBUG:paramiko.transport: [chan 9] EOF sent (9)                                          
2018-11-23 15:51:06,714 DEBUG:paramiko.transport: [chan 10] Max packet out: 32768 bytes                          
2018-11-23 15:51:06,714 DEBUG:paramiko.transport: Secsh channel 10 opened.                                       
2018-11-23 15:51:06,762 DEBUG:paramiko.transport: [chan 10] Sesch channel 10 request ok                          
2018-11-23 15:51:08,537 DEBUG:paramiko.transport: [chan 10] EOF received (10)                                    
2018-11-23 15:51:08,538 DEBUG:proxmoxer.core: Status code: 500, output:                                          
Traceback (most recent call last):                                                                               
  File "proxmox-dokuwiki-exporter.py", line 24, in <module>                                                      
    for vm in proxmox.nodes(node['node']).qemu.get():                                                            
2018-11-23 15:51:08,541 DEBUG:paramiko.transport: [chan 10] EOF sent (10)                                        
  File "/home/chris/.virtualenvs/proxmox-dokuwiki-exporter/lib/python3.7/site-packages/proxmoxer/core.py", line 8
4, in get                                                                                                        
    return self(args)._request("GET", params=params)                                                             
  File "/home/chris/.virtualenvs/proxmox-dokuwiki-exporter/lib/python3.7/site-packages/proxmoxer/core.py", line 7
9, in _request                                                                                                   
    resp.content))                                                                                               
proxmoxer.core.ResourceException: 500 Internal Server Error:                                                     

Renew Session?

After running for a while, this package will start getting 401 Unauthorized errors due to the session timing out. We need a function to renew the session that we can call periodically, say every 30 minutes.

TypeError: __call__() takes from 1 to 2 positional arguments but 7 were given

I have the following code:

proxmox.get('nodes', node['node'], 'qemu', vm['vmid'], 'config', 'description')                

shouldn't this work? I try to get the information in /nodes/<node>/qemu/<vmid>/config/description, but instead I get this TypeError Exception:

2018-11-23 16:23:44,652 DEBUG:paramiko.transport: [chan 1] EOF sent (1)          
  File "proxmox-dokuwiki-exporter.py", line 36, in <module>                      
    'description')                                                               
TypeError: __call__() takes from 1 to 2 positional arguments but 7 were given    

creation problm

print(proxmox.create('/nodes/pve/qemu -name oti -vmid 111 -scsi0 local-lvm:16 -memory 2048 -cpu host -socket 2 -cores 2 -net0 virtio,bridge=vmbr0 -cdrom backup:iso/mini.iso'))

when i try to create a VM with this code i get a message :

<proxmoxer.core.ProxmoxResource object at 0x000001B6BEF75FD0>

If user's locale is not installed in proxmox, ssh calls all fail.

When using Proxmoxer via the ssh method, if your local is not available on the Proxmox host then there's some warnings in the stderr that's returned to the call site, which results in the code thinking that it's a fatal error and returns a 500 status in the response.

ipdb> full_cmd
'pvesh get /nodes/proxmox15/qemu'
ipdb> n
> proxmoxer/backends/base_ssh.py(46)request()
     45         stdout, stderr = self._exec(full_cmd)
---> 46         try:
     47             status_code = int(stderr.split()[0])

ipdb> stderr
'perl: warning: Setting locale failed.\nperl: warning: Please check that your locale settings:\n\tLANGUAGE = (unset),\n\tLC_ALL = (unset),\n\tLC_TIME = "en_GB.UTF-8",\n\tLANG = "en_US.UTF-8"\n    are supported and installed on your system.\nperl: warning: Falling back to a fallback locale ("en_US.UTF-8").\n200 OK'

which ends up causing:

ValueError: "invalid literal for int() with base 10: 'perl:'"
> proxmoxer/backends/base_ssh.py(47)request()
     46         try:
---> 47             status_code = int(stderr.split()[0])
     48         except:

better errors on authentication errors

I get the following when I have a bad authentication

In[3]: p = proxmoxer.ProxmoxAPI('gravity', user='root@pam', password='foo', verify_ssl=False)
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2883, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-ec400ea48901>", line 1, in <module>
    p = proxmoxer.ProxmoxAPI('server', user='root@pam', password='foo', verify_ssl=False)
  File "C:\Python27\lib\site-packages\proxmoxer\core.py", line 95, in __init__
    self._backend = imp.load_module(backend, *found_module).Backend(host, **kwargs)
  File "C:\Python27\lib\site-packages\proxmoxer\backends\https.py", line 79, in __init__
    self.auth = ProxmoxHTTPAuth(self.base_url, user, password)
  File "C:\Python27\lib\site-packages\proxmoxer\backends\https.py", line 26, in __init__
    self.pve_auth_cookie = response_data["ticket"]
TypeError: 'NoneType' object has no attribute '__getitem__'

This isn't very useful for dealing with authentication errors. raising a AuthenticationError or having a way to check if the authentication was successful would likely be more appropriate. Now to catch a authentication error I have to wrap the authentication in a

try:
    # build the proxmoxapi object here
except TypeError:
    # It seems like other things could raise this exception

Perhaps this is too nit picky or maybe there is a better way to deal with this is python but I think it would be nice to raise an AuthenticationError when this occurs.

Failing test: tests.https_tests.test_https_connection

Running the tests (from the relased tarball proxmoxer-1.0.2.tar.gz) with nosetests3 tests.https_tests tests.paramiko_tests I get the following failure (nosetests with python2 gives a similar, but not identical error):

======================================================================
ERROR: tests.https_tests.test_https_connection
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/usr/lib/python3/dist-packages/mock/mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "/home/valhalla/tmp/proxmoxer/proxmoxer-1.0.2/tests/https_tests.py", line 16, in test_https_connection
    call = req_session.return_value.request.call_args[1]
TypeError: 'NoneType' object is not subscriptable

Am I correct in understanding that this is because the test suite is expecting a proxmox server at proxmox, which other people are probably not going to have.

Should it be mentioned somewhere in the docs, (and/or in a comment in the code)?

boolean parameter not serialized correctly

prox.nodes('pve1').lxc(500).clone.create(newid=501, full=True, hostname="worker1", pool="workers")

results in:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/site-packages/proxmoxer/core.py", line 181, in create
    return self.post(*args, **data)
  File "/usr/local/lib/python3.8/site-packages/proxmoxer/core.py", line 172, in post
    return self(args)._request("POST", data=data)
  File "/usr/local/lib/python3.8/site-packages/proxmoxer/core.py", line 149, in _request
    raise ResourceException(
proxmoxer.core.ResourceException: 400 Bad Request: Parameter verification failed. - {'full': "type check ('boolean') failed - got 'True'"}

ImportError: cannot import name ProxmoxAPI

I've this error when I try to use proxmoxer

Tried on Debian 9 and Ubuntu 16.04

Package dependecies are installed


root@localhost:~# cat proxmoxer.py
from proxmoxer import ProxmoxAPI
proxmox = ProxmoxAPI('_my_ip_', user='root@pam',
                     password='***', verify_ssl=False)
Traceback (most recent call last):
   File "proxmoxer.py", line 1, in <module>
     from proxmoxer import ProxmoxAPI
   File "/root/proxmoxer.py", line 1, in <module>
     from proxmoxer import ProxmoxAPI
ImportError: cannot import name ProxmoxAPI

Any ideas?

Still working (python3)?

Hello folks!

I'm trying to use this library to automate some tasks but I don't know if proxmoxer is still maintained nor still working with the proxmox version 6.x

I'm importing proxmoxer as mentioned in the ReadMe in a python3.7 environment and I'm getting errors all the time.

Best regards

KVM current disk space not showing

Hi,

Using Proxmoxer:

{u'node': u'kvm-03', u'status': u'running', u'uptime': 881010, u'hastate': u'started', u'name': u'X-vm', u'maxcpu': 2, u'diskread': 8949149848, u'mem': 3554562048, u'vmid': 111, u'netin': 1252519321, u'cpu': 0.00837704669003285, u'diskwrite': 19621984256, u'template': 0, u'netout': 895871658, u'disk': 0, u'type': u'qemu', u'id': u'qemu/111', u'maxdisk': 32212254720, u'maxmem': 4294967296}

The u'disk' is empty. Using pvesh get /cluster/resources/ I can see the disk space.
How would I fix this?

EDIT:

For nodes it works, but not for VM's.
{u'node': u'kvm-01', u'status': u'online', u'uptime': 516716, u'maxcpu': 24, u'level': u'', u'mem': 11441430528, u'id': u'node/kvm-01', u'disk': 10191282176, u'type': u'node', u'cpu': 0.0568762327337271, u'maxdisk': 17568661504, u'maxmem': 50626011136}

Thank you!

Encryption of SSH keys

sshkeys for qemu hosts

Python3 code!
For using the SSH keys for configuring cloud-init qemu host, the sshkey needs to be encrypted with urllib.parse.quote and then all '/' replaced.
ssh_key=urllib.parse.quote(ssh_key).replace('/', '%2F')

This is not really issue, it is notice for others as there is no Wiki.

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.