• Stars
    star
    270
  • Rank 152,163 (Top 3 %)
  • Language
    Python
  • License
    Other
  • Created about 10 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Thin wrapper around OVH's APIs. Handles all the hard work including credential creation and requests signing.
Python & OVH APIs

Lightweight wrapper around OVHcloud's APIs. Handles all the hard work including credential creation and requests signing.

PyPi Version PyPi repository status PyPi supported Python versions PyPi Wheel status Build Status Coverage Status
import ovh

# Instantiate. Visit https://api.ovh.com/createToken/?GET=/me
# to get your credentials
client = ovh.Client(
    endpoint='ovh-eu',
    application_key='<application key>',
    application_secret='<application secret>',
    consumer_key='<consumer key>',
)

# Print nice welcome message
print("Welcome", client.get('/me')['firstname'])

Installation

The python wrapper works with Python 3.6+.

The easiest way to get the latest stable release is to grab it from pypi using pip.

pip install ovh

Alternatively, you may get latest development version directly from Git.

pip install -e git+https://github.com/ovh/python-ovh.git#egg=ovh

People looking for Python 2 compatibility should use 0.6.x version.

Example Usage

Use the API on behalf of a user

1. Create an application

To interact with the APIs, the SDK needs to identify itself using an application_key and an application_secret. To get them, you need to register your application. Depending the API you plan to use, visit:

Once created, you will obtain an application key (AK) and an application secret (AS).

2. Configure your application

The easiest and safest way to use your application's credentials is to create an ovh.conf configuration file in application's working directory. Here is how it looks like:

[default]
; general configuration: default endpoint
endpoint=ovh-eu

[ovh-eu]
; configuration specific to 'ovh-eu' endpoint
application_key=my_app_key
application_secret=my_application_secret
; uncomment following line when writing a script application
; with a single consumer key.
;consumer_key=my_consumer_key

Depending on the API you want to use, you may set the endpoint to:

  • ovh-eu for OVH Europe API
  • ovh-us for OVH US API
  • ovh-ca for OVH North-America API
  • soyoustart-eu for So you Start Europe API
  • soyoustart-ca for So you Start North America API
  • kimsufi-eu for Kimsufi Europe API
  • kimsufi-ca for Kimsufi North America API

See Configuration for more information on available configuration mechanisms.

Note

When using a versioning system, make sure to add ovh.conf to ignored files. It contains confidential/security-sensitive information!

3. Authorize your application to access a customer account

To allow your application to access a customer account using the API on your behalf, you need a consumer key (CK).

Here is a sample code you can use to allow your application to access a customer's information:

import ovh

# create a client using configuration
client = ovh.Client()

# Request RO, /me API access
ck = client.new_consumer_key_request()
ck.add_rules(ovh.API_READ_ONLY, "/me")

# Request token
validation = ck.request()

print("Please visit %s to authenticate" % validation['validationUrl'])
input("and press Enter to continue...")

# Print nice welcome message
print("Welcome", client.get('/me')['firstname'])
print("Btw, your 'consumerKey' is '%s'" % validation['consumerKey'])

Returned consumerKey should then be kept to avoid re-authenticating your end-user on each use.

Note

To request full and unlimited access to the API, you may use add_recursive_rules:

# Allow all GET, POST, PUT, DELETE on /* (full API)
ck.add_recursive_rules(ovh.API_READ_WRITE, '/')

Install a new mail redirection

e-mail redirections may be freely configured on domains and DNS zones hosted by OVH to an arbitrary destination e-mail using API call POST /email/domain/{domain}/redirection.

For this call, the api specifies that the source address shall be given under the from keyword. Which is a problem as this is also a reserved Python keyword. In this case, simply prefix it with a '_', the wrapper will automatically detect it as being a prefixed reserved keyword and will substitute it. Such aliasing is only supported with reserved keywords.

import ovh

DOMAIN = "example.com"
SOURCE = "[email protected]"
DESTINATION = "[email protected]"

# create a client
client = ovh.Client()

# Create a new alias
client.post('/email/domain/%s/redirection' % DOMAIN,
        _from=SOURCE,
        to=DESTINATION,
        localCopy=False
    )
print("Installed new mail redirection from %s to %s" % (SOURCE, DESTINATION))

Grab bill list

Let's say you want to integrate OVH bills into your own billing system, you could just script around the /me/bills endpoints and even get the details of each bill lines using /me/bill/{billId}/details/{billDetailId}.

This example assumes an existing Configuration with valid application_key, application_secret and consumer_key.

