コード例 #1
0
def login_activate(module, credential_0, credential_1):
    set_cookie = ""
    resp = ""
    url = "https://activate.arubanetworks.com/LOGIN"
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': 'Activate-cookie.text'
    }
    data = {"credential_0": credential_0, "credential_1": credential_1}
    cookies = cookiejar.LWPCookieJar()
    validate_certs = module.params.get('validate_certs')
    try:
        resp = open_url(url=url,
                        data=urlencode(data),
                        headers=headers,
                        method="POST",
                        validate_certs=validate_certs,
                        cookies=cookies)
        if resp.code == 200:
            cookie_list = []
            for ck in cookies:
                cookie_list.append(str(ck.name) + "=" + str(ck.value))
            set_cookie = "; ".join(cookie_list)
        else:
            module.fail_json(changed=False,
                             msg="Login Failed!",
                             reason=resp.read(),
                             response="HTTP status_code: " + str(resp.code))
    except Exception as e:
        module.fail_json(changed=False,
                         msg="API Call failed! Exception during login",
                         reason=str(e))
    return set_cookie
コード例 #2
0
def login_api_mm(module):
    # Define variables from module arguments
    username = module.params.get('username')
    password = module.params.get('password')
    host = module.params.get('host')
    session_key = ""
    resp = ""
    # Variables required for open_url
    url = "https://" + str(host) + ":4343/v1/api/login"
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    data = urlencode({'username': username, 'password': password})
    cookies = cookiejar.LWPCookieJar()
    validate_certs = False
    http_agent = 'ansible-httpget'
    follow_redirects = 'urllib2'
    method = "POST"
    # Store the url to module, so we can print the details in case of error
    module.api_call = {
        'host': host,
        'username': username,
        'password': password,
        'url': ''
    }
    module.api_call['url'] = url

    try:
        resp = open_url(url,
                        data=data,
                        headers=headers,
                        method=method,
                        validate_certs=validate_certs,
                        http_agent=http_agent,
                        follow_redirects=follow_redirects,
                        cookies=cookies)
        resp = resp.read()
        result = json.loads(resp)['_global_result']
        if result['status'] == "0":
            session_key = result['UIDARUBA']
        else:
            module.fail_json(
                changed=False,
                msg="Login Failed! Recheck the credentials you provided",
                reason=str(result['status_str']),
                api_call=module.api_call,
                response="content: " + str(resp) + " login status code: " +
                str(result['status']) + " login error: " +
                str(result['status_str']))
    except Exception as e:
        module.fail_json(changed=False,
                         msg="API Call failed! Exception during login",
                         reason=str(e),
                         api_call=module.api_call)

    session_dict = {'host': host, 'session_token': session_key}
    return session_dict
コード例 #3
0
def main():

    module = AnsibleModule(argument_spec=dict(
        script=dict(required=True, type="str"),
        url=dict(required=False, type="str", default="http://localhost:8080"),
        validate_certs=dict(required=False, type="bool", default=True),
        user=dict(required=False, type="str", default=None),
        password=dict(required=False, no_log=True, type="str", default=None),
        timeout=dict(required=False, type="int", default=10),
        args=dict(required=False, type="dict", default=None)))

    if module.params['user'] is not None:
        if module.params['password'] is None:
            module.fail_json(msg="password required when user provided",
                             output='')
        module.params['url_username'] = module.params['user']
        module.params['url_password'] = module.params['password']
        module.params['force_basic_auth'] = True

    if module.params['args'] is not None:
        from string import Template
        try:
            script_contents = Template(module.params['script']).substitute(
                module.params['args'])
        except KeyError as err:
            module.fail_json(msg="Error with templating variable: %s" % err,
                             output='')
    else:
        script_contents = module.params['script']

    headers = {}
    cookies = None
    if is_csrf_protection_enabled(module):
        cookies = cookiejar.LWPCookieJar()
        crumb = get_crumb(module, cookies)
        headers = {crumb['crumbRequestField']: crumb['crumb']}

    resp, info = fetch_url(module,
                           module.params['url'] + "/scriptText",
                           data=urlencode({'script': script_contents}),
                           headers=headers,
                           method="POST",
                           timeout=module.params['timeout'],
                           cookies=cookies)

    if info["status"] != 200:
        module.fail_json(msg="HTTP error " + str(info["status"]) + " " +
                         info["msg"],
                         output='')

    result = to_native(resp.read())

    if 'Exception:' in result and 'at java.lang.Thread' in result:
        module.fail_json(msg="script failed with stacktrace:\n " + result,
                         output='')

    module.exit_json(output=result, )
