Skip to content

antony@notes:~/ops-automation$ cat "rest-api.sh.md"

rest-api.sh

2022-08-27· ops-automation ·Shell Script

rest-api.sh program

#!/bin/bash

#set -x # debug mode

# var
script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd -P)

# function
usage() {
  cat <<EOF
Usage:
  $(basename "${BASH_SOURCE[0]}") [options]

Available options:

test      test config
create    create from mapping.list
delete    delete from mapping.list
EOF
  exit
}

get_token() {
  token=$(curl -s --location --request POST "${GUACAMOLESERVER}/api/tokens" \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode "username=${GUACADMIN}" \
    --data-urlencode "password=${GUACPASS}" | jq -r '.authToken')
  [ "${token}" == "null" ] && echo 'Get token fail, Please check config' && exit 1
}

get_connection_groupID() {
  groups=$(curl -s --location --request GET "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/connectionGroups?token=${token}")
  groupIndex=$(echo "${groups}" | jq -r .[].identifier)
  for num in ${groupIndex}; do
    echo "${groups}" | jq -r ".\"${num}\".name" | grep "${connGroup}" &>/dev/null &&
      connGroupID=$(echo "${groups}" | jq -r ".\"${num}\".identifier")
  done
}

get_connection_nameid() {
  conns=$(curl -s --location --request GET "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/connections?token=${token}")
  connsIndex=$(echo "${conns}" | jq -r .[].identifier)
  for num in ${connsIndex}; do
    echo "${conns}" | jq -r ".\"${num}\".name" | grep "${connName}" &>/dev/null &&
      connNameID=$(echo "${conns}" | jq -r ".\"${num}\".identifier")
  done
}

check_connection_service() {
  if ! nmap -Pn -p "${connPort}" "${connIP}" | grep 'open' &>/dev/null; then
    connName="${connName}.X"
  fi
}

create_user() {
  curl -s -w '\n' --location --request POST "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/users?token=${token}" \
    --header 'Content-Type: application/json' \
    --data-raw "{
      \"username\": \"${userAccount}\",
      \"password\": \"${userPassword}\",
      \"attributes\": {}
    }"
}

create_connection_group() {
  curl -s -w '\n' --location --request POST "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/connectionGroups?token=${token}" \
    --header 'Content-Type: application/json' \
    --data-raw "{
      \"name\": \"${connGroup}\",
      \"type\": \"ORGANIZATIONAL\",
      \"attributes\": {
        \"max-connections\": \"\",
        \"max-connections-per-user\": \"\",
        \"enable-session-affinity\": \"\"
      }
    }"
}

create_connection_rdp() {
  curl -s -w '\n' --location --request POST "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/connections?token=${token}" \
    --header 'Content-Type: application/json' \
    --data-raw "{
      \"parentIdentifier\": \"${connGroupID}\",
      \"name\": \"${connName}\",
      \"protocol\": \"rdp\",
      \"parameters\": {
        \"hostname\": \"${connIP}\",
        \"port\": \"${connPort}\",
        \"username\": \"${connAccount}\",
        \"password\": \"${connPassword}\",
        \"security\": \"nla\",
        \"ignore-cert\": \"true\"
      },
      \"attributes\": {
        \"max-connections\": \"\",
        \"max-connections-per-user\": \"\"
      }
    }"
}

create_connection_ssh() {
  curl -s -w '\n' --location --request POST "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/connections?token=${token}" \
    --header 'Content-Type: application/json' \
    --data-raw "{
      \"parentIdentifier\": \"${connGroupID}\",
      \"name\": \"${connName}\",
      \"protocol\": \"ssh\",
      \"parameters\": {
        \"hostname\": \"${connIP}\",
        \"port\": \"${connPort}\",
        \"username\": \"${connAccount}\",
        \"password\": \"${connPassword}\",
        \"color-scheme\": \"black-white\",
        \"font-size\": \"14\"
      },
      \"attributes\": {
        \"max-connections\": \"\",
        \"max-connections-per-user\": \"\"
      }
    }"
}