import ovh

# create a client
client = ovh.Client()

# Grab bill list
bills = client.get('/me/bill')
for bill in bills:
    details = client.get('/me/bill/%s' % bill)
    print("%12s (%s): %10s --> %s" % (
        bill,
        details['date'],
        details['priceWithTax']['text'],
        details['pdfUrl'],
    ))

Enable network burst in SBG1

'Network burst' is a free service but is opt-in. What if you have, say, 10 servers in SBG-1 datacenter? You certainly don't want to activate it manually for each servers. You could take advantage of a code like this.

This example assumes an existing Configuration with valid application_key, application_secret and consumer_key.

import ovh

# create a client
client = ovh.Client()

# get list of all server names
servers = client.get('/dedicated/server/')

# find all servers in SBG-1 datacenter
for server in servers:
    details = client.get('/dedicated/server/%s' % server)
    if details['datacenter'] == 'sbg1':
        # enable burst on server
        client.put('/dedicated/server/%s/burst' % server, status='active')
        print("Enabled burst for %s server located in SBG-1" % server)

List application authorized to access your account

Thanks to the application key / consumer key mechanism, it is possible to finely track applications having access to your data and revoke this access. This examples lists validated applications. It could easily be adapted to manage revocation too.

This example assumes an existing Configuration with valid application_key, application_secret and consumer_key.

import ovh
from tabulate import tabulate

# create a client
client = ovh.Client()

credentials = client.get('/me/api/credential', status='validated')

# pretty print credentials status
table = []
for credential_id in credentials:
    credential_method = '/me/api/credential/'+str(credential_id)
    credential = client.get(credential_method)
    application = client.get(credential_method+'/application')

    table.append([
        credential_id,
        '[%s] %s' % (application['status'], application['name']),
        application['description'],
        credential['creation'],
        credential['expiration'],
        credential['lastUse'],
    ])
print(tabulate(table, headers=['ID', 'App Name', 'Description',
                               'Token Creation', 'Token Expiration', 'Token Last Use']))

Before running this example, make sure you have the tabulate library installed. It's a pretty cool library to pretty print tabular data in a clean and easy way.

>>> pip install tabulate

Open a KVM (remote screen) on a dedicated server

Recent dedicated servers come with an IPMI interface. A lightweight control board embedded on the server. Using IPMI, it is possible to get a remote screen on a server. This is particularly useful to tweak the BIOS or troubleshoot boot issues.

Hopefully, this can easily be automated using a simple script. It assumes Java Web Start is fully installed on the machine and a consumer key allowed on the server exists.

import ovh
import sys
import time
import tempfile
import subprocess

# check arguments
if len(sys.argv) != 3:
    print("Usage: %s SERVER_NAME ALLOWED_IP_V4" % sys.argv[0])
    sys.exit(1)

server_name = sys.argv[1]
allowed_ip = sys.argv[2]

# create a client
client = ovh.Client()

# create a KVM
client.post('/dedicated/server/'+server_name+'/features/ipmi/access', ipToAllow=allowed_ip, ttl=15, type="kvmipJnlp")

# open the KVM, when ready
while True:
    try:
        # use a named temfile and feed it to java web start
        with tempfile.NamedTemporaryFile() as f:
            f.write(client.get('/dedicated/server/'+server_name+'/features/ipmi/access?type=kvmipJnlp')['value'])
            f.flush()
            subprocess.call(["javaws", f.name])
        break
    except:
        time.sleep(1)

Running is only a simple command line:

# Basic
python open_kvm.py ns1234567.ip-42-42-42.eu $(curl ifconfig.ovh)

# Use a specific consumer key
OVH_CONSUMER_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA python open_kvm.py ns1234567.ip-42-42-42.eu $(curl -s ifconfig.ovh)

Configuration

You have 3 ways to provide configuration to the client:
  • write it directly in the application code
  • read environment variables or predefined configuration files
  • read it from a custom configuration file

Embed the configuration in the code

The straightforward way to use OVH's API keys is to embed them directly in the application code. While this is very convenient, it lacks of elegance and flexibility.

Example usage:

client = ovh.Client(
    endpoint='ovh-eu',
    application_key='<application key>',
    application_secret='<application secret>',
    consumer_key='<consumer key>',
)

Environment vars and predefined configuration files

Alternatively it is suggested to use configuration files or environment variables so that the same code may run seamlessly in multiple environments. Production and development for instance.