コード例 #4
0
def mm_api_call(module, session):
    host = module.params.get('host', session['host'])
    username = module.params.get('username')
    password = module.params.get('password')
    method = module.params.get('method')
    api_type = module.params.get('api_type')
    api_name = module.params.get('api_name')
    iap_ip_addr = module.params.get('iap_ip_addr')
    config_path = module.params.get('config_path')
    data = module.params.get('data')
    cookies = cookiejar.LWPCookieJar()
    resp = ""
    validate_certs = False
    http_agent = 'ansible-httpget'
    follow_redirects = 'urllib2'
    session_token = session['session_token']
    if not host:
        host = session['host']
    module.api_call = {'host':host,'username':username,'password':password,'api_name':api_name,'method':method,'config_path':config_path,'data':data, 'url':''}

    # Create the URL for the REST API call

    if api_type == 'action' or api_type == 'configuration':
        if method == 'POST':
            url = "https://" + str(host) + ":4343/rest/" + str(api_name) + "?sid=" + str(session_token)
            module.api_call['url'] = url # Store the url to module, so we can print the details in case of error
        else:#method is GET
            module.fail_json(changed=False, failed=True, msg="Action APIs and Configuartion APIs should have 'POST' as the method, since they are only used to add new data, modify or delete existing data")

    elif api_type == 'monitoring':
        if method == 'GET':
            api_name = api_name.replace(" ","%20")
            url = "https://" + str(host) + ":4343/rest/show-cmd?iap_ip_addr=" +str(iap_ip_addr) + "&cmd=" + str(api_name) + "&sid=" + str(session_token)
            module.api_call['url'] = url # Store the url to module, so we can print the details in case of error

        else:#method is POST
            module.fail_json(changed=False, failed=True, msg="Monitoring APIs or show commands should have 'GET' as the method.")


    try:
        headers = {'Accept': 'application/json', 'Content-Type': 'application/json', 'Cookie': 'SESSION=' + str(session_token)}
        # Data has to be json formatted
        data = json.dumps(data) #converts python object to json string that is readable by Ansible
        resp =  open_url(url, data = data, headers=headers, method=method, validate_certs=validate_certs, http_agent=http_agent, follow_redirects=follow_redirects, cookies=cookies)
        result = json.loads(resp.read())

        if result['Status'] == 'Success':
            module.exit_json(changed=True, msg=str(result), status_code=int(resp.code))
        else:
            module.fail_json(changed=False, msg="API Call failed!", reason=result['status_str'], api_call=module.api_call)

    except Exception as e:
        module.fail_json(changed=False, msg="API Call failed! Exception during api call",
                         reason=str(e), api_call=module.api_call)
コード例 #5
0
def amp_api_call(module,
                 x_biscotti,
                 set_cookie,
                 host,
                 api_name,
                 method='GET',
                 data={},
                 params=None):
    url = "https://" + str(host) + "/" + str(api_name)
    cookies = cookiejar.LWPCookieJar()
    validate_certs = module.params.get('validate_certs')
    client_cert = module.params.get('client_cert')
    client_key = module.params.get('client_key')
    http_agent = 'ansible-httpget'
    follow_redirects = 'urllib'
    try:
        if method == "GET":
            if params:
                params = urlencode(params)
                url = url + "?" + params
            headers = {
                'Cookie': 'MercuryAuthHandlerCookie_AMPAuth=' + set_cookie
            }
            resp = open_url(url,
                            headers=headers,
                            validate_certs=validate_certs)

        else:  # POST
            headers = {
                'Cookie': 'MercuryAuthHandlerCookie_AMPAuth=' + set_cookie,
                'X-BISCOTTI': x_biscotti
            }
            resp = open_url(url,
                            headers=headers,
                            method=method,
                            validate_certs=validate_certs,
                            data=data,
                            client_cert=client_cert,
                            client_key=client_key)

    except Exception as e:
        module.fail_json(changed=False,
                         msg="API Call failed! Exception during api call",
                         reason=str(e))
    return resp