create_connection_sharingprofile() {
  curl -s -w '\n' --location --request POST "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/sharingProfiles?token=${token}" \
    --header 'Content-Type: application/json' \
    --data-raw "{
      \"primaryConnectionIdentifier\": \"${connNameID}\",
      \"name\": \"ro\",
      \"parameters\": {
        \"read-only\": \"true\"
      },
      \"attributes\": {}
    }"
  curl -s -w '\n' --location --request POST "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/sharingProfiles?token=${token}" \
    --header 'Content-Type: application/json' \
    --data-raw "{
      \"primaryConnectionIdentifier\": \"${connNameID}\",
      \"name\": \"rw\",
      \"parameters\": {
        \"read-only\": \"\"
      },
      \"attributes\": {}
    }"
}

assign_user_connections() {
  curl -s --location --request PATCH "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/users/${userAccount}/permissions?token=${token}" \
    --header 'Content-Type: application/json' \
    --data-raw "[
      {
          \"op\": \"add\",
          \"path\": \"/connectionGroupPermissions/${connGroupID}\",
          \"value\": \"READ\"
      },
      {
          \"op\": \"add\",
          \"path\": \"/connectionPermissions/${connNameID}\",
          \"value\": \"READ\"
      }
    ]"
}

delete_user() {
  curl -s --location --request DELETE "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/users/${userAccount}?token=${token}"
}

delete_connection_group() {
  curl -s --location --request DELETE "${GUACAMOLESERVER}/api/session/data/${DATASOURCE}/connectionGroups/${connGroupID}?token=${token}"
}

if [ "${1-}" == "" ]; then
  usage && exit 1
fi

packages='jq nmap'
for package in ${packages}; do
  if ! command -v "${package}" &>/dev/null; then
    echo "Ops, ${package} is not installed." && exit 1
  fi
done

source "${script_dir}"/rest-api.conf
get_token
if [ "${1-}" == "test" ]; then
  echo "Token: ${token}" && exit 0
fi

while read -r line; do
  echo "${line}" | grep '^#' &>/dev/null &&
    continue
  echo ${line} | grep '^$' &>/dev/null &&
    continue
  userAccount=$(echo "${line}" | awk -F',' '{print $1}')
  userPassword=$(echo "${line}" | awk -F',' '{print $2}')
  connGroup=$(echo "${line}" | awk -F',' '{print $3}')
  connName=$(echo "${line}" | awk -F',' '{print $4}')
  connProtocol=$(echo "${line}" | awk -F',' '{print $5}')
  connIP=$(echo "${line}" | awk -F',' '{print $6}')
  connPort=$(echo "${line}" | awk -F',' '{print $7}')
  connAccount=$(echo "${line}" | awk -F',' '{print $8}')
  connPassword=$(echo "${line}" | awk -F',' '{print $9}')

  if [ "${1-}" == "create" ]; then
    # create user set password
    if [ "${userPassword}" == "" ]; then
      tempPassword=$(date +%S%N | md5sum)
      userPassword=${tempPassword:0:PASSLENGTH}
    fi
    if ! create_user | grep 'already exists' &>/dev/null; then
      echo "${userAccount}","${userPassword}" >>"${script_dir}"/random.csv
      echo "Create userAccount ${userAccount} ok"
    fi
    create_connection_group &>/dev/null
    get_connection_groupID

    # create connection
    check_connection_service
    [ "${connProtocol}" == "rdp" ] && create_connection_rdp &>/dev/null && echo "Create connName ${connName} ok"
    [ "${connProtocol}" == "ssh" ] && create_connection_ssh &>/dev/null && echo "Create connName ${connName} ok"

    # have connection get id
    get_connection_nameid
    create_connection_sharingprofile &>/dev/null
    assign_user_connections
  fi

  if [ "${1-}" == "delete" ]; then
    delete_user &>/dev/null
    get_connection_groupID
    delete_connection_group &>/dev/null
    rm -r "${script_dir}"/random.csv &>/dev/null
  fi
done <"${script_dir}"/mapping.list