Ubuntu 环境需求安装jq环境,用于解析JSON数据。

apt-get install jq
#!/bin/bash
 
# Zabbix server URL
ZABBIX_URL="http://10.18.10.x/api_jsonrpc.php" #nginx
#ZABBIX_URL="http://10.18.10.x/api_jsonrpc.php" #apache
# Zabbix API 用户名和密码
ZABBIX_USER="Admin"
ZABBIX_PASS="xxxxxx"
 
# 获取 Zabbix API token
RESPONSE=$(curl -s -X POST -H 'Content-Type: application/json-rpc' \
-d '{
    "jsonrpc": "2.0",
    "method": "user.login",
    "params": {
        "username": "'"$ZABBIX_USER"'",
        "password": "'"$ZABBIX_PASS"'"
    },
    "id": 1,
    "auth": null
}' $ZABBIX_URL)
 
AUTH_TOKEN=$(echo $RESPONSE | jq -r '.result')
ERROR_MSG=$(echo $RESPONSE | jq -r '.error.data')
 
# 检查是否成功获取 token
if [ "$AUTH_TOKEN" == "null" ] || [ -z "$AUTH_TOKEN" ]; then
    echo "Failed to get auth token. Error: $ERROR_MSG"
    exit 1
fi
 
echo "Auth token: $AUTH_TOKEN"
 
# 获取主机列表
HOSTS=$(curl -s -X POST -H 'Content-Type: application/json-rpc' \
-d '{
    "jsonrpc": "2.0",
    "method": "host.get",
    "params": {
        "output": ["hostid", "host"]
    },
    "id": 2,
    "auth": "'"$AUTH_TOKEN"'"
}' $ZABBIX_URL | jq -r '.result[] | "\(.hostid) \(.host)"')
 
# 检查是否成功获取主机列表
if [ -z "$HOSTS" ]; then
    echo "Failed to get hosts."
    exit 1
fi
 
echo "Hosts:"
echo "$HOSTS"
 
# 注销用户
curl -s -X POST -H 'Content-Type: application/json-rpc' \
-d '{
    "jsonrpc": "2.0",
    "method": "user.logout",
    "params": [],
    "id": 3,
    "auth": "'"$AUTH_TOKEN"'"
}' $ZABBIX_URL > /dev/null
 
echo "Logged out."

运行脚本

./zabbix-api