Giter VIP home page Giter VIP logo

fortiosapi's People

Contributors

akasurde avatar barbosm avatar damanin avatar jamesharr avatar javcasalc avatar jiex19 avatar kifeo avatar migumun avatar thomnico avatar udit107710 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fortiosapi's Issues

Improve Exception Handling

Hi,

I'm working on a new FortiOS driver for Napalm and in this process I noticed the current exception handling at check_session().

I've prepared a PR adjusting the exception handling to what I usually see in other projects like requests and urllib3. Let me know your thoughts.

Tests do not run: missing file, wrong Python version

I'm trying to run the tests using tox. Here's what I did to setup:

$ virtualenv -p /usr/bin/python3 venv
Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /data/src/fortiosapi/venv/bin/python3
Also creating executable in /data/src/fortiosapi/venv/bin/python
Installing setuptools, pkg_resources, pip, wheel...done.

$ ./venv/bin/pip install tox

And here is how the test run went:

$ ./venv/bin/tox
GLOB sdist-make: /data/src/fortiosapi/setup.py
py27 inst-nodeps: /data/src/fortiosapi/.tox/.tmp/package/1/fortiosapi-0.10.3.zip
py27 installed: DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.,asn1crypto==0.24.0,bcrypt==3.1.6,certifi==2018.11.29,cffi==1.11.5,chardet==3.0.4,cryptography==2.5,enum34==1.1.6,fortiosapi==0.10.3,idna==2.8,ipaddress==1.0.22,nose==1.3.7,oyaml==0.7,packaging==19.0,paramiko==2.4.2,pexpect==4.6.0,ptyprocess==0.6.0,pyasn1==0.4.5,pycparser==2.19,PyNaCl==1.3.0,pyparsing==2.3.1,PyYAML==3.13,requests==2.21.0,six==1.12.0,urllib3==1.24.1
py27 run-test-pre: PYTHONHASHSEED='2774607791'
py27 runtests: commands[0] | /data/src/fortiosapi/.tox/py27/bin/python -m unittest discover -v
test_fortiosapi_virsh (unittest.loader.ModuleImportFailure) ... ERROR