コード例 #6
0
def login_amp(module, host, credential_0, credential_1):
    return_list = []
    resp = ""
    url = "https://" + str(host) + "/LOGIN"
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    data = 'credential_0=' + credential_0 + '&credential_1=' + credential_1 + '&destination=/&login=Log In'
    cookies = cookiejar.LWPCookieJar()
    validate_certs = module.params.get('validate_certs')
    client_cert = module.params.get('client_cert')
    client_key = module.params.get('client_key')
    try:

        resp = open_url(url,
                        headers=headers,
                        method="POST",
                        validate_certs=validate_certs,
                        data=data,
                        cookies=cookies,
                        client_cert=client_cert,
                        client_key=client_key)
        if resp.code == 200:
            ## Extract Biscotti from headers
            if "X-BISCOTTI" in resp.headers:
                x_biscotti = resp.headers.get("X-BISCOTTI")
                return_list.append(x_biscotti)
            ## Extract session key from cookie
            for set_cookie in cookies:
                set_cookie = set_cookie.value
                return_list.append(set_cookie)

        else:
            module.fail_json(changed=False,
                             msg="Login Failed!",
                             reason=resp.text,
                             response="HTTP status_code: " +
                             str(resp.status_code))
    except Exception as e:
        module.fail_json(changed=False,
                         msg="API Call failed! Exception during login",
                         reason=str(e))
    return return_list
コード例 #7
0
    def __init__(self, module):
        # To be able to call fail_json
        self.module = module

        # Shortcuts for the params
        self.params = self.module.params
        self.url = self.params['url']
        self.timeout = self.params['timeout']

        # Crumb
        self.crumb = {}
        # Cookie jar for crumb session
        self.cookies = None

        if self._csrf_enabled():
            self.cookies = cookiejar.LWPCookieJar()
            self.crumb = self._get_crumb()

        # Get list of installed plugins
        self._get_installed_plugins()
コード例 #8
0
def fetch_url(module,
              url,
              data=None,
              headers=None,
              method=None,
              use_proxy=True,
              force=False,
              last_mod_time=None,
              timeout=10):
    """Sends a request via HTTP(S) or FTP (needs the module as parameter)

    :arg module: The AnsibleModule (used to get username, password etc. (s.b.).
    :arg url:             The url to use.

    :kwarg data:          The data to be sent (in case of POST/PUT).
    :kwarg headers:       A dict with the request headers.
    :kwarg method:        "POST", "PUT", etc.
    :kwarg boolean use_proxy:     Default: True
    :kwarg boolean force: If True: Do not get a cached copy (Default: False)
    :kwarg last_mod_time: Default: None
    :kwarg int timeout:   Default: 10

    :returns: A tuple of (**response**, **info**). Use ``response.body()`` to read the data.
        The **info** contains the 'status' and other meta data. When a HttpError (status > 400)
        occurred then ``info['body']`` contains the error response data::

    Example::

        data={...}
        resp, info = fetch_url(module,
                               "http://example.com",
                               data=module.jsonify(data)
                               header={Content-type': 'application/json'},
                               method="POST")
        status_code = info["status"]
        body = resp.read()
        if status_code >= 400 :
            body = info['body']
    """

    if not HAS_URLPARSE:
        module.fail_json(msg='urlparse is not installed')

    # Get validate_certs from the module params
    validate_certs = module.params.get('validate_certs', True)

    username = module.params.get('url_username', '')
    password = module.params.get('url_password', '')
    http_agent = module.params.get('http_agent', 'ansible-httpget')
    force_basic_auth = module.params.get('force_basic_auth', '')

    follow_redirects = module.params.get('follow_redirects', 'urllib2')

    client_cert = module.params.get('client_cert')
    client_key = module.params.get('client_key')

    cookies = cookiejar.LWPCookieJar()

    r = None
    info = dict(url=url)
    try:
        r = open_url(url,
                     data=data,
                     headers=headers,
                     method=method,
                     use_proxy=use_proxy,
                     force=force,
                     last_mod_time=last_mod_time,
                     timeout=timeout,
                     validate_certs=validate_certs,
                     url_username=username,
                     url_password=password,
                     http_agent=http_agent,
                     force_basic_auth=force_basic_auth,
                     follow_redirects=follow_redirects,
                     client_cert=client_cert,
                     client_key=client_key,
                     cookies=cookies)
        info.update(r.info())
        # parse the cookies into a nice dictionary
        cookie_dict = dict()
        for cookie in cookies:
            cookie_dict[cookie.name] = cookie.value
        info['cookies'] = cookie_dict
        # finally update the result with a message about the fetch
        info.update(
            dict(msg="OK (%s bytes)" %
                 r.headers.get('Content-Length', 'unknown'),
                 url=r.geturl(),
                 status=r.code))
    except NoSSLError as e:
        distribution = get_distribution()
        if distribution is not None and distribution.lower() == 'redhat':
            module.fail_json(
                msg='%s. You can also install python-ssl from EPEL' %
                to_native(e))
        else:
            module.fail_json(msg='%s' % to_native(e))
    except (ConnectionError, ValueError) as e:
        module.fail_json(msg=to_native(e))
    except urllib_error.HTTPError as e:
        try:
            body = e.read()
        except AttributeError:
            body = ''

        # Try to add exception info to the output but don't fail if we can't
        try:
            info.update(dict(**e.info()))
        except:
            pass

        info.update({'msg': to_native(e), 'body': body, 'status': e.code})

    except urllib_error.URLError as e:
        code = int(getattr(e, 'code', -1))
        info.update(dict(msg="Request failed: %s" % to_native(e), status=code))
    except socket.error as e:
        info.update(
            dict(msg="Connection failure: %s" % to_native(e), status=-1))
    except Exception as e:
        info.update(dict(msg="An unknown error occurred: %s" % to_native(e),
                         status=-1),
                    exception=traceback.format_exc())

    return r, info