This wrapper will first look for direct instantiation parameters then OVH_ENDPOINT, OVH_APPLICATION_KEY, OVH_APPLICATION_SECRET and OVH_CONSUMER_KEY environment variables. If either of these parameter is not provided, it will look for a configuration file of the form:

[default]
; general configuration: default endpoint
endpoint=ovh-eu

[ovh-eu]
; configuration specific to 'ovh-eu' endpoint
application_key=my_app_key
application_secret=my_application_secret
consumer_key=my_consumer_key

The client will successively attempt to locate this configuration file in

  1. Current working directory: ./ovh.conf
  2. Current user's home directory ~/.ovh.conf
  3. System wide configuration /etc/ovh.conf

This lookup mechanism makes it easy to overload credentials for a specific project or user.

Example usage:

client = ovh.Client()

Use v1 and v2 API versions

When using OVHcloud APIs (not So you Start or Kimsufi ones), you are given the opportunity to aim for two API versions. For the European API, for example:

Calling client.get, you can target the API version you want:
client = ovh.Client(endpoint="ovh-eu")

# Call to https://eu.api.ovh.com/v1/xdsl/xdsl-yourservice
client.get("/v1/xdsl/xdsl-yourservice")

# Call to https://eu.api.ovh.com/v2/xdsl/xdsl-yourservice
client.get("/v2/xdsl/xdsl-yourservice")

# Legacy call to https://eu.api.ovh.com/1.0/xdsl/xdsl-yourservice
client.get("/xdsl/xdsl-yourservice")

Custom configuration file

You can also specify a custom configuration file. With this method, you won't be able to inherit values from environment.

Example usage:

client = ovh.Client(config_file='/my/config.conf')

Passing parameters

You can call all the methods of the API with the necessary arguments.

If an API needs an argument colliding with a Python reserved keyword, it can be prefixed with an underscore. For example, from argument of POST /email/domain/{domain}/redirection may be replaced by _from.

With characters invalid in python argument name like a dot, you can:

import ovh

params = {}
params['date.from'] = '2014-01-01'
params['date.to'] = '2015-01-01'

# create a client
client = ovh.Client()

# pass parameters using **
client.post('/me/bills', **params)

Advanced usage

Un-authenticated calls

If the user has not authenticated yet (ie, there is no valid Consumer Key), you may force python-ovh to issue the call by passing _need_auth=True to the high level get(), post(), put() and delete() helpers or need_auth=True to the low level method Client.call() and Client.raw_call().

This is needed when calling POST /auth/credential and GET /auth/time which are used internally for authentication and can optionally be done for most of the /order calls.

Access the raw requests response objects

The high level get(), post(), put() and delete() helpers as well as the lower level call() will returned a parsed json response or raise in case of error.

In some rare scenario, advanced setups, you may need to perform customer processing on the raw request response. It may be accessed via raw_call(). This is the lowest level call in python-ovh. See the source for more information.

Hacking

This wrapper uses standard Python tools, so you should feel at home with it. Here is a quick outline of what it may look like. A good practice is to run this from a virtualenv.

Get the sources

git clone https://github.com/ovh/python-ovh.git
cd python-ovh
python setup.py develop

You've developed a new cool feature? Fixed an annoying bug? We'd be happy to hear from you!

Run the tests

Simply run pytest. It will automatically load its configuration from setup.cfg and output full coverage status. Since we all love quality, please note that we do not accept contributions with test coverage under 100%.

pip install -e .[dev]
pytest

Build the documentation

Documentation is managed using the excellent Sphinx system. For example, to build HTML documentation:

cd python-ovh/docs
make html

Supported APIs

OVH Europe

OVH US

OVH North America

So you Start Europe

So you Start North America

Kimsufi Europe

Kimsufi North America

Related links

License

3-Clause BSD

More Repositories

1

cds

Enterprise-Grade Continuous Delivery & DevOps Automation Open Source Platform
Go
4,572
star
2

the-bastion

Authentication, authorization, traceability and auditability for SSH accesses.
Perl
1,514
star
3

utask

Β΅Task is an automation engine that models and executes business processes declared in yaml. βœοΈπŸ“‹
Go
1,197
star
4

venom

🐍 Manage and run your integration tests with efficiency - Venom run executors (script, HTTP Request, web, imap, etc... ) and assertions
Go
1,043
star
5

debian-cis

PCI-DSS compliant Debian 10/11/12 hardening
Shell
731
star
6

celery-director

Simple and rapid framework to build workflows with Celery
Python
535
star
7

svfs

The Swift Virtual File System
Go
374
star
8