======================================================================
ERROR: test_fortiosapi_virsh (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_fortiosapi_virsh
Traceback (most recent call last):
  File "/usr/lib/python2.7/unittest/loader.py", line 254, in _find_tests
    module = self._get_module_from_name(name)
  File "/usr/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name
    __import__(name)
  File "/data/src/fortiosapi/tests/test_fortiosapi_virsh.py", line 49, in <module>
    conf = yaml.load(open(virshconffile, 'r'))
IOError: [Errno 2] No such file or directory: 'virsh.yaml'


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
ERROR: InvocationError for command '/data/src/fortiosapi/.tox/py27/bin/python -m unittest discover -v' (exited with code 1)
py35 create: /data/src/fortiosapi/.tox/py35
ERROR: InterpreterNotFound: python3.5
________________________________________ summary _________________________________________
ERROR:   py27: commands failed
ERROR:  py35: InterpreterNotFound: python3.5

I hacked tox.ini to use Python 3.6, since that is what my OS (Ubuntu 18.04) includes:

diff --git a/tox.ini b/tox.ini
index edb1521..b7e8071 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
 [tox]
-envlist = py27,py35
+envlist = py27,py36
 
 [testenv]
 changedir=tests
@@ -15,6 +15,6 @@ commands = {envbindir}/python -m unittest discover -v []
 basepython = python2.7
 
 
-[testenv:py35]
+[testenv:py36]
 #commands = {envbindir}/python -m unittest discover -v []
-basepython = python3.5
\ No newline at end of file
+basepython = python3.6

At least the InterpreterNotFound error is gone, but the tests still fail:

$ ./venv/bin/tox
GLOB sdist-make: /data/src/fortiosapi/setup.py
py27 inst-nodeps: /data/src/fortiosapi/.tox/.tmp/package/1/fortiosapi-0.10.3.zip
py27 installed: DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.,asn1crypto==0.24.0,bcrypt==3.1.6,certifi==2018.11.29,cffi==1.11.5,chardet==3.0.4,cryptography==2.5,enum34==1.1.6,fortiosapi==0.10.3,idna==2.8,ipaddress==1.0.22,nose==1.3.7,oyaml==0.7,packaging==19.0,paramiko==2.4.2,pexpect==4.6.0,ptyprocess==0.6.0,pyasn1==0.4.5,pycparser==2.19,PyNaCl==1.3.0,pyparsing==2.3.1,PyYAML==3.13,requests==2.21.0,six==1.12.0,urllib3==1.24.1
py27 run-test-pre: PYTHONHASHSEED='3793182550'
py27 runtests: commands[0] | /data/src/fortiosapi/.tox/py27/bin/python -m unittest discover -v
test_fortiosapi_virsh (unittest.loader.ModuleImportFailure) ... ERROR

======================================================================
ERROR: test_fortiosapi_virsh (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_fortiosapi_virsh
Traceback (most recent call last):
  File "/usr/lib/python2.7/unittest/loader.py", line 254, in _find_tests
    module = self._get_module_from_name(name)
  File "/usr/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name
    __import__(name)
  File "/data/src/fortiosapi/tests/test_fortiosapi_virsh.py", line 49, in <module>
    conf = yaml.load(open(virshconffile, 'r'))
IOError: [Errno 2] No such file or directory: 'virsh.yaml'


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
ERROR: InvocationError for command '/data/src/fortiosapi/.tox/py27/bin/python -m unittest discover -v' (exited with code 1)
py36 inst-nodeps: /data/src/fortiosapi/.tox/.tmp/package/1/fortiosapi-0.10.3.zip
py36 installed: asn1crypto==0.24.0,bcrypt==3.1.6,certifi==2018.11.29,cffi==1.11.5,chardet==3.0.4,cryptography==2.5,fortiosapi==0.10.3,idna==2.8,nose==1.3.7,oyaml==0.7,packaging==19.0,paramiko==2.4.2,pexpect==4.6.0,ptyprocess==0.6.0,pyasn1==0.4.5,pycparser==2.19,PyNaCl==1.3.0,pyparsing==2.3.1,PyYAML==3.13,requests==2.21.0,six==1.12.0,urllib3==1.24.1
py36 run-test-pre: PYTHONHASHSEED='3793182550'
py36 runtests: commands[0] | /data/src/fortiosapi/.tox/py36/bin/python -m unittest discover -v
test_fortiosapi_virsh (unittest.loader._FailedTest) ... ERROR

======================================================================
ERROR: test_fortiosapi_virsh (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_fortiosapi_virsh
Traceback (most recent call last):
  File "/usr/lib/python3.6/unittest/loader.py", line 428, in _find_test_path
    module = self._get_module_from_name(name)
  File "/usr/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name
    __import__(name)
  File "/data/src/fortiosapi/tests/test_fortiosapi_virsh.py", line 49, in <module>
    conf = yaml.load(open(virshconffile, 'r'))
FileNotFoundError: [Errno 2] No such file or directory: 'virsh.yaml'


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
ERROR: InvocationError for command '/data/src/fortiosapi/.tox/py36/bin/python -m unittest discover -v' (exited with code 1)
________________________________________ summary _________________________________________
ERROR:   py27: commands failed
ERROR:   py36: commands failed

License check breaks usage with vdom admin

Hi,

because the library is trying to access the global vdom here:

resp_lic = self.monitor('license', 'status', vdom="global")

it is not possible to use it with an administrator inside a vdom, because this user obviously cant access the global vdom.

To be honest - I'm not quite sure why this is required anyways?

For the sake of completeness - this is the error which is thrown:

  File "[...]site-packages/fortiosapi/fortiosapi.py", line 182, in login
    self._fortiversion = resp_lic['version']
TypeError: 'Response' object is not subscriptable

To reproduce:

  1. Create VDOM
  2. Create Administrator for this vdom
  3. Try to use the library with the vdom's IP and the created admin user

I'm using a 60d with 5.6.9.

regards,
Jan

Needs timeout value

Requests does not timeout without a timeout value being passed to it. Right now there isn't any mechanism to pass a timeout to the individual request calls that I can tell, so a down device can hang indefinitely (I've seen up to 15 minutes in my environment which is probably when my firewall is killing the session, but in theory requests will hang forever if you let it).

Should probably be able to define a timeout on the FortiOSAPI init and then update the various _session calls to include the timeout option.

FortiOSAPI needs to allow selective TLS Verification

In testing of our ansible playbooks, using ansible_fgt_modules/v6.0.2/firewall/fortios_firewall_vip.py we hit an issue trying to act against a firewall deployed using the FortiNet A-A HA Cluster in Azure, because we were trying to use the HTTPS management interface, not an HTTP interface. We received an error message as follows:

"module_stderr": "/var/lib/awx/venv/ansible/lib/python2.7/site-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n  InsecureRequestWarning)

I believe it should be possible, from reading the fortiosapi code, to specify HTTPS with specific CA verification, with no verification, or to default to standard certificates. Would it be possible to have a feature flag (like you currently have with HTTPS: bool) to select TLS verification?

If this could also be pushed out to the Ansible modules, this would be very helpful!

Happy to engage with your support teams to help progress this.

PS. I have partner status, and am happy to liaise via our SE if required :)

Impossible to use ssl_verify --> Max retries exceeded with url or NotLogged

Hello,

I an trying to create a VDOM through Ansible

I am stuck at the same point I think than greenspartan in ticket #51

My FortiGate is using default configuration with default self signed certificate

Here is my configuration:
thomas@debianAnsible:/etc/ansible$ ansible --version
ansible 2.9.7
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/thomas/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.16 (default, Oct 10 2019, 22:02:15) [GCC 8.3.0]

First try:

My playbook:

- hosts: localhost
  vars:
   host: "10.5.X.1"
   username: "admin"
   password: "fortinet"
   ssl_verify: "False"
   vdom: "root"
  tasks:
  - name: Configure virtual domain.
    fortios_system_vdom:
      host:  "{{ host }}"
      username: "{{ username }}"
      password: "{{ password }}"
      vdom:  "{{ vdom }}"
      https: "False"
      state: "present"
      system_vdom:
        name: "default_name_3"
        short_name: "<your_own_value>"
        temporary: "5"
        vcluster_id: "6"

Here is the output:

Using /etc/ansible/ansible.cfg as config file
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [localhost] **************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************************************************************************************************************
ok: [localhost]

TASK [Configure virtual domain.] **********************************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "No handlers could be found for logger \"fortiosapi\"\nTraceback (most recent call last):\n  File \"/home/thomas/.ansible/tmp/ansible-tmp-1588688299.47-955-192869020258714/AnsiballZ_fortios_system_vdom.py\", line 102, in <module>\n    _ansiballz_main()\n  File \"/home/thomas/.ansible/tmp/ansible-tmp-1588688299.47-955-192869020258714/AnsiballZ_fortios_system_vdom.py\", line 94, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/home/thomas/.ansible/tmp/ansible-tmp-1588688299.47-955-192869020258714/AnsiballZ_fortios_system_vdom.py\", line 40, in invoke_module\n    runpy.run_module(mod_name='ansible.modules.network.fortios.fortios_system_vdom', init_globals=None, run_name='__main__', alter_sys=True)\n  File \"/usr/lib/python2.7/runpy.py\", line 188, in run_module\n    fname, loader, pkg_name)\n  File \"/usr/lib/python2.7/runpy.py\", line 82, in _run_module_code\n    mod_name, mod_fname, mod_loader, pkg_name)\n  File \"/usr/lib/python2.7/runpy.py\", line 72, in _run_code\n    exec code in run_globals\n  File \"/tmp/ansible_fortios_system_vdom_payload_J84qe7/ansible_fortios_system_vdom_payload.zip/ansible/modules/network/fortios/fortios_system_vdom.py\", line 350, in <module>\n  File \"/tmp/ansible_fortios_system_vdom_payload_J84qe7/ansible_fortios_system_vdom_payload.zip/ansible/modules/network/fortios/fortios_system_vdom.py\", line 339, in main\n  File \"/tmp/ansible_fortios_system_vdom_payload_J84qe7/ansible_fortios_system_vdom_payload.zip/ansible/modules/network/fortios/fortios_system_vdom.py\", line 224, in login\n  File \"/home/thomas/.local/lib/python2.7/site-packages/fortiosapi/fortiosapi.py\", line 170, in login\n    data='username=' + urllib.parse.quote(username) + '&secretkey=' + urllib.parse.quote(password) + \"&ajax=1\", timeout=self.timeout)\n  File \"/home/thomas/.local/lib/python2.7/site-packages/requests/sessions.py\", line 578, in post\n    return self.request('POST', url, data=data, json=json, **kwargs)\n  File \"/home/thomas/.local/lib/python2.7/site-packages/requests/sessions.py\", line 530, in request\n    resp = self.send(prep, **send_kwargs)\n  File \"/home/thomas/.local/lib/python2.7/site-packages/requests/sessions.py\", line 665, in send\n    history = [resp for resp in gen] if allow_redirects else []\n  File \"/home/thomas/.local/lib/python2.7/site-packages/requests/sessions.py\", line 245, in resolve_redirects\n    **adapter_kwargs\n  File \"/home/thomas/.local/lib/python2.7/site-packages/requests/sessions.py\", line 643, in send\n    r = adapter.send(request, **kwargs)\n  File \"/home/thomas/.local/lib/python2.7/site-packages/requests/adapters.py\", line 514, in send\n    raise SSLError(e, request=request)\nrequests.exceptions.SSLError: HTTPSConnectionPool(host='10.5.X.1', port=443): Max retries exceeded with url: /logincheck (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:727)'),))\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

2nd try:

My playbook:

- hosts: localhost
  vars:
   host: "10.5.X.1"
   username: "admin"
   password: "fortinet"
   ssl_verify: "False"
   vdom: "root"
  tasks:
  - name: Configure virtual domain.
    fortios_system_vdom:
      host:  "{{ host }}"
      username: "{{ username }}"
      password: "{{ password }}"
      ssl_verify: "{{ ssl_verify }}"  <----- Added
      vdom:  "{{ vdom }}"
      https: "False"
      state: "present"
      system_vdom:
        name: "default_name_3"
        short_name: "<your_own_value>"
        temporary: "5"
        vcluster_id: "6"

Here is the output:

PLAY [localhost] **************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************************************************************************************************************
ok: [localhost]

TASK [Configure virtual domain.] **********************************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "No handlers could be found for logger \"fortiosapi\"\n/home/thomas/.local/lib/python2.7/site-packages/urllib3/connectionpool.py:986: InsecureRequestWarning: Unverified HTTPS request is being made to host '10.5.X.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n  InsecureRequestWarning,\n/home/thomas/.local/lib/python2.7/site-packages/urllib3/connectionpool.py:986: InsecureRequestWarning: Unverified HTTPS request is being made to host '10.5.X.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n  InsecureRequestWarning,\n/home/thomas/.local/lib/python2.7/site-packages/urllib3/connectionpool.py:986: InsecureRequestWarning: Unverified HTTPS request is being made to host '10.5.X.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n  InsecureRequestWarning,\nTraceback (most recent call last):\n  File \"/home/thomas/.ansible/tmp/ansible-tmp-1588688469.75-1041-79183703068022/AnsiballZ_fortios_system_vdom.py\", line 102, in <module>\n    _ansiballz_main()\n  File \"/home/thomas/.ansible/tmp/ansible-tmp-1588688469.75-1041-79183703068022/AnsiballZ_fortios_system_vdom.py\", line 94, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/home/thomas/.ansible/tmp/ansible-tmp-1588688469.75-1041-79183703068022/AnsiballZ_fortios_system_vdom.py\", line 40, in invoke_module\n    runpy.run_module(mod_name='ansible.modules.network.fortios.fortios_system_vdom', init_globals=None, run_name='__main__', alter_sys=True)\n  File \"/usr/lib/python2.7/runpy.py\", line 188, in run_module\n    fname, loader, pkg_name)\n  File \"/usr/lib/python2.7/runpy.py\", line 82, in _run_module_code\n    mod_name, mod_fname, mod_loader, pkg_name)\n  File \"/usr/lib/python2.7/runpy.py\", line 72, in _run_code\n    exec code in run_globals\n  File \"/tmp/ansible_fortios_system_vdom_payload_Mf8gAM/ansible_fortios_system_vdom_payload.zip/ansible/modules/network/fortios/fortios_system_vdom.py\", line 350, in <module>\n  File \"/tmp/ansible_fortios_system_vdom_payload_Mf8gAM/ansible_fortios_system_vdom_payload.zip/ansible/modules/network/fortios/fortios_system_vdom.py\", line 340, in main\n  File \"/tmp/ansible_fortios_system_vdom_payload_Mf8gAM/ansible_fortios_system_vdom_payload.zip/ansible/modules/network/fortios/fortios_system_vdom.py\", line 284, in fortios_system\n  File \"/tmp/ansible_fortios_system_vdom_payload_Mf8gAM/ansible_fortios_system_vdom_payload.zip/ansible/modules/network/fortios/fortios_system_vdom.py\", line 267, in system_vdom\n  File \"/home/thomas/.local/lib/python2.7/site-packages/fortiosapi/fortiosapi.py\", line 417, in set\n    mkey = self.get_mkey(path, name, data, vdom=vdom)\n  File \"/home/thomas/.local/lib/python2.7/site-packages/fortiosapi/fortiosapi.py\", line 228, in get_mkey\n    keyname = self.get_mkeyname(path, name, vdom)\n  File \"/home/thomas/.local/lib/python2.7/site-packages/fortiosapi/fortiosapi.py\", line 217, in get_mkeyname\n    schema = self.schema(path, name, vdom=vdom)\n  File \"/home/thomas/.local/lib/python2.7/site-packages/fortiosapi/fortiosapi.py\", line 317, in schema\n    url = self.cmdb_url(path, name, vdom=vdom) + \"&action=schema\"\n  File \"/home/thomas/.local/lib/python2.7/site-packages/fortiosapi/fortiosapi.py\", line 252, in cmdb_url\n    self.check_session()\n  File \"/home/thomas/.local/lib/python2.7/site-packages/fortiosapi/fortiosapi.py\", line 126, in check_session\n    raise NotLogged()\nfortiosapi.exceptions.NotLogged: Not logged on a session, please login.\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

I am sure of the credentials as I can log from debianAnsible in my FortiGate using SSH:

thomas@debianAnsible:/etc/ansible$ ssh [email protected]
The authenticity of host '10.5.X.1 (10.5.X.1)' can't be established.
ED25519 key fingerprint is SHA256:ejSbDEsTO09eQcC/RN5kqtxXgLGzs5wi6XcRbt05Ia4.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.5.X.1' (ED25519) to the list of known hosts.
[email protected]'s password:
fortinet-vm #

I am stuck could you help me?
Is there any bug?

Cheers

Thomas

HTTP -> HTTPS (via 302 redirect) does not disable certificate checking

I am using the ansible_fgt_module libraries, and if I forget to specify https: True, and don't specify a port number, I get the following:

fatal: [localhost]: FAILED! => {
    "changed": false,
    "module_stderr": "/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n  InsecureRequestWarning)\n/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n  InsecureRequestWarning)\n/usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n  InsecureRequestWarning)\nTraceback (most recent call last):\n  File \"/home/spriggsj/.ansible/tmp/ansible-tmp-1549621114.0393393-176012617895562/AnsiballZ_fortios_log_syslogd_setting.py\", line 113, in <module>\n    _ansiballz_main()\n  File \"/home/spriggsj/.ansible/tmp/ansible-tmp-1549621114.0393393-176012617895562/AnsiballZ_fortios_log_syslogd_setting.py\", line 105, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/home/spriggsj/.ansible/tmp/ansible-tmp-1549621114.0393393-176012617895562/AnsiballZ_fortios_log_syslogd_setting.py\", line 48, in invoke_module\n    imp.load_module('__main__', mod, module, MOD_DESC)\n  File \"/usr/lib/python3.6/imp.py\", line 235, in load_module\n    return load_source(name, filename, file)\n  File \"/usr/lib/python3.6/imp.py\", line 170, in load_source\n    module = _exec(spec, sys.modules[name])\n  File \"<frozen importlib._bootstrap>\", line 618, in _exec\n  File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\n  File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n  File \"/tmp/ansible_fortios_log_syslogd_setting_payload_lpcznfjs/__main__.py\", line 367, in <module>\n  File \"/tmp/ansible_fortios_log_syslogd_setting_payload_lpcznfjs/__main__.py\", line 358, in main\n  File \"/tmp/ansible_fortios_log_syslogd_setting_payload_lpcznfjs/__main__.py\", line 293, in fortios_log_syslogd\n  File \"/tmp/ansible_fortios_log_syslogd_setting_payload_lpcznfjs/__main__.py\", line 265, in login\n  File \"/usr/local/lib/python3.6/dist-packages/fortiosapi/fortiosapi.py\", line 193, in login\n    raise Exception('login failed')\nException: login failed\n",
    "module_stdout": "",
    "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
    "rc": 1
}

If I specify https: True this play runs successfully.

I believe that the fortiosapi library is disabling HTTPS certificate checking when HTTPS is enabled, but not doing so when it is not enabled. Thus, when the HTTP302 is fired, and it redirects to the HTTPS port, it should also disable HTTPS certificate checking.

I can't spot where in the code this is happening (I had a quick parse, but couldn't catch it), but it's worth noting.

