Parse security token with cookie library
@@ -2,7 +2,6 @@ import errno
import httplib
import logging
import os
-import re
import socket
import subprocess
import time
@@ -10,6 +9,11 @@ import urllib
from datetime import timedelta
from xml.etree import ElementTree
+try:
+ from http.cookies import SimpleCookie
+except ImportError:
+ from Cookie import SimpleCookie
+
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPClient
@@ -272,8 +276,7 @@ class MonitOperator(object):
if error.code == httplib.FORBIDDEN:
# Retrieve CSRF token (introduced in Monit 5.20).
response = yield self._async_client.fetch(process_url)
- self._csrf_token = re.search('securitytoken=([a-zA-Z0-9]+);',
- response.headers['Set-Cookie']).group(1)
+ self._csrf_token = self._parse_security_token(response)
if error.code == httplib.NOT_FOUND:
raise ProcessNotFound('{} is not monitored'.format(process_name))
@@ -311,8 +314,7 @@ class MonitOperator(object):
# Retrieve CSRF token (introduced in Monit 5.20).
response = self._client.fetch(process_url)
- self._csrf_token = re.search('securitytoken=([a-zA-Z0-9]+);',
- response.headers['Set-Cookie']).group(1)
+ self._csrf_token = self._parse_security_token(response)
return self.send_command_sync(process_name, command, new_token=True)
if error.code == httplib.NOT_FOUND:
@@ -408,3 +410,15 @@ class MonitOperator(object):
yield gen.sleep(wait_time)
self.last_reload = time.time()
subprocess.check_call(['monit', 'reload'])
+
+ @staticmethod
+ def _parse_security_token(http_response):
+ """ Extracts the security token from an HTTP response.
+
+ Args:
+ A tornado.httpclient.HTTPResponse object.
+ Returns:
+ A string containing the security token.
+ """
+ cookie = SimpleCookie(http_response['Set-Cookie'])
+ return cookie['securitytoken'].value