コード例 #9
0
def fetch_url(module,
              url,
              data=None,
              headers=None,
              method=None,
              use_proxy=True,
              force=False,
              last_mod_time=None,
              timeout=10):
    """Sends a request via HTTP(S) or FTP (needs the module as parameter)

    :arg module: The AnsibleModule (used to get username, password etc. (s.b.).
    :arg url:             The url to use.

    :kwarg data:          The data to be sent (in case of POST/PUT).
    :kwarg headers:       A dict with the request headers.
    :kwarg method:        "POST", "PUT", etc.
    :kwarg boolean use_proxy:     Default: True
    :kwarg boolean force: If True: Do not get a cached copy (Default: False)
    :kwarg last_mod_time: Default: None
    :kwarg int timeout:   Default: 10

    :returns: A tuple of (**response**, **info**). Use ``response.read()`` to read the data.
        The **info** contains the 'status' and other meta data. When a HttpError (status > 400)
        occurred then ``info['body']`` contains the error response data::

    Example::

        data={...}
        resp, info = fetch_url(module,
                               "http://example.com",
                               data=module.jsonify(data)
                               header={'Content-type': 'application/json'},
                               method="POST")
        status_code = info["status"]
        body = resp.read()
        if status_code >= 400 :
            body = info['body']
    """

    if not HAS_URLPARSE:
        module.fail_json(msg='urlparse is not installed')

    # ensure we use proper tempdir
    old_tempdir = tempfile.tempdir
    tempfile.tempdir = module.tmpdir

    # Get validate_certs from the module params
    validate_certs = module.params.get('validate_certs', True)

    username = module.params.get('url_username', '')
    password = module.params.get('url_password', '')
    http_agent = module.params.get('http_agent', 'ansible-httpget')
    force_basic_auth = module.params.get('force_basic_auth', '')

    follow_redirects = module.params.get('follow_redirects', 'urllib2')

    client_cert = module.params.get('client_cert')
    client_key = module.params.get('client_key')

    cookies = cookiejar.LWPCookieJar()

    r = None
    info = dict(url=url)
    try:
        r = open_url(url,
                     data=data,
                     headers=headers,
                     method=method,
                     use_proxy=use_proxy,
                     force=force,
                     last_mod_time=last_mod_time,
                     timeout=timeout,
                     validate_certs=validate_certs,
                     url_username=username,
                     url_password=password,
                     http_agent=http_agent,
                     force_basic_auth=force_basic_auth,
                     follow_redirects=follow_redirects,
                     client_cert=client_cert,
                     client_key=client_key,
                     cookies=cookies)
        # Lowercase keys, to conform to py2 behavior, so that py3 and py2 are predictable
        info.update(dict((k.lower(), v) for k, v in r.info().items()))

        # Don't be lossy, append header values for duplicate headers
        # In Py2 there is nothing that needs done, py2 does this for us
        if PY3:
            temp_headers = {}
            for name, value in r.headers.items():
                # The same as above, lower case keys to match py2 behavior, and create more consistent results
                name = name.lower()
                if name in temp_headers:
                    temp_headers[name] = ', '.join((temp_headers[name], value))
                else:
                    temp_headers[name] = value
            info.update(temp_headers)

        # parse the cookies into a nice dictionary
        cookie_list = []
        cookie_dict = dict()
        # Python sorts cookies in order of most specific (ie. longest) path first. See ``CookieJar._cookie_attrs``
        # Cookies with the same path are reversed from response order.
        # This code makes no assumptions about that, and accepts the order given by python
        for cookie in cookies:
            cookie_dict[cookie.name] = cookie.value
            cookie_list.append((cookie.name, cookie.value))
        info['cookies_string'] = '; '.join('%s=%s' % c for c in cookie_list)

        info['cookies'] = cookie_dict
        # finally update the result with a message about the fetch
        info.update(
            dict(msg="OK (%s bytes)" %
                 r.headers.get('Content-Length', 'unknown'),
                 url=r.geturl(),
                 status=r.code))
    except NoSSLError as e:
        distribution = get_distribution()
        if distribution is not None and distribution.lower() == 'redhat':
            module.fail_json(
                msg='%s. You can also install python-ssl from EPEL' %
                to_native(e))
        else:
            module.fail_json(msg='%s' % to_native(e))
    except (ConnectionError, ValueError) as e:
        module.fail_json(msg=to_native(e))
    except urllib_error.HTTPError as e:
        try:
            body = e.read()
        except AttributeError:
            body = ''

        # Try to add exception info to the output but don't fail if we can't
        try:
            info.update(dict(**e.info()))
        except:
            pass

        info.update({'msg': to_native(e), 'body': body, 'status': e.code})

    except urllib_error.URLError as e:
        code = int(getattr(e, 'code', -1))
        info.update(dict(msg="Request failed: %s" % to_native(e), status=code))
    except socket.error as e:
        info.update(
            dict(msg="Connection failure: %s" % to_native(e), status=-1))
    except httplib.BadStatusLine as e:
        info.update(
            dict(
                msg=
                "Connection failure: connection was closed before a valid response was received: %s"
                % to_native(e.line),
                status=-1))
    except Exception as e:
        info.update(dict(msg="An unknown error occurred: %s" % to_native(e),
                         status=-1),
                    exception=traceback.format_exc())
    finally:
        tempfile.tempdir = old_tempdir

    return r, info
