Python调用OpenStack API

返回目录

Python调用OpenStack API

获取token值(除了身份认证,还可以用 openstack token issue + awk 命令得到,或直接写死【1小时生效】)

import json
import requests

headers = {"Content-Type": "application/json"}

body = {
    "auth": {
        "identity": {
            "methods": ["password"],
            "password": {
                "user": {
                    "domain": {
                        "name": "demo"
                    },
                    "name": "admin",
                    "password": "000000"
                }
            }
        },
        "scope": {
            "project": {
                "domain": {
                    "name": "demo"
                },
                "name": "admin"
            }
        }
    }
}

headers["X-Auth-Token"] = requests.post('http://192.168.100.10:5000/v3/auth/tokens', headers=headers, json=body).headers["X-Subject-Token"]
import os
headers["X-Auth-Token"] = os.popen("source /etc/keystone/admin-openrc.sh && openstack token issue | awk '/ id/{print $4}'").read().strip('\n')
headers["X-Auth-Token"] = os.popen("source /etc/keystone/admin-openrc.sh && openstack token issue | sed -n '/ id/s/|.*| //p'").read().strip('\n')

调用PythonAPI创建flavor

data = {
    'flavor': {
        'name': 'test_flavor',
        'id': '666',
        'ram': 2048,
        'disk': 20,
        'vcpus': 2
    }
}
print(json.dumps(requests.post('http://192.168.100.10:8774/v2.1/flavors', headers=headers, json=data).json(), indent=4))
print('云主机类型创建成功')

调用PythonAPI创建镜像

data = {
    "container_format": "bare",
    "disk_format": "qcow2",
    "name": "cirros",
    "visibility": "public"
}
request = requests.post('http://192.168.100.10:9292/v2/images', headers=headers, json=data).json()
headers["Content-Type"] = "application/octet-stream"
print(requests.put(f"http://192.168.100.10:9292{request['file']}", headers=headers, data=open("cirros-0.3.4-x86_64-disk.img", 'rb')).status_code)
print('云主机镜像上传成功')
上一篇:MySQL中常用的时间操作


下一篇:18、猿人学第三题:访问逻辑 - 推心置腹【Post/Js逆向笔记】