使用 Foreman 的 API 更新主机的 Python 脚本

标签 python curl httprequest kerberos theforeman

我想用 Python 编写一个脚本,给定主机和主机组这两个参数,使用 Foreman API ( http://theforeman.org/api/apidoc/v1/hosts/update.html) 更改主机的主机组。

执行此操作的 cURL 命令如下(有效!):

curl -s -H "Accept:application/json" -X PUT --insecure --negotiate -u : -d "host[hostgroup_id]=ZZZZZ" https://foreman.mydomain.com:443/api/hosts/XXXX

但是现在,我想使用 Python 脚本来完成它。

我使用 Python request 库没有问题,直到我到达必须传递参数的部分。

我正在关注此信息 http://docs.python-requests.org/en/latest/user/quickstart/#passing-parameters-in-urls但显然这不起作用,因为这不是 Foreman 的 API 期望接收参数的方式。

那么,有什么想法可以让我以 Foreman 可以理解的方式传递参数吗?

在此先感谢任何帮助!

最佳答案

抱歉,我找到了方法,但我忘记发布了。 下一个代码可以解决这个问题:

def updateHost(host_id, new_hostgroup_id):
    url = "https://foreman.mydomain.com:443/api/hosts/" + host_id
    payload = {'host[hostgroup_id]': new_hostgroup_id}
    headers = {'Accept': 'application/json'}
    r = requests.put(url, data=payload, headers=headers, verify=False, uth=HTTPKerberosAuth())
    if (r.status_code != requests.codes.ok):
        raise BadStatusCodeRequest("HTTP Request status code error: " + r.raise_for_status())

关于使用 Foreman 的 API 更新主机的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24763665/

相关文章:

python - 使交互式 matplotlib 窗口不会在每次更新时弹出到前面(Windows 7)

php - Docker php curl 连接被拒绝

java - 读取 HTTP 请求参数时将垃圾字符添加到字符串

javascript - 使用 AngularJS 发送 HTTP header 请求

java - 如何编写用于文件上传的 MVC Web Api Post 方法

python - SCIPY 线性规划方案中缩放矩阵变量的最佳方法

python - 如何在 Docker 中运行flask_migrate

python - 使用 tf.data.Dataset 使保存的模型更大

php - 使用 Guzzle/Goutte 时限制请求大小

javascript - 将 curl 命令转换为 JavaScript