コード例 #10
0
def mm_api_call(module, session):
    host = module.params.get('host', session['host'])
    username = module.params.get('username')
    password = module.params.get('password')
    #session_token =  module.params.get('session_token')
    method = module.params.get('method')
    api_name = module.params.get('api_name')
    config_path = module.params.get('config_path')
    data = module.params.get('data')
    cookies = cookiejar.LWPCookieJar()
    resp = ""
    validate_certs = False
    http_agent = 'ansible-httpget'
    follow_redirects = 'urllib2'
    session_token = session['session_token']
    if not host:
        host = session['host']
    module.api_call = {
        'host': host,
        'username': username,
        'password': password,
        'api_name': api_name,
        'method': method,
        'config_path': config_path,
        'data': data,
        'url': ''
    }

    # Create the URL for the REST API call
    if config_path != None and config_path != "" and config_path != "null":
        url = "https://" + str(host) + ":4343/v1/configuration/object/" + str(
            api_name) + "?config_path=" + str(
                config_path) + "&UIDARUBA=" + str(session_token)
    else:
        url = "https://" + str(host) + ":4343/v1/configuration/object/" + str(
            api_name) + "?UIDARUBA=" + str(session_token)

    # Store the url to module, so we can print the details in case of error
    module.api_call['url'] = url

    try:
        # Data has to be json formatted
        if method == "GET":
            headers = {
                'Accept': 'application/json',
                'Cookie': 'SESSION=' + str(session_token)
            }
            if api_name == "showcommand":
                params = {
                    "command": data["command"],
                    "UIDARUBA": str(session_token)
                }
                url = "https://" + str(host) + ":4343/v1/configuration/" + str(
                    api_name) + "?" + urlencode(params)
            resp = open_url(url,
                            headers=headers,
                            method=method,
                            validate_certs=validate_certs,
                            http_agent=http_agent,
                            follow_redirects=follow_redirects,
                            cookies=cookies)
        else:  # method is POST
            headers = {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Cookie': 'SESSION=' + str(session_token)
            }

            data = json.dumps(
                data
            )  #converts python object to json string that is readable by Ansible

            resp = open_url(url,
                            data=data,
                            headers=headers,
                            method=method,
                            validate_certs=validate_certs,
                            http_agent=http_agent,
                            follow_redirects=follow_redirects,
                            cookies=cookies)

        result = json.loads(resp.read())

        if method == "POST":
            result = result['_global_result']
            if result['status'] == 0:
                module.exit_json(changed=True,
                                 msg=str(result['status_str']),
                                 status_code=int(resp.code))
            else:
                module.fail_json(changed=False,
                                 msg="API Call failed!",
                                 reason=result['status_str'],
                                 api_call=module.api_call)
        # if method is GET
        else:
            if resp.code == 200:
                module.exit_json(changed=False,
                                 msg=result['_data'],
                                 status_code=resp.code,
                                 response=result)
            else:
                raise Exception("API call failed with status code %d" %
                                int(resp.code))

    except Exception as e:
        module.fail_json(changed=False,
                         msg="API Call failed! Exception during api call",
                         reason=str(e),
                         api_call=module.api_call)