Better documentation

Hallo,

I would like to have more documentation, e.g. with sphinx.

Best regards
ikreb7

SSH Method broken

The SSH method doesn't work. This can be fixed by changing line 433 in fortiosapi.py from:

        LOG.debug("ssh login to  %s:%s ", host, ssh_port)

to

        LOG.debug("ssh login to  %s:%s ", host, port)`

Installation problem

Installed /usr/local/lib/python3.6/site-packages/fortiosapi-1.0.4-py3.6.egg
Processing dependencies for fortiosapi==1.0.4
Searching for oyaml
Reading https://pypi.org/simple/oyaml/

hello๏ผŒ
I found that downloading oyaml stopped during use. Is the wrong path for specifying oyaml? I noticed that oyaml was last updated a year ago

get_name_path_dict() logic incorrect

if vdom is None:

Looks like this line should be:

if vdom is not None

Right now it's checking to see if vdom is passed, and if it is, it doesn't use it, but if it isn't, it tries to concatenate None into the url string causing a traceback.

It still gets me back a list of paths when I do this (on a non vdom enabled Fortigate):

names = fgt.get_name_path_dict(vdom='gibberish! this should not work!')

Modification of the 'password' field of system.admin is forbidden

Trying to update the password of an existing system admin on a FortiGate VM64-KVM v6.2.2 fails with error

Modification of the 'password' field of system.admin is forbidden.

See full log output below. It was attempted to apply the config via the ansible fortios_system_admin module, see as well the relevant excerpt of the play below. This looks like an issue with fortiosapi, but let me know if this should be rather handled by the ansible module.

[httpsd 1582 - 1585763448     info] child_main[5142] -- New PUT request for "/api/v2/cmdb/system/admin/SNMP_DUMMY" from "10.123.42.1:12400"
[httpsd 1582 - 1585763448     info] child_main[5143] -- User-Agent: "python-requests/2.23.0"
[httpsd 1582 - 1585763448     info] ap_invoke_handler[572] -- Handler "api_cmdb_v2-handler" assigned to request
[httpsd 1582 - 1585763448     info] aps_init_process_vdom[1262] -- initialized process vdom to 'root' (cookie='(null)')
[httpsd 1582 - 1585763448     info] api_store_parameter[239] -- add API parameter 'vdom' (type=string)
[httpsd 1582 - 1585763448     info] api_store_parameter[239] -- add API parameter 'accprofile' (type=string)
[httpsd 1582 - 1585763448     info] api_store_parameter[239] -- add API parameter 'name' (type=string)
[httpsd 1582 - 1585763448     info] api_store_parameter[239] -- add API parameter 'password' (type=string)
[httpsd 1582 - 1585763448     info] api_store_parameter[239] -- add API parameter 'trusthost1' (type=string)
[httpsd 1582 - 1585763448     info] handle_cli_req_v2_vdom[2123] -- new CMDB API request (vdom='root',user='admin')
[httpsd 1582 - 1585763448     info] api_cmdb_request_init_by_path[1509] -- new CMDB query (path='system',name='admin')
[httpsd 1582 - 1585763448     info] api_cmdb_request_init_by_path[1538] -- querying CMDB entry (mkey='SNMP_DUMMY')
[httpsd 1582 - 1585763448     info] _api_cmdb_v2_config[1180] -- editing CLI object (append=0, auto_key=0, path=system, name=admin, mkey=SNMP_DUMMY, flags=0)
[httpsd 1582 - 1585763448    error] _api_cmdb_v2_config[1191] -- Modification of the 'password' field of system.admin is forbidden.
[httpsd 1582 - 1585763448  warning] api_return_http_result[702] -- API error 403 raised
[httpsd 1582 - 1585763448     info] child_main[5212] -- Completed PUT request for "/api/v2/cmdb/system/admin/SNMP_DUMMY"
- name: Create dummy admin accounts to allow SNMP access via trusted hosts
  delegate_to: localhost
  fortios_system_admin:
    host: "{{ ansible_host }}"
    username: "{{ FORTIOS_USER }}"
    password: "{{ FORTIOS_PASS }}"
    vdom: "root"
    https: "{{ FORTIOS_HTTPS }}"
    ssl_verify: "{{ FORTIOS_SSL_VERIFY }}"
    state: "present"
    system_admin:
      name: "{{ 'SNMP_DUMMY }}"
      accprofile: "admin_no_access"
      trusthost1: "{{ item + ' 255.255.255.255' }}"
      password: "test"

How to use POST module for objects under monitor (eg monitor/geoip

I am currently testing using restapi utilizing the fortiosapi, however, I would like to ask because I bump into issue when I am trying to monitor/geoip that must use POST.

In this /geoip/geoip-query/select, the fndn mentioned is using POST. Meanwhile if I am using FortiOSAPI.monitor:

def monitor(self, path, name, vdom=None, mkey=None, parameters=None):
    url = self.mon_url(path, name, vdom, mkey)
    LOG.debug("in monitor url is %s", url)
    res = **self._session.get**(url, params=parameters, timeout=self.timeout)
    LOG.debug("in MONITOR function")

The procedure is using get, and canโ€™t use POST as recommended by fndn.fortinet.

In the other hand, I also can not use post module :

def post(self, path, name, data, vdom=None,
mkey=None, parameters=None):
# we always post to the upper name/path the mkey is in the data.
# So we can ensure the data set is correctly filled in case mkey is passed.
LOG.debug("in POST function")
if mkey:
mkeyname = self.get_mkeyname(path, name, vdom)
LOG.debug("in post calculated mkeyname : %s mkey: %s ",
mkeyname, mkey)
# if mkey is forced on the function call then we change it in the data
# even if inconsistent data/mkey is passed
data[mkeyname] = mkey
# post with mkey will return a 404 as the next level is not there yet
# we pushed mkey in data if needed.
url = **self.cmdb_url(**path, name, vdom, mkey=None)

Because post module will use cmdb_url , meanwhile the monitor/geoip is not under /api/v2/cmdb/.

Or should I use other procedure to accomplish POST under MONITOR/GEOIP ?
Thanks

Format response cannot deal with non utf-8 characters

The fortigate supports non utf-8 characters, suggestion to replace these when formatting response:

def formatresponse(self, res, vdom=None):
        LOG.debug("formating response")
        self.logging(res)
        # Generic way to format the return from FortiAPI
        # If vdom is global the resp is a dict of resp (even 1)
        # 1 per vdom we check only the first one here (might need a more
        # complex check)
        if vdom == "global":
            resp = json.loads(res.content.decode('utf-8', errors='replace'))[0]
            resp['vdom'] = "global"
        else:
            LOG.debug("content res: %s", res.content)
            resp = json.loads(res.content.decode('utf-8', errors='replace'))
        return resp

Getaddrinfo failed upon logging in

I am connected directly to a FortiGate 100E to test my code and upon logging in, I received a "getaddrinfo" failed error:

Traceback (most recent call last):
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connection.py", line 160, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\util\connection.py", line 57, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connectionpool.py", line 603, in urlopen
chunked=chunked)
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connectionpool.py", line 344, in _make_request
self._validate_conn(conn)
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connectionpool.py", line 843, in _validate_conn
conn.connect()
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connection.py", line 316, in connect
conn = self._new_conn()
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connection.py", line 169, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x00000271E236AC50>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\adapters.py", line 449, in send
timeout=timeout
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connectionpool.py", line 641, in urlopen
_stacktrace=sys.exc_info()[2])
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\util\retry.py", line 399, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: //192.168.1.159/logincheck (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x00000271E236AC50>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\ktrang\Downloads\fortiosapi-master\fortiosapi-master_init_.py", line 1, in
from fortiosapi.fortiosapi import FortiOSAPI
File "C:\Users\ktrang\Downloads\fortiosapi-master\fortiosapi-master\fortiosapi_init_.py", line 4, in
print(server.login(host = "https://192.168.1.159", username = "admin", password = "admin"))
File "C:\Users\ktrang\Downloads\fortiosapi-master\fortiosapi-master\fortiosapi\fortiosapi.py", line 183, in login
data='username=' + urllib.parse.quote(username) + '&secretkey=' + urllib.parse.quote(password) + "&ajax=1", timeout=self.timeout)
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 581, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "C:\Users\ktrang\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: //192.168.1.159/logincheck (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x00000271E236AC50>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

Configuration restore issue

Hi,
I'm using your script in order to backup existing configuration, manipulate it and then upload to another device.
I'm having issues with the upload (restore function) part.
Here is the relevant part:
`params = {'access_token': apikey}
data = {"source": "upload", "scope": "global"}
files = {'file': ('random_conf.conf', config, 'text/plain')}

