examples: add a script for bulk user update

you can use this sample script a a basis if you need to update
some common parameters for multiple users while preserving the others
This commit is contained in:
Nicola Murino 2021-01-27 19:18:37 +01:00
parent 02679d6df3
commit 9985224966
No known key found for this signature in database
GPG key ID: 2F1FB59433D5A8CB
2 changed files with 66 additions and 0 deletions

View file

@ -0,0 +1,17 @@
# Bulk user update
The `bulkuserupdate` example script shows how to use the SFTPGo REST API to easily update some common parameters for multiple users while preserving the others.
The script is written in Python and has the following requirements:
- python3 or python2
- python [Requests](https://requests.readthedocs.io/en/master/) module
The provided example tries to connect to an SFTPGo instance running on `127.0.0.1:8080` using the following credentials:
- username: `admin`
- password: `password`
and it updates some fields for `user1`, `user2` and `user3`.
Please edit the script according to your needs.

View file

@ -0,0 +1,49 @@
#!/usr/bin/env python
import posixpath
import sys
import requests
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
# change base_url to point to your SFTPGo installation
base_url = "http://127.0.0.1:8080"
# set to False if you want to skip TLS certificate validation
verify_tls_cert = True
# set the credentials for a valid admin here
admin_user = "admin"
admin_password = "password"
# insert here the users you want to update
users_to_update = ["user1", "user2", "user3"]
# set here the fields you need to update
fields_to_update = {"status":0, "quota_files": 1000, "additional_info":"updated using the bulkuserupdate example script"}
# get a JWT token
auth = requests.auth.HTTPBasicAuth(admin_user, admin_password)
r = requests.get(urlparse.urljoin(base_url, "api/v2/token"), auth=auth, verify=verify_tls_cert)
if r.status_code != 200:
print("error getting access token: {}".format(r.text))
sys.exit(1)
access_token = r.json()["access_token"]
auth_header = {"Authorization": "Bearer " + access_token}
for username in users_to_update:
r = requests.get(urlparse.urljoin(base_url, posixpath.join("api/v2/users", username)),
headers=auth_header, verify=verify_tls_cert)
if r.status_code != 200:
print("error getting user {}: {}".format(username, r.text))
continue
user = r.json()
user.update(fields_to_update)
r = requests.put(urlparse.urljoin(base_url, posixpath.join("api/v2/users", username)),
headers=auth_header, verify=verify_tls_cert, json=user)
if r.status_code == 200:
print("user {} updated".format(username))
else:
print("error updating user {}, response code: {} response text: {}".format(username,
r.status_code,
r.text))