Parse Proxmox Web API authentication ticket and the CSRFPreventionToken in Bash

Parse Proxmox Web API authentication ticket and the CSRFPreventionToken in Bash

Category : How-to

Get Social!

The Proxmox Web API can perform any actions available in the front end Web. By implementing a REST API, all commands have been exposed and can be used programatically.

The API is secured using a token based method which provides a ticket that must accompany all API requests except for the request that generates the token. The token is generated from an API call containing a username, password and security realm.

In this example we’ll use Bash to call the Proxmox Web API, authenticate with the root Proxmox user and parse the response for use in later API requests. Note that it’s not good practice to use the root account for API calls due to the security implications.

See this post for an introduction to the Proxmox Web API.

Add this function to the top of your Bash script. This will be used to parse the JSON using standard Bash calls to obtain the information we need.

decodeDataFromJson(){
    echo `echo $1 \
	    | sed 's/{\"data\"\:{//g' \
	    | sed 's/\\\\\//\//g' \
	    | sed 's/[{}]//g' \
            | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' \
	    | sed 's/\"\:\"/\|/g' \
	    | sed 's/[\,]/ /g' \
	    | sed 's/\"// g' \
	    | grep -w $2 \
	    | awk -F "|" '{print $2}'`
}

The next step is to call the Proxmox API using curl to obtain our authentication token. Use the below script and substitute the values as required:

  • PROX_USERNAME is the username and security realm used to log into the Proxmox Web front end. This must be a valid user with the required permission to make the calls you need.
  • PROX_PASSWORD is the password for the above user. You must escape any special characters as usual in Bash.
  • HOST is the host or IP address of the Proxmox server.
PROX_USERNAME=root@pam
PROX_PASSWORD=PASSWORD
HOST=proxmox-host

DATA=`curl -s -k -d "username=$PROX_USERNAME&password=$PROX_PASSWORD" $HOST/api2/json/access/ticket` 
TICKET=$(decodeDataFromJson $DATA 'ticket')
CSRF=$(decodeDataFromJson $DATA 'CSRFPreventionToken')

And that’s all there is to it! You can use the variables $TICKET and $CSRF in later requests. Keep in mind that a valid ticket is only valid for 2 hours, after that you’ll need to create a new one.


2 Comments

Dotux

20-Oct-2017 at 6:45 pm

Hello,

You can used the binary “jq” to parse json return.
It’s very simple ;-)

Leave a Reply

Visit our advertisers

Quick Poll

How often do you change the password for the computer(s) you use?

Visit our advertisers