logging.info("attempting to upload configuration to device")
response = fgt.upload("system/config", "restore", data=data, files=files, parameters=params)`

I'm getting the following response: "403 | Forbidden: Request is missing CSRF token or administrator is missing access profile permissions."
The end device running 6.4.3 without vdom's.

Thanks,
Grigory

TypeError: 'Response' object is not subscriptable

Hello

I'm not sure if this is the correct repo for such an issue - apologies if I should post this somewhere else.

I'm trying to run the following ansible playbook, using Ansible AWX, but am getting the below error:

Versions

ansible-playbook 2.9.4
python 3.6.8

Ansible Playbook

---
- name: Sync ports
  hosts: localhost
  connection: local
  gather_facts: no
  vars:
   host: "xx.xx.xx.xx"
   username: "xxxx"
   password: "xxxxx"
   vdom: "test_vdom"
   ssl_verify: "False"

  tasks:



    - name: Configure custom services.
      fortios_firewall_service_custom:
        host:  "{{ host }}"
        username: "{{ username }}"
        password: "{{ password }}"
        vdom:  "{{ vdom }}"
        https: "false"
        ssl_verify: "False"
  #      state: "present"
        firewall_service_custom:
            category: "test_cat"
            comment: "testing"
            name: "testing_tcp.10000"
            visibility: "enable"
            state: present
   #         ssl_verify: false

Error

    "module_stderr": "in formatresponse res.content does not exist, should not occur\nTraceback (most recent call last):\n  File \"/var/lib/awx/.ansible/tmp/ansible-tmp-1580769097.8021286-118964279067587/AnsiballZ_fortios_firewall_service_custom.py\", line 102, in <module>\n    _ansiballz_main()\n  File \"/var/lib/awx/.ansible/tmp/ansible-tmp-1580769097.8021286-118964279067587/AnsiballZ_fortios_firewall_service_custom.py\", line 94, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/var/lib/awx/.ansible/tmp/ansible-tmp-1580769097.8021286-118964279067587/AnsiballZ_fortios_firewall_service_custom.py\", line 40, in invoke_module\n    runpy.run_module(mod_name='ansible.modules.network.fortios.fortios_firewall_service_custom', init_globals=None, run_name='__main__', alter_sys=True)\n  File \"/usr/lib64/python3.6/runpy.py\", line 205, in run_module\n    return _run_module_code(code, init_globals, run_name, mod_spec)\n  File \"/usr/lib64/python3.6/runpy.py\", line 96, in _run_module_code\n    mod_name, mod_spec, pkg_name, script_name)\n  File \"/usr/lib64/python3.6/runpy.py\", line 85, in _run_code\n    exec(code, run_globals)\n  File \"/tmp/ansible_fortios_firewall_service_custom_payload_doutnw1b/ansible_fortios_firewall_service_custom_payload.zip/ansible/modules/network/fortios/fortios_firewall_service_custom.py\", line 566, in <module>\n  File \"/tmp/ansible_fortios_firewall_service_custom_payload_doutnw1b/ansible_fortios_firewall_service_custom_payload.zip/ansible/modules/network/fortios/fortios_firewall_service_custom.py\", line 555, in main\n  File \"/tmp/ansible_fortios_firewall_service_custom_payload_doutnw1b/ansible_fortios_firewall_service_custom_payload.zip/ansible/modules/network/fortios/fortios_firewall_service_custom.py\", line 391, in login\n  File \"/opt/custom-venvs/infrastructure/lib/python3.6/site-packages/fortiosapi/fortiosapi.py\", line 181, in login\n    self._fortiversion = resp_lic['version']\nTypeError: 'Response' object is not subscriptable\n",

Should review "set"

MAny parameters/rules use only "put" and post raise error.

Should do a better check and might try put before post.

Need instructions on how to run tests

It's unclear how to run the tests in this project. There is a small blurb in README.md, but I have never used tox so I don't know what I need to do. It's also unclear what "virsh access" means -- does that mean the tests use libvirt/virsh/KVM/etc. to run in a virtualized environment? If so, what versions of Linux are supported? Are any other operating systems supported?

It would be much more helpful if the README file specified:

  • what operating system(s) are supported for running the tests
  • what additional OS packages must be installed to run the tests
  • what versions of Python are supported and/or required
  • the exact shell command(s) I must run to run the tests

For the record, here are the things I tried:

  1. Create a virtualenv, "pip install -r requirements.txt", "pip install tox", then run tox. This failed in a variety of ways. (I'll open separate issues for them.)
  2. "python setup.py test". This did a bunch of stuff and finished with "Ran 0 tests in 0.000s". Not the expected outcome!

How to add New One-Time Schedule by cmdb api

When I use the python code as below, then I get a error:

name = str(name)
        payload = {'json':
                    {
                    'name':  name ,
                    'start': stime,
                    'end': etime,
                    'type':  'One Time'
                    }
               }
        requests.post('https://$ip/api/v2/cmdb/firewall/schedule/onetime/' + name + '/', json.loads(payload))

the return error code is 400. So how can i use the api to create one-time schedule . Thanks!

401 Authorization Error when post-login-banner option is set.

I tried engaging support, but was told the Technical Team doesn't support the API even though its clear the issue stems from the use of the post-login-banner option being set. I am opening this issue up in hopes for clarity around the 401 response that i am getting using the fortiosapi library.

I also asked about this being a potential bug but got no response.

Thank you.

stdout from script:

$ python3 fortigateapi_test.py                                                                                                                                                                                                                                                 /usr/lib/python3.6/site-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings              InsecureRequestWarning)                                                                                                                                                                                                                                                      /usr/lib/python3.6/site-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)                                                                                                                                                                                                                                                      Traceback (most recent call last):                                                                                                                                                                                                                                               File "fortigateapi_test.py", line 19, in <module>                                                                                                                                                                                                                                fgt.login("REMOVED", "admin", "REMOVED")                                                                                                                                                                                                                             File "/usr/lib/python3.6/site-packages/fortiosapi/fortiosapi.py", line 187, in login
    raise e
  File "/usr/lib/python3.6/site-packages/fortiosapi/fortiosapi.py", line 182, in login
    self._fortiversion = resp_lic['version']
TypeError: 'Response' object is not subscriptable

Test script:

#!/usr/bin/env python

import sys
import pprint
import requests
import getpass
import logging
from fortiosapi import FortiOSAPI

formatter = logging.Formatter(
    '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
logger = logging.getLogger('fortiosapi')
hdlr = logging.FileHandler('testfortiosapi.log')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
fgt = FortiOSAPI()

fgt.login("0.0.0.0", "admin", "PASSWORD-REMOVED")

resp = fgt.get('system', 'global', vdom="global")

logging.debug(resp)

fgt.logout()

output in testfortiosapi.log: (with post-login-banner set in config)

$ cat testfortiosapi.log
2019-08-02 12:08:14,596 fortiosapi   DEBUG    self._https is True
2019-08-02 12:08:15,130 fortiosapi   DEBUG    response content type : text/html; charset=utf-8
2019-08-02 12:08:15,131 fortiosapi   DEBUG    Request : POST on url : https://0.0.0.0/logincheck
2019-08-02 12:08:15,131 fortiosapi   DEBUG    Response : http code 200  reason : OK
2019-08-02 12:08:15,131 fortiosapi   DEBUG    raw response:  b'1document.location="/logindisclaimer?viewOnly&redir=%2Fng%2F";\n'
2019-08-02 12:08:15,131 fortiosapi   DEBUG    logincheck res : b'1document.location="/logindisclaimer?viewOnly&redir=%2Fng%2F";\n'
2019-08-02 12:08:15,131 fortiosapi   DEBUG    cookies are  : <RequestsCookieJar[<Cookie APSCOOKIE_2735489310="Era%3D0%26Payload%3DpV7NoyHomCpeJqN0m4AbTxH8yPX6wK55KUK0yj+6wM2zJ2dajUryWM%2FY07xYyRFV%0AOTMyCE%2FLuILhoOSgs0JjHf0sSCFa8rqGV5wgznkXVEao2NmbCfa4xIn+Q4MvdV2M%0AO9m
SnoRIkhNFvFaLhnViuQOXTZioG2dTOQ215XvWl55pHxwamOY5GOf2tF+pVbsk%0AKVY8uOcNubzSF9OS4d3Evw%3D%3D%0A%26AuthHash%3DOoktRdOfh0gy+tBD6F0d4KnJoY8A%0A" for 0.0.0.0/>, <Cookie ccsrftoken="53C3487D7463F6BAC67D3508291D0CE" for 0.0.0.0/>, <Cookie ccsrftoken_2735489310="5
3C3487D7463F6BAC67D3508291D0CE" for 0.0.0.0/>]>
2019-08-02 12:08:15,131 fortiosapi   DEBUG    csrftoken before update  : 53C3487D7463F6BAC67D3508291D0CE
2019-08-02 12:08:15,131 fortiosapi   DEBUG    csrftoken after update  : 53C3487D7463F6BAC67D3508291D0CE
2019-08-02 12:08:15,131 fortiosapi   DEBUG    New session header is: {'User-Agent': 'python-requests/2.21.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'X-CSRFTOKEN': '53C3487D7463F6BAC67D3508291D0CE'}
2019-08-02 12:08:15,131 fortiosapi   DEBUG    vdom is: global
2019-08-02 12:08:15,131 fortiosapi   DEBUG    in monitor url is https://0.0.0.0/api/v2/monitor/license/status?global=1
2019-08-02 12:08:15,231 fortiosapi   DEBUG    in MONITOR function
2019-08-02 12:08:15,231 fortiosapi   DEBUG    formating response
2019-08-02 12:08:15,232 fortiosapi   DEBUG    response content type : text/html; charset=iso-8859-1
2019-08-02 12:08:15,232 fortiosapi   DEBUG    Request : GET on url : https://0.0.0.0/api/v2/monitor/license/status?global=1
2019-08-02 12:08:15,232 fortiosapi   DEBUG    Response : http code 401  reason : Authorization Required
2019-08-02 12:08:15,232 fortiosapi   DEBUG    raw response:  b'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<HTML><HEAD>\n<TITLE>401 Authorization Required</TITLE>\n</HEAD><BODY>\n<H1>Authorization Required</H1>\nThis server could not verify that you\nare authoriz
ed to access the document\nrequested.  Either you supplied the wrong\ncredentials (e.g., bad password), or your\nbrowser doesn\'t understand how to supply\nthe credentials required.<P>\n<P>Additionally, a 401 Authorization Required\nerror was encountered while trying to
use an ErrorDocument to handle the request.\n</BODY></HTML>\n'
2019-08-02 12:08:15,233 fortiosapi   WARNING  in formatresponse res.content does not exist, should not occur
2019-08-02 12:08:15,233 fortiosapi   DEBUG    response monitor license: <Response [401]>

output in testfortiosapi.log: (WITHOUT post-login-banner set in config)

$ cat testfortiosapi.log                                                                                                                                                                                                                                              [23/2922]
2019-08-02 12:10:51,745 fortiosapi   DEBUG    self._https is True
2019-08-02 12:10:52,319 fortiosapi   DEBUG    response content type : text/html; charset=utf-8
2019-08-02 12:10:52,319 fortiosapi   DEBUG    Request : POST on url : https://0.0.0.0/logincheck
2019-08-02 12:10:52,320 fortiosapi   DEBUG    Response : http code 200  reason : OK
2019-08-02 12:10:52,320 fortiosapi   DEBUG    raw response:  b'1document.location="/ng/prompt?viewOnly&redir=%2Fng%2F";\n'
2019-08-02 12:10:52,320 fortiosapi   DEBUG    logincheck res : b'1document.location="/ng/prompt?viewOnly&redir=%2Fng%2F";\n'
2019-08-02 12:10:52,321 fortiosapi   DEBUG    cookies are  : <RequestsCookieJar[<Cookie APSCOOKIE_2735489310="Era%3D0%26Payload%3D4i3SPAe4WWmApRRwS242E7hW1LnOeSOMNsEzLqo5j3ZSpdO+0eZCIiCSng7RobQS%0AQA9yihBqmQSYebQHVaHZ%2FGlaqRVbHKiF7yXWOD8+00MuFTNkAQWlsgBYvmQFPL4Z%0ABBEhr
LQcySKtCXHCodZ1z5Udr7AATFTyPeJNlpa2SFAOD9uZFbTLEOQqCC96sosx%0Ar9Ci%2FhHTBvN02ScGmzYPvA%3D%3D%0A%26AuthHash%3Df9bq0VE8r4vdRGEIKOz+A8Md7tkA%0A" for 0.0.0.0/>, <Cookie ccsrftoken="248DF4DA959C5DBE8FF6F723B743CF9" for 0.0.0.0/>, <Cookie ccsrftoken_2735489310="2
48DF4DA959C5DBE8FF6F723B743CF9" for 0.0.0.0/>]>
2019-08-02 12:10:52,321 fortiosapi   DEBUG    csrftoken before update  : 248DF4DA959C5DBE8FF6F723B743CF9
2019-08-02 12:10:52,321 fortiosapi   DEBUG    csrftoken after update  : 248DF4DA959C5DBE8FF6F723B743CF9
2019-08-02 12:10:52,322 fortiosapi   DEBUG    New session header is: {'User-Agent': 'python-requests/2.21.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'X-CSRFTOKEN': '248DF4DA959C5DBE8FF6F723B743CF9'}
2019-08-02 12:10:52,322 fortiosapi   DEBUG    vdom is: global
2019-08-02 12:10:52,322 fortiosapi   DEBUG    in monitor url is https://0.0.0.0/api/v2/monitor/license/status?global=1
2019-08-02 12:10:52,469 fortiosapi   DEBUG    in MONITOR function
2019-08-02 12:10:52,469 fortiosapi   DEBUG    formating response
2019-08-02 12:10:52,469 fortiosapi   DEBUG    response content type : application/json
2019-08-02 12:10:52,469 fortiosapi   DEBUG    Request : GET on url : https://0.0.0.0/api/v2/monitor/license/status?global=1
2019-08-02 12:10:52,470 fortiosapi   DEBUG    Response : http code 200  reason : OK
2019-08-02 12:10:52,470 fortiosapi   DEBUG    raw response:  b'[\n  {\n    "http_method":"GET",\n    "results":{\n      "fortiguard":{\n        "connected":true,\n        "update_server_usa":false,\n        "server_address":"173.243.138.91:443",\n        "fortigate_wan_i
p":"0.0.0.0"\n      },\n      "forticare":{\n        "status":"registered",\n        "account":"[email protected]",\n        "support":{\n          "hardware":{\n            "status":"licensed",\n            "support_level":"Return To Factory",\n
 "expires":1650240000\n          },\n          "firmware":{\n            "status":"licensed",\n            "support_level":"Web\\/Online",\n            "expires":1650240000\n          },\n          "enhanced":{\n            "status":"licensed",\n            "support_leve
l":"8x5",\n            "expires":1650240000\n          }\n        },\n        "company":"Innflux",\n        "industry":""\n      },\n      "antivirus":{\n        "status":"licensed",\n        "version":"1.00000",\n        "expires":1650240000,\n        "last_update":1350
513960,\n        "db_status":"db_type_extended",\n        "engine":{\n          "version":"5.00361",\n          "last_update":1529466120,\n          "last_update_attempt":1555522659,\n          "last_update_result_status":"update_result_no_updates",\n          "last_upda
te_method_status":"update_method_manual"\n        }\n      },\n      "ips":{\n        "status":"licensed",\n        "version":"14.00596",\n        "expires":1650240000,\n        "last_update":1555522659,\n        "last_update_attempt":1555522659,\n        "last_update_re
sult_status":"update_result_success",\n        "last_update_method_status":"update_method_sched",\n        "db_status":"db_type_normal",\n        "engine":{\n          "version":"3.00539",\n          "last_update":1541488380,\n          "last_update_attempt":1555522659,\
n          "last_update_result_status":"update_result_no_updates",\n          "last_update_method_status":"update_method_manual"\n        },\n        "malicious_urls":{\n          "status":"licensed",\n          "version":"2.00376",\n          "expires":1650240000,\n
      "last_update":1564724233,\n          "last_update_attempt":1564760173,\n          "last_update_result_status":"update_result_no_updates",\n          "last_update_method_status":"update_method_sched"\n        }\n      },\n      "appctrl":{\n        "status":"license
d",\n        "version":"14.00596",\n        "expires":1650240000,\n        "last_update":1555522659,\n        "last_update_attempt":1555522659,\n        "last_update_result_status":"update_result_success",\n        "last_update_method_status":"update_method_sched"\n
 },\n      "botnet_ip":{\n        "status":"licensed",\n        "version":"4.00459",\n        "expires":1650240000,\n        "last_update":1555522659,\n        "last_update_attempt":1555522659,\n        "last_update_result_status":"update_result_success",\n        "last_
update_method_status":"update_method_sched"\n      },\n      "botnet_domain":{\n        "status":"licensed",\n        "version":"2.00296",\n        "expires":1650240000,\n        "last_update":1564695434,\n        "last_update_attempt":1564760173,\n        "last_update_r
esult_status":"update_result_no_updates",\n        "last_update_method_status":"update_method_sched"\n      },\n      "mobile_malware":{\n        "status":"licensed",\n        "version":"70.00425",\n        "expires":1650240000,\n        "last_update":1564760173,\n
  "last_update_attempt":1564760173,\n        "last_update_result_status":"update_result_success",\n        "last_update_method_status":"update_method_sched"\n      },\n      "internet_service_db":{\n        "status":"licensed",\n        "version":"7.00016",\n        "las
t_update":1564695434,\n        "last_update_attempt":1564760173,\n        "last_update_result_status":"update_result_no_updates",\n        "last_update_method_status":"update_method_sched"\n      },\n      "device_os_id":{\n        "status":"licensed",\n        "version"
:"1.00079",\n        "expires":1650240000,\n        "last_update":1560793814,\n        "last_update_attempt":1564760173,\n        "last_update_result_status":"update_result_no_updates",\n        "last_update_method_status":"update_method_sched"\n      },\n      "web_filt
ering":{\n        "status":"unavailable",\n        "category_list_version":8\n      },\n      "antispam":{\n        "status":"unavailable"\n      },\n      "industrial_db":{\n        "status":"pending",\n        "version":"6.00741",\n        "last_update":1448962200\n
   },\n      "vdom":{\n        "can_upgrade":false,\n        "used":1,\n        "max":10\n      },\n      "forticlient":{\n        "status":"free_license",\n        "can_upgrade":true,\n        "used":0,\n        "max":10\n      },\n      "forticloud":{\n        "status"
:"cloud_logged_out"\n      },\n      "sms":{\n        "status":"no_license",\n        "used":0,\n        "max":0\n      }\n    },\n    "vdom":"root",\n    "path":"license",\n    "name":"status",\n    "action":"select",\n    "status":"success",\n    "serial":"FGT60ETK1806
7969",\n    "version":"v5.6.8",\n    "build":1672\n  }\n]'
2019-08-02 12:10:52,471 fortiosapi   DEBUG    response monitor license: {'http_method': 'GET', 'results': {'fortiguard': {'connected': True, 'update_server_usa': False, 'server_address': '173.243.138.91:443', 'fortigate_wan_ip': '0.0.0.0'}, 'forticare': {'status':
 'registered', 'account': '[email protected]', 'support': {'hardware': {'status': 'licensed', 'support_level': 'Return To Factory', 'expires': 1650240000}, 'firmware': {'status': 'licensed', 'support_level': 'Web/Online', 'expires': 1650240000}, 'enhanced': {'stat
us': 'licensed', 'support_level': '8x5', 'expires': 1650240000}}, 'company': 'Innflux', 'industry': ''}, 'antivirus': {'status': 'licensed', 'version': '1.00000', 'expires': 1650240000, 'last_update': 1350513960, 'db_status': 'db_type_extended', 'engine': {'version': '5.
00361', 'last_update': 1529466120, 'last_update_attempt': 1555522659, 'last_update_result_status': 'update_result_no_updates', 'last_update_method_status': 'update_method_manual'}}, 'ips': {'status': 'licensed', 'version': '14.00596', 'expires': 1650240000, 'last_update'
: 1555522659, 'last_update_attempt': 1555522659, 'last_update_result_status': 'update_result_success', 'last_update_method_status': 'update_method_sched', 'db_status': 'db_type_normal', 'engine': {'version': '3.00539', 'last_update': 1541488380, 'last_update_attempt': 15
55522659, 'last_update_result_status': 'update_result_no_updates', 'last_update_method_status': 'update_method_manual'}, 'malicious_urls': {'status': 'licensed', 'version': '2.00376', 'expires': 1650240000, 'last_update': 1564724233, 'last_update_attempt': 1564760173, 'l
ast_update_result_status': 'update_result_no_updates', 'last_update_method_status': 'update_method_sched'}}, 'appctrl': {'status': 'licensed', 'version': '14.00596', 'expires': 1650240000, 'last_update': 1555522659, 'last_update_attempt': 1555522659, 'last_update_result_
status': 'update_result_success', 'last_update_method_status': 'update_method_sched'}, 'botnet_ip': {'status': 'licensed', 'version': '4.00459', 'expires': 1650240000, 'last_update': 1555522659, 'last_update_attempt': 1555522659, 'last_update_result_status': 'update_resu
lt_success', 'last_update_method_status': 'update_method_sched'}, 'botnet_domain': {'status': 'licensed', 'version': '2.00296', 'expires': 1650240000, 'last_update': 1564695434, 'last_update_attempt': 1564760173, 'last_update_result_status': 'update_result_no_updates', '
last_update_method_status': 'update_method_sched'}, 'mobile_malware': {'status': 'licensed', 'version': '70.00425', 'expires': 1650240000, 'last_update': 1564760173, 'last_update_attempt': 1564760173, 'last_update_result_status': 'update_result_success', 'last_update_met
hod_status': 'update_method_sched'}, 'internet_service_db': {'status': 'licensed', 'version': '7.00016', 'last_update': 1564695434, 'last_update_attempt': 1564760173, 'last_update_result_status': 'update_result_no_updates', 'last_update_method_status': 'update_method_sch
ed'}, 'device_os_id': {'status': 'licensed', 'version': '1.00079', 'expires': 1650240000, 'last_update': 1560793814, 'last_update_attempt': 1564760173, 'last_update_result_status': 'update_result_no_updates', 'last_update_method_status': 'update_method_sched'}, 'web_filt
ering': {'status': 'unavailable', 'category_list_version': 8}, 'antispam': {'status': 'unavailable'}, 'industrial_db': {'status': 'pending', 'version': '6.00741', 'last_update': 1448962200}, 'vdom': {'can_upgrade': False, 'used': 1, 'max': 10}, 'forticlient': {'status':
'free_license', 'can_upgrade': True, 'used': 0, 'max': 10}, 'forticloud': {'status': 'cloud_logged_out'}, 'sms': {'status': 'no_license', 'used': 0, 'max': 0}}, 'vdom': 'global', 'path': 'license', 'name': 'status', 'action': 'select', 'status': 'success', 'serial': 'FGT
60ETK18067969', 'version': 'v5.6.8', 'build': 1672}
2019-08-02 12:10:52,471 fortiosapi   DEBUG    vdom is: global
2019-08-02 12:10:52,472 fortiosapi   DEBUG    urlbuild is https://0.0.0.0/api/v2/cmdb/system/global?global=1 with crsf: {'User-Agent': 'python-requests/2.21.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'X-CSRFTOKEN': '248DF4
DA959C5DBE8FF6F723B743CF9'}
2019-08-02 12:10:52,472 fortiosapi   DEBUG    Calling GET ( https://0.0.0.0/api/v2/cmdb/system/global?global=1, None)
2019-08-02 12:10:52,575 fortiosapi   DEBUG    in GET function
2019-08-02 12:10:52,575 fortiosapi   DEBUG    formating response
2019-08-02 12:10:52,575 fortiosapi   DEBUG    response content type : application/json
2019-08-02 12:10:52,575 fortiosapi   DEBUG    Request : GET on url : https://0.0.0.0/api/v2/cmdb/system/global?global=1
2019-08-02 12:10:52,575 fortiosapi   DEBUG    Response : http code 200  reason : OK
2019-08-02 12:10:52,575 fortiosapi   DEBUG    raw response:  b'[\n  {\n    "http_method":"GET",\n    "revision":"6.0.0.2735489310.1563504401",\n    "results":{\n      "language":"english",\n      "gui-ipv6":"disable",\n      "gui-certificates":"disable",\n      "gui-cust
om-language":"disable",\n      "gui-wireless-opensecurity":"disable",\n      "gui-display-hostname":"disable",\n      "gui-lines-per-page":50,\n      "admin-https-ssl-versions":"tlsv1-1 tlsv1-2",\n      "admintimeout":5,\n      "admin-console-timeout":0,\n      "admin-co
ncurrent":"enable",\n      "admin-lockout-threshold":3,\n      "admin-lockout-duration":60,\n      "refresh":0,\n      "interval":5,\n      "failtime":5,\n      "daily-restart":"disable",\n      "restart-time":"00:00",\n      "radius-port":1812,\n      "admin-login-max":
100,\n      "remoteauthtimeout":5,\n      "ldapconntimeout":500,\n      "batch-cmdb":"enable",\n      "dst":"enable",\n      "timezone":"04",\n      "ntpserver":"",\n      "ntpsync":"disable",\n      "syncinterval":0,\n      "traffic-priority":"tos",\n      "traffic-prio
rity-level":"medium",\n      "anti-replay":"strict",\n      "send-pmtu-icmp":"enable",\n      "honor-df":"enable",\n      "revision-image-auto-backup":"disable",\n      "revision-backup-on-logout":"disable",\n      "management-vdom":"root",\n      "hostname":"7078296677_
FW55001",\n      "alias":"FGT60ETK18067969",\n      "strong-crypto":"enable",\n      "ssh-cbc-cipher":"enable",\n      "ssh-hmac-md5":"enable",\n      "ssh-kex-sha1":"enable",\n      "ssl-static-key-ciphers":"enable",\n      "snat-route-change":"disable",\n      "cli-aud
it-log":"disable",\n      "dh-params":"2048",\n      "fds-statistics":"enable",\n      "fds-statistics-period":60,\n      "multicast-forward":"enable",\n      "mc-ttl-notchange":"disable",\n      "asymroute":"disable",\n      "tcp-option":"enable",\n      "lldp-transmiss
ion":"disable",\n      "proxy-auth-timeout":300,\n      "sys-perf-log-interval":5,\n      "check-protocol-header":"loose",\n      "vip-arp-range":"restricted",\n      "reset-sessionless-tcp":"disable",\n      "allow-traffic-redirect":"enable",\n      "strict-dirty-sessio
n-check":"enable",\n      "tcp-halfclose-timer":120,\n      "tcp-halfopen-timer":10,\n      "tcp-timewait-timer":1,\n      "udp-idle-timer":180,\n      "block-session-timer":30,\n      "ip-src-port-range":"1024-25000",\n      "pre-login-banner":"enable",\n      "post-log
in-banner":"disable",\n      "tftp":"enable",\n      "av-failopen":"pass",\n      "av-failopen-session":"disable",\n      "memory-use-threshold-extreme":95,\n      "memory-use-threshold-red":88,\n      "memory-use-threshold-green":82,\n      "check-reset-range":"disable"
,\n      "vdom-admin":"disable",\n      "long-vdom-name":"disable",\n      "admin-port":80,\n      "admin-sport":443,\n      "admin-https-redirect":"enable",\n      "admin-ssh-password":"enable",\n      "admin-ssh-port":22,\n      "admin-ssh-grace-time":120,\n      "admi
n-ssh-v1":"disable",\n      "admin-telnet-port":23,\n      "admin-maintainer":"enable",\n      "admin-reset-button":"enable",\n      "admin-server-cert":"Fortinet_Factory",\n      "user-server-cert":"Fortinet_Factory",\n      "admin-https-pki-required":"disable",\n
"wifi-certificate":"Fortinet_Wifi",\n      "wifi-ca-certificate":"Fortinet_Wifi_CA",\n      "auth-http-port":1000,\n      "auth-https-port":1003,\n      "auth-keepalive":"disable",\n      "policy-auth-concurrent":0,\n      "auth-session-limit":"block-new",\n      "auth-c
ert":"Fortinet_Factory",\n      "clt-cert-req":"disable",\n      "fortiservice-port":8013,\n      "endpoint-control-portal-port":8009,\n      "endpoint-control-fds-access":"enable",\n      "tp-mc-skip-policy":"disable",\n      "cfg-save":"automatic",\n      "cfg-revert-t
imeout":600,\n      "reboot-upon-config-restore":"enable",\n      "admin-scp":"disable",\n      "fortiguard-audit-result-submission":"enable",\n      "wireless-controller":"enable",\n      "wireless-controller-port":5246,\n      "fortiextender-data-port":25246,\n      "f
ortiextender":"disable",\n      "fortiextender-vlan-mode":"disable",\n      "switch-controller":"disable",\n      "switch-controller-reserved-network":"169.254.0.0 255.255.0.0",\n      "proxy-worker-count":2,\n      "scanunit-count":4,\n      "proxy-kxp-hardware-accelera
tion":"enable",\n      "proxy-cipher-hardware-acceleration":"enable",\n      "fgd-alert-subscription":"",\n      "ipsec-hmac-offload":"enable",\n      "ipv6-accept-dad":1,\n      "ipv6-allow-anycast-probe":"disable",\n      "csr-ca-attribute":"enable",\n      "wimax-4g-u
sb":"disable",\n      "cert-chain-max":8,\n      "sslvpn-max-worker-count":3,\n      "sslvpn-kxp-hardware-acceleration":"enable",\n      "sslvpn-cipher-hardware-acceleration":"enable",\n      "sslvpn-plugin-version-check":"enable",\n      "two-factor-ftk-expiry":60,\n
   "two-factor-email-expiry":60,\n      "two-factor-sms-expiry":60,\n      "two-factor-fac-expiry":60,\n      "two-factor-ftm-expiry":72,\n      "virtual-server-count":2,\n      "virtual-server-hardware-acceleration":"enable",\n      "wad-worker-count":4,\n      "login-t
imestamp":"disable",\n      "miglogd-children":0,\n      "special-file-23-support":"disable",\n      "log-uuid":"policy-only",\n      "log-ssl-connection":"disable",\n      "arp-max-entry":131072,\n      "ndp-max-entry":0,\n      "br-fdb-max-entry":8192,\n      "max-rout
e-cache-size":0,\n      "ipsec-asic-offload":"enable",\n      "device-idle-timeout":300,\n      "device-identification-active-scan-delay":90,\n      "compliance-check":"enable",\n      "compliance-check-time":"00:00:00",\n      "gui-device-latitude":"",\n      "gui-devic
e-longitude":"",\n      "private-data-encryption":"disable",\n      "auto-auth-extension-device":"enable",\n      "gui-theme":"green",\n      "igmp-state-limit":3200\n    },\n    "vdom":"root",\n    "path":"system",\n    "name":"global",\n    "status":"success",\n    "ht
tp_status":200,\n    "serial":"FGT60ETK18067969",\n    "version":"v5.6.8",\n    "build":1672\n  }\n]'
2019-08-02 12:10:52,662 fortiosapi   DEBUG    response content type : text/html; charset=utf-8
2019-08-02 12:10:52,662 fortiosapi   DEBUG    Request : POST on url : https://0.0.0.0/logout
2019-08-02 12:10:52,662 fortiosapi   DEBUG    Response : http code 200  reason : OK
2019-08-02 12:10:52,662 fortiosapi   DEBUG    raw response:  b'<script language="javascript">\ntop.location="/login";\n</script>\n'

fortiosapi ssh implementation

Good day!

Let's discuss the destiny of the following method:

def ssh(cmds, host, user, password=None, port=22):
"""
DEPRECATED use paramiko directly.
Send a multi line string via ssh to the fortigate

Could you clarify me the purpose for Deprecated comment in this method? Does it state the method is no longer supported?
The reason for the clarification is the bug in this method, so I really do not know what to do...

Disable SSL verification not working in 1.0.1

FortiOS API: 1.0.1
Python: 2.7.5
Ansible: 2.8.2
Ansible Module: fortios
OS: CentOS 7.6.1810

I was not able to connect to a lab FortiGate running 5.6.8 and a self-signed certificate due to this error:

fatal: [localhost -> localhost]: FAILED! => {"changed": false, "module_stderr": "No handlers could be found for logger "fortiosapi"\nTraceback (most recent call last):\n File "/home/user.name/.ansible/tmp/ansible-tmp-1566238292.13-228453108213076/AnsiballZ_fortios_system_accprofile.py", line 114, in \n _ansiballz_main()\n File "/home/user.name/.ansible/tmp/ansible-tmp-1566238292.13-228453108213076/AnsiballZ_fortios_system_accprofile.py", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File "/home/user.name/.ansible/tmp/ansible-tmp-1566238292.13-228453108213076/AnsiballZ_fortios_system_accprofile.py", line 49, in invoke_module\n imp.load_module('main', mod, module, MOD_DESC)\n File "/tmp/ansible_fortios_system_accprofile_payload_nhat_l/main.py", line 730, in \n File "/tmp/ansible_fortios_system_accprofile_payload_nhat_l/main.py", line 721, in main\n File "/tmp/ansible_fortios_system_accprofile_payload_nhat_l/main.py", line 584, in fortios_system\n File "/tmp/ansible_fortios_system_accprofile_payload_nhat_l/main.py", line 530, in login\n File "/usr/lib/python2.7/site-packages/fortiosapi/fortiosapi.py", line 170, in login\n data='username=' + urllib.parse.quote(username) + '&secretkey=' + urllib.parse.quote(password) + "&ajax=1", timeout=self.timeout)\n File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 555, in post\n return self.request('POST', url, data=data, json=json, **kwargs)\n File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 508, in request\n resp = self.send(prep, **send_kwargs)\n File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 618, in send\n r = adapter.send(request, **kwargs)\n File "/usr/lib/python2.7/site-packages/requests/adapters.py", line 506, in send\n raise SSLError(e, request=request)\nrequests.exceptions.SSLError: HTTPSConnectionPool(host='labfirewall.domain.com', port=443): Max retries exceeded with url: /logincheck (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:618)'),))\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

I played around with the fortiosapi.py script a bit trying to override that, but ultimately the only way I found that works was to:

  1. Open file fortiosapi.py
    E.g. : /usr/lib/python2.7/site-packages/fortiosapi/fortiosapi.py

  2. Go to line 171 :

data='username=' + urllib.parse.quote(username) + '&secretkey=' + urllib.parse.quote(password) + "&ajax=1", timeout=self.timeout)

  1. Add ", verify=False" to the end of those parameters :

data='username=' + urllib.parse.quote(username) + '&secretkey=' + urllib.parse.quote(password) + "&ajax=1", timeout=self.timeout, verify=False)

  1. Test playbook

It appears two things are true:

  1. Overriding "verify = " earlier in the script does not work as it should
  2. There is no ability to specify to ignore cert errors or not, via a playbook.

fortiosapi: update_cookie issue since upgrade from 7.0.12 to 7.2.6

Since the fortigate upgrade from 7.0.12 to 7.2.6 we noticed a problem with fortiosapi.

When creating an address we now get a 403 error.
we use https port 10443

the name of the Cookie is not
'ccsrftoken'
but
'ccsrftoken_10443'

the result of this is that the session header does not have an X-CSRFTOKEN.

As a workaround, I adjusted the update_cookie routine:

if cookie.name == 'ccsrftoken':
changed to
if cookie.name == 'ccsrftoken' or cookie.name == 'ccsrftoken_10443':

now it works for me....

KeyError: 'vm'

Hello,

I got the error:

if resp['results']['vm']['status'] == "vm_valid" or "vm_eval":
KeyError: 'vm'

But I have the firmware version 5.6.2. Any idea what could be the problem?

Error creating groups

Hi all!
I have a problem with the fortiosapi.
When I try to create a group with the new fortiosapi version, I receive the follow message:

Creating groups and objects for category test

Processing group 1 (0 to 500) ...

No handlers could be found for logger "fortiosapi"

And the group is not created.

I've revised the script but I can't found the error.

Can someone help me?
Thank you so much

Fortiosapi no longer installs dependencies

In version 0.10.5 if you issue a command pip install fortiosapi (or issue pip install fortiosapi=0.10.5) it will install the dependencies such as requests etc... if you remove fortiosapi and all dependencies and then install fortiosapi version 0.10.7 via pip it no longer installs the dependencies.

UnicodeDecodeError at login

This happens when the default system proxy gets used with does not allow the request to the fortimanager, but returns an error message page. There should be an error handing. running on Fedora 27 with python 2.7.14

$ python testlogin.py 
Traceback (most recent call last):
  File "testlogin.py", line 35, in <module>
    main()
  File "testlogin.py", line 28, in main
    resp = fgt.login(fgthost, user, passwd)
  File "xxxxxxx/fortinet/fortiosapi/fortiosapi.py", line 123, in login
    if res.content.decode('ascii')[0] == '1':
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5337: ordinal not in range(128)

KeyError: 'results'

Hello,

I get this error messege:

if resp['results']['vm']['status'] == "vm_valid" or "vm_eval":
KeyError: 'results'

This is my example code to reproduce the error:

#!/usr/bin/python

from fortiosapi import FortiOSAPI

FGT_HOST='192.168.122.40'
FGT_USER='admin'
FGT_PASSWORD=''


fosapi = FortiOSAPI()
fosapi.https('on')
fosapi.login(FGT_HOST, FGT_USER, FGT_PASSWORD)

print(fosapi.license())

fosapi.logout()

I use the Fortigate-60D with the Firmware v.5.2.11 and fortisapi with 0.9.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.