php-ovh

Lightweight PHP wrapper for OVH APIs. That's the easiest way to use OVH.com APIs in your PHP applications.
PHP
287
star
9

docs

Official repository containing all docs & guides of OVH Group
HTML
224
star
10

manager

OVHcloud Control Panel
JavaScript
213
star
11

overthebox

OverTheBox - Aggregate and encrypt your multiple internet connections.
Shell
197
star
12

public-cloud-roadmap

Agile roadmap for OVHcloud Public Cloud services. Discover the features our product teams are working on, comment and influence our backlog.
187
star
13

terraform-provider-ovh

Terraform OVH provider
Go
183
star
14

ai-training-examples

Jupyter Notebook
138
star
15

metronome

Metronome is a distributed and fault-tolerant event scheduler
Go
136
star
16

go-ovh

Simple go wrapper for the OVH API
Go
127
star
17

node-ovh

Node.js wrapper for the OVH APIs
JavaScript
125
star
18

symmecrypt

Golang symmetric encryption library
Go
115
star
19

ovh-ttyrec

Enhanced (but compatible) version of the classic ttyrec
C
112
star
20

overthebox-feeds

OverTheBox - LEDE/OpenWrt feed
JavaScript
106
star
21

sv2chisel

(System)Verilog to Chisel translator
Scala
104
star
22

overthebox-openwrt

OverTheBox - OpenWrt fork
C
98
star
23

celery-dyrygent

Celery extension which allows to orchestrate 100/1000/10000 tasks combined into a complex workflow
Python
97
star
24

tat

Tat Engine - Text And Tags
Go
89
star
25

beamium

Prometheus to Warp10 metrics forwarder
Rust
84
star
26

ip-reputation-monitoring

Monitor the reputation of your IP ranges
Python
83
star
27

depc

QoS Measurement & Dependency Graph Platform
Python
80
star
28

configstore

Golang configuration management library
Go
65
star
29

erlenmeyer

Erlenmeyer is a proxy used to parse common Open Source TimeSeries DataBase query endpoints like OpenTSDB, Prometheus/PromQL, InfluxQL or Graphite. Parsed queries are translated into WarpScript to produce native Warp 10 queries.
Go
60
star
30

ovh-ui-kit

OVHcloud UI Kit - Master UI Framework
JavaScript
58
star
31

tsl

TSL is a HTTP proxy which generate WarpScript or a PromQl script based on a TSL query.
Go
56
star
32

noderig

Export OS stats as Sensision Metrics
Go
55
star
33

terraform-ovh-commons

This repo contains commons resources to interact with OVH Public Cloud using Terraform.
HTML
54
star
34

php-ovh-sms

PHP for ovh sms API
PHP
48
star
35

ovh-cli

OVH Command Line Interface
Python
42
star
36

infrastructure-roadmap

Agile roadmap for OVHcloud for Baremetal, Network and Storage IaaS services. Discover the features our product teams are working on, comment and influence our backlog.
38
star
37

the-bastion-ansible-wrapper

Using Ansible through The Bastion
Python
35
star
38

summit2016-RankingPredict

Deprecated, No more maintained - Deprecated, no longer maintained
R
34
star
39

ovh-warp10-datasource

Grafana datasource for Warp10 platform
TypeScript
33
star
40

csharp-ovh

Thin wrapper around OVH's APIs. Handles all the hard work including credential creation and requests signing
C#
28
star
41

order-cart-examples

Example code snippets demonstrating how to use new order with cart on api.ovh.com
PHP
26
star
42

ldp-tail

OVH Logs Data Platform - Tail CLI tooling
Go
25
star
43

design-system

A collection of assets, guidelines and UI components for building consistent user experiences across OVHcloud products.
SCSS
22
star
44

public-cloud-examples

Jupyter Notebook
22
star
45

haproxy-exporter

Export HAProxy stats as Sensision Metrics
Go
21
star
46

fossil

Fossil is a proxy for securing unencrypted Graphite metrics collection
Go
20
star
47

python-apispec-fromfile

APISpec plugin to import OpenAPI specifications from a file
Python
19
star
48

terraform-ovh-publiccloud-network

HCL
19
star
49

tatwebui

Tat Web UI - Text And Tags
JavaScript
19
star
50

java-ovh

Thin wrapper around OVH's APIs. Handles all the hard work including credential creation and requests signing
Java
19
star
51

pulumi-ovh

Pulumi provider for OVHcloud
Java
17
star
52

cerberus-ux

