unistra / python-glpi-api Goto Github PK
View Code? Open in Web Editor NEWPython module for interacting with GLPI using the API.
License: GNU General Public License v3.0
Python module for interacting with GLPI using the API.
License: GNU General Public License v3.0
Hello, Is this project still working on GLPI 9.5.5 ?
I just tried a very simple use case, where:
app_token is taken from Application Token (app_token)
and usertoken is the api_token inside user profile page. ( don't worry, tokens regenerated )
But when I try to run the basic python script below it fails with the following log:
glpi_api.GLPIError: (ERROR_LOGIN_PARAMETERS_MISSING)
with glpi_api.connect(url=URL, apptoken=APPTOKEN, auth=USERTOKEN, verify_certs=False) as glpi:
print(json.dumps(glpi.list_search_options('Ticket_User')))
Any ideas here ?
Api is enabled
GLPI API search method loads only first 20 rows, if you not specify more in range parameter. But range param is not implemented, sadly does the search method unusable for now.
Anyway repo is very helpful, thank you! Maybe I'll try to implement it by myself.
The method _set_method(self, *endpoints) generates an invalid path due to os.path routine under Windows (invalid path separator):
def _set_method(self, *endpoints): """Generate the URL from ``endpoints``.""" return os.path.join(self.url, *[str(endpoint) for endpoint in endpoints])
We can get the path as: https://127.0.0.1/glpi/apirest.php\search/Computer ... then GLPI reports a 404 error.
It's safer to construct path directly from *endpoints together with UNIX path separator.
Hello,
Is it possible to provide type hints for the API functions? Many people (myself included) work with static type checkers like mypy or pylance to make sure up to a point that no arbitrary conversions happen between data that haven't been accounted for.
Thanks in advance!
Hi everyone, i'm trying to create two entities...
I've got :
Root
i want :
Root > A > B
So after initializing my glpi_api session here's my code:
glpi.add("Entity", {'entities_id':'0', 'name':'A'}) glpi.add("Entity", {'entities_id: '1', 'name':'B'})
this code is for example. it works fine creating Entity A But then i got this error on entity B : (ERROR_GLPI_ADD) No permission [...]
I'm with a RECURSIVE super-admin profile.
This post in french is the closest i'm able to identify myself. But i didn't find a change_active_entity in glpi_api python module.
https://forum.glpi-project.org/viewtopic.php?id=288539
Do you have ideas ?
Thanks
Using quotes in search filters returns empty result.
Hello everyone.
I can't seem to update items no matter what input I give.
try:
with glpi_api.connect(URL, APPTOKEN, USERTOKEN, verify_certs=False) as glpi:
print(glpi.update('Computer', [{'id': 108, 'name': "test server1"}]))
print(glpi.update('Computer', {'id': 108, 'name': "test server1"}))
except glpi_api.GLPIError as err:
print(str(err))
I've even tried to create a request myself in which I get 200 OK but no message, nor the item is updated.
`def update_location(self, computer_id, location_id):
print("Updating location for computer id:", computer_id)
#-d '{"input": {"id": 11, "otherserial": "abcde"}}'
json_data = '{"input": {"id": ' + str(computer_id) + ', "locations_id": ' + str(location_id) + '}}'
response = self.session.put(url=self._update_computer_url(),
data=json_data,
verify=self.verify_certs)
print("Status code:", response.status_code)
return response
Any help will be appreciated.
hello,
if target GLPI sits on a webserver where only TLSv1.3 is allowed, you will get errot when calling connect
:
[SSLError: ("bad handshake: Error([('SSL routines', 'SSL23_GET_SERVER_HELLO', 'sslv3 alert handshake failure')],)",)](https://stackoverflow.com/questions/43969408/requests-exceptions-sslerror-bad-handshake-errorssl-routines-ssl23-ge)
Apache, which is a web server for the GLPI, is configured (/etc/apache2/sites-enabled/ssl.conf
in my case:
<VirtualHost xxxxxx:443>
...
...
SSLProxyProtocol +TLSv1.2
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1 -TLSv1.2
</VirtualHost>
Resolution:
Downgrade the server to TLSv1.2 solves the issue temporarily for me.
This is probably caused by either requests library or combination of python, requests, urlib and openssl libs.
I'm looking for a way to add a ticket follow-up after it is already create.
Are you planning to implement this functionality ?
setup.py
still mentions 0.3.0 in 0.3.1 release.
Then (on Debian GNU/Linux 11 (bullseye)):
python3 -m venv glpi
./glpi/bin/pip install git+https://github.com/unistra/[email protected]
./glpi/bin/pip list | grep glpi-api
glpi-api 0.3.0
Same with the tar ball: pip install https://github.com/unistra/python-glpi-api/archive/refs/tags/0.3.1.tar.gz
Hi there
As someone really happy about this package, i would like to hear if it would be possible to implement the following functions:
add_sub_items and update_sub_items
I had the need to have both of these functions in a project where we add entries to the glpi installation from another system.
I changed in my local installation, but i'm not sure if you want to do any of the following:
I basically copied the get_sub_item function and changed the names:
eg:
def add_sub_items(self, itemtype, item_id, sub_itemtype, *items):
And changed the method to either post or put, depending on if it is a update request or create.
I know it is not official on the api documentation from glpi, but it seems to work.
Either way let me know what you think.
Hello, j'ai un petit soucis, lorsque je suis en VPN.
Nous avons autorisé les adresses IP en 10.3.X.X sur l'API de GLPI.
import socket
hostname = socket. gethostname()
IPAddr=socket.gethostbyname(hostname)
Me retourne bien l'IP en 10.3, par contre lorsque je veux m'authentifier, j'ai un message d'erreur :
(ERROR_NOT_ALLOWED_IP) Il n'y a aucun client de l'API dans la configuration qui vérifie votre adresse IP (193.X.X.X.X)
193.X.X.X étant l'adresse de mon VPN.
Est il possible de forcer l'utilisation de l'IP de la machine?
Cordialement
When I create a new ticket using:
glpi.add('Ticket' , { 'name': 'TicketName , 'content': 'ticket title'} )
The ticket is created assigned to my user and with the state PROCESSING (Assigned ). Is there a way to make it unassigned and in NEW state ?
Having this code:
import requests
init_headers = {
'User-Agent': 'SOMETHING',
'Authorization': 'user_token [https://mydomain.com/front/preference.php API-TOKEN HERE]'
}
init_response = requests.get('https://mydomain.com//apirest.php/initSession/', headers=init_headers)
session_token = init_response.json()['session_token']
post_headers = {
'User-Agent': 'SOMETHING',
'Content-Type': 'application/json',
'Authorization': 'user_token [https://mydomain.com/front/preference.php API-TOKEN HERE]',
'Session-Token': session_token
}
# Define the query parameters to get all open tickets
query_params = {
'itemtype': 'Ticket',
}
data_response = requests.get('https://mydomain.comapirest.php/search/Ticket/', headers=post_headers,
params=query_params)
print(data_response.text)
I am able to get the tickets by the API. Is it possible to add the user_token method to the authentication methods?
Thanks
Bonjour,
J'essaie de modifier les valeurs de certains champs de mon "Applicatif" au sein de GLPI via l'api. J'utilise le plugin Fields qui m'a permis d'ajouter des champs particulier au sein de chaque Applicatif.
Lorsque j'utilise cette commande, tout fonctionne bien :
glpi.update('Appliance', {'id' : '1', 'name': 'monnouveaunom})
Si je veux update un champ créé par le plugin Field je n'y arrive pas.
glpi.update('Appliance', {'id' : '1', 'PluginFieldsApplianceobjetapplicatif.monchampfield': 'monnouveauchamp})
En revanche si je ne prends que la fin cela fonctionne :
glpi.update('Appliance', {'id' : '1', 'monchampfield': 'monnouveauchamp})
Ma question est la suivante, le cas précédemment vu concerne le cas ou les champs sont à texte simple...
J'ai un champ que je veux updater mais qui se présente sous la forme d'un DropDown...
Comment suis-je censé l'updater ?
Je veux lui attribuer la modalité "S" du dropdown (qui a pour id 12)
glpi.update('Appliance', {'id' : '1', 'plugin_fields_champaplusieursmodfielddropdo777592026.PluginFieldsApplianceobjetapplicatif.PluginFieldsVhampaplusieursmodfieldDropdown.name': 'S'})
Ne fonctionne pas...
J'ai essayé juste avec "name" mais ca me change l'intitulé de mon Appliance...
J'ai également essayé avec ["12"] ou "["12"]" ou [12] ou "[12] pour les valeurs mais sans succès...
Auriez vous une idée ?
Bien cordialement,
Method _map_fields
replaces the fields uid
to remove the itemtype
from it.
I've one field with uid Ticket.Group_Ticket.Group.completename
that gets translated to Group_Group.completename
, but should be Group_Ticket.Group.completename
The itemtype
should be deleted only from the beginning of the uid
Hi, I am having problems trying to make a search with multiple criterias.
I have created a ticket using this api and if I do a simple search by name using the following criteria I can get the result as expected:
criteria = [ {'field': 'name' , 'searchtype': 'contains', 'value': "^" + ticketName + "$" }
[
{
"2": 2021070035,
"1": "serverName - disk failure",
"80": "ORG",
"15": "2021-07-14 11:07:41",
"12": 1,
"7": null,
"4": "4785",
"5": null,
"19": "2021-07-14 11:07:41"
}
]
But I can not find a way to search for tickets with that name and status not '5' ( solved ).
First I tried the following:
criteria = [ {'field': 'name' , 'searchtype': 'contains', 'value': "^" + ticketName + "$" } ,{'field': 'status' , 'searchtype': 'notequals', 'value': "5" } ]
but it returned empty.
Then I tried
criteria = [ {'field': 'name' , 'searchtype': 'contains', 'value': "^" + subject + "$" } , { 'link': 'NOT', 'criteria': [ {'field': 'status' , 'searchtype': 'equals', 'value': "5" } ] } ]
Also empty.
What am I doing wrong ?
>>> criteria = [{"link": "AND", "criteria": [{"field": "Computer.name", "searchtype": "contains", "value": "example.com"}]}]
>>> glpi.search("Computer", criteria=criteria)
# returns the expected result
>>> print(criteria)
[{"link": "AND"}]
This is a problem when the input criteria are supposed to be used for another invocation, like when you have children groups in an Ansible GLPI inventory.
I'll open a PR fixing this in a minute.
The API supports "search criteria groups" like so:
criteria:
- field: name
searchtype: contains
value: example.org
- link: AND
criteria:
- field: Item_OperatingSystem.OperatingSystem.name
searchtype: contains
value: Debian
- link: OR
field: Item_OperatingSystem.OperatingSystem.name
searchtype: contains
value: Ubuntu
The library doesn't, however:
Traceback (most recent call last):
[...]
File "glpi_api.py", line 96, in wrapper
return func(self, *args, **kwargs)
File "glpi_api.py", line 615, in search
for param in ('criteria', 'metacriteria')
File "glpi_api.py", line 617, in <dictcomp>
for filter_param, value in c.items()})
AttributeError: 'list' object has no attribute 'replace'
Hi, thanks again for this awesome project!
This is not really a issue, but more like a help request. I read a lot the glpi documentation and this module's documentation and I already can do lots of things, but there is one "simple" thing that I am not able to do: I can not find a way to assign a group to a ticket.
I have tried: glpi.update('Group_Ticket' , { 'tickets_id': 2021060118, 'groups_id': 16, type: '2' } )
Do you think you could help me with this ?
I found a PHP code that works, but I would lile to use only python for this.
This is the PHP code that works( extracted from this link ):
$url=$api_url . "/Ticket/".$ticket_id."/group_ticket/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$json = curl_exec($ch);
curl_close ($ch);
$obj = json_decode($json,true);
$gp_ticket_id= $obj[0][id]; //Get the ID value
//And Update it //
$url=$api_url . "/group_ticket/".$gp_ticket_id."/";
$input='{ "input": {"id" : "'.$gp_ticket_id.'","groups_id": "'.$group_id.'","type": "2","use_notification": "1"}}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS,$input);
$request_result = curl_exec($ch);
curl_close ($ch);
$obj = json_decode($request_result,true);
print_r($request_result);
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.