HTML
16
star
53

cerberus-core

Cerberus is a toolkit to receive, parse, process and automate abuse reports handling received by ISP or hosting providers.
Python
15
star
54

public-cloud-databases-examples

OVHcloud Public Cloud Databases Training examples
HCL
14
star
55

lxd-puppet-module

Ruby
14
star
56

osarchiver

OpenStack databases archiver
Python
14
star
57

jerem

Jerem is a golang bot that scrap JIRA project to extract Metrics. Those Metrics can then be send to a Warp 10 Backend.
Go
14
star
58

website-evidence-collector-batch

A tool to launch website-evidence-collector on several URLs or Sitemaps and generate a full report.
JavaScript
13
star
59

distronaut

Find distribution installers all across the web !
Go
13
star
60

rtm

RTM (OVH Real Time Monitoring)
Perl
13
star
61

ovh-ui-kit-bs

A bootstrap theme for the OVH managers, based on ovh-ui-kit
Less
13
star
62

prescience-client

Desktop python client for using OVH Prescience service
Jupyter Notebook
13
star
63

gulp-drupal-stack

OVH Gulp tasks for Drupal themes and modules
JavaScript
12
star
64

serving-runtime

Exposes a serialized machine learning model through a HTTP API.
Java
12
star
65

swift-ovh

This Swift package is a lightweight wrapper for OVH APIs. That's the easiest way to use OVH.com APIs in your Swift applications. Apple platforms supported: iOS, OSX, tvOS, watchOS.
Swift
11
star
66

metronome-ui

User interface for Metronome
JavaScript
11
star
67

private-cloud-roadmap

Agile roadmap for OVHcloud Hosted Private Cloud services. Discover the features our product teams are working on, comment and influence our backlog.
11
star
68

telephony-example-cti-dashboard

Shows signaling events provided by OVH France telephony services CTI
CSS
11
star
69

drucker

Drucker is a lightweight Drupal Developer Environment.
Shell
10
star
70

phishing-mitigation

Tilera-based phishing mitigation layer
JavaScript
10
star
71

lhasa

List and map micro-services-based information system and observe how they interact. Track their activities, then gamify their continuous improvement.
Go
10
star
72

python-logging-gelf

A python logging bundle to send logs using GELF
Python
9
star
73

webpaas-cli

PHP
8
star
74

overthebox-lede

OverTheBox - OpenWRT fork
C
8
star
75

terraform-provider-mimirtool

Terraform provider for Grafana Mimir
Go
8
star
76

owstats-ui

JavaScript
7
star
77

vbridge

X11 cloud desktop software
C
7
star
78

djehouty

Djehouty intends to be a set of logging formatters and handlers to easily send log entries.
Python
7
star
79

crystal-ovh

Lightweight Crystal wrapper around OVH's APIs.
Crystal
7
star
80

ovhdata-cli

Rust
7
star
81

python-warp10client

Python
7
star
82

data-processing-spark-submit

Spark CLI wrapper to run your jobs on OVHcloud Data Processing
Go
7
star
83

docs-rendering

[DEPRECATED] Official rendering engine for static generation of OVH Docs platform
HTML
7
star
84

interpretability-engine

Interpret Machine Learning black-box models deployed on Serving Engine
Python
6
star
85

yubico-piv-checker

Go
6
star
86

webhosting-ssh-bashrc

Shell
6
star
87

puppet-thebastion

Puppet module for Thebastion management.
Ruby
6
star
88

public-cloud-databases-operator

This operator allow you to automaticaly authorize your Kubernetes cluster IP on your OVHcloud cloud databases service.
Go
6
star
89

docs-developer-env

Easy to deploy developer environment, for writing/testing guides & documentations for docs.ovh.com
Shell
6
star
90

tat-contrib

Go
6
star
91

bringyourownlinux

Shell
6
star
92

terraform-ovh-publiccloud-docker-swarm

HCL
5
star
93

terraform-ovh-publiccloud-spark

HCL
5
star
94

summit2016-webhosting-example-rondcoin

PHP
5
star
95

collectd-write-warp10

Python
5
star
96

fiowebviewer

Python
5
star
97

puppet-mimir

Ruby
4
star
98

pingdom-to-graphite

A tool for copying metrics from Pingdom to Graphite.
JavaScript
4
star
99

ovh-winston-ldp

A graylog2 TCP/TLS transport for winston library
JavaScript
4
star
100

okms-sdk-go

The Golang SDK to interact with your OVHcloud KMS services.
Go
4
star