Exemple #1
0
def portConfig(ctx, **kwargs):

    ctx.logger.info('Start port config task....')

    templatePortConfig = ctx.get_resource(TEMPLATE_CONFIG_FILE)
    ctx.download_resource(templatePortConfig, TMP_CONFIG_FILE)

    forti_host = inputs['fortinet_host']
    forti_username = inputs['fortinet_user']
    forti_password = inputs['fortinet_password']

    portnum = inputs['test_port_number']
    portip = inputs['test_ce_port']
    portmask = '255.255.255.0'
    aliasname = 'Internal'

    f = open(TMP_CONFIG_FILE, 'r+')
    clean = f.read().replace(portIdToSearch, portnum).replace(
        portIpToSearch,
        portip).replace(portMaskToSearch,
                        portmask).replace(portAliasToSearch, aliasname)
    f.write(clean)

    portConf = ctx.get_resource(TMP_CONFIG_FILE)
    ctx.logger.info('New file to execute {0} '.format(portConf))

    ctx.logger.info('Open connection to host {0} '.format(forti_host))
    conn = FortiOS(forti_host,
                   username=forti_username,
                   password=forti_password)
    conn.open()

    execCmd(ctx, conn, portConf)
Exemple #2
0
def portConfig(ctx, **kwargs):

    ctx.logger.info('Start port config task....')

    templatePortConfig=ctx.get_resource(TEMPLATE_CONFIG_FILE)
    ctx.download_resource(templatePortConfig, TMP_CONFIG_FILE)

    forti_host = inputs['fortinet_host']
    forti_username = inputs['fortinet_user']
    forti_password = inputs['fortinet_password']

    portnum = inputs['test_port_number']
    portip = inputs['test_ce_port']
    portmask = '255.255.255.0'
    aliasname = 'Internal'

    f  = open(TMP_CONFIG_FILE, 'r+')
    clean  = f.read().replace(portIdToSearch, portnum).replace(portIpToSearch, portip).replace(portMaskToSearch, portmask).replace(portAliasToSearch, aliasname)
    f.write(clean)

    portConf=ctx.get_resource(TMP_CONFIG_FILE)
    ctx.logger.info('New file to execute {0} '.format(portConf))

    ctx.logger.info('Open connection to host {0} '.format(forti_host))
    conn = FortiOS(forti_host, username=forti_username, password=forti_password)
    conn.open()

    execCmd(ctx,conn,portConf)
    def _connect(self):
        if self.module.params['file_mode']:
            self.forti_device = FortiOS('')
        else:
            host = self.module.params['host']
            username = self.module.params['username']
            password = self.module.params['password']
            timeout = self.module.params['timeout']
            vdom = self.module.params['vdom']

            self.forti_device = FortiOS(host, username=username, password=password, timeout=timeout, vdom=vdom)

            try:
                self.forti_device.open()
            except Exception as e:
                self.module.fail_json(msg='Error connecting device. %s' % to_text(e),
                                      exception=traceback.format_exc())
def exec_command(ctx, command, fortinet_host_ip):

    ctx.logger.info('Open connection to host {0} '.format(fortinet_host_ip))
    conn = FortiOS(fortinet_host_ip, username=forti_username, password=forti_password)
    conn.open()

    ctx.logger.info("Execute Command >> \n {0}".format(command))

    conn.execute_command(command)
    conn.close()
Exemple #5
0
    def _connect(self):
        host = self.module.params['host']
        username = self.module.params['username']
        password = self.module.params['password']
        timeout = self.module.params['timeout']
        vdom = self.module.params['vdom']

        self.forti_device = FortiOS(host,
                                    username=username,
                                    password=password,
                                    timeout=timeout,
                                    vdom=vdom)

        try:
            self.forti_device.open()
        except Exception:
            e = get_exception()
            self.module.fail_json(msg='Error connecting device. %s' % e)
Exemple #6
0
class SkyBetFG:
  verbose = True
  fg = None
  username = None
  password=None
  dry_run=None
  d = None
  vdom = None
  current_config = None
  candidate_config = None
  running_config = {}

  def __init__(self, hostname=None, username=None, password=None, vdom=None, verbose=True, dry_run=False):
    self.fg = hostname
    self.username = username
    self.password = password
    self.verbose = verbose
    self.dry_run = dry_run
    self.vdom = vdom

    if verbose: print "Connecting to %s on vdom %s" % (hostname, vdom)
    self.d = FortiOS(self.fg, username=self.username, password=self.password, vdom=vdom)
    self.d.open()
    self.current_config = self.d.running_config.to_text()

#    for section in ['system interface', 'firewall policy', 'firewall address', 'firewall addrgrp']:
#      if section in dev.running_config[section]:
#        self.running_config[section] = dev.running_config[section]

  def _fg(self):
    return self.d

  def commit(self):
    d = self.d

    changes = d.compare_config(text=True)
    if self.verbose or self.dry_run: print changes
    if self.dry_run: return True
    try:
      d.commit()
    except pyFG.exceptions.FailedCommit, e:
      pprint(e)

    d.close()
Exemple #7
0
  def __init__(self, hostname=None, username=None, password=None, vdom=None, verbose=True, dry_run=False):
    self.fg = hostname
    self.username = username
    self.password = password
    self.verbose = verbose
    self.dry_run = dry_run
    self.vdom = vdom

    if verbose: print "Connecting to %s on vdom %s" % (hostname, vdom)
    self.d = FortiOS(self.fg, username=self.username, password=self.password, vdom=vdom)
    self.d.open()
    self.current_config = self.d.running_config.to_text()
def exec_command(ctx, command, fortinet_host_ip):

    ctx.logger.info('Open connection to host {0} '.format(fortinet_host_ip))
    conn = FortiOS(fortinet_host_ip, username=forti_username, password=forti_password)
    conn.open()

    ctx.logger.info("Execute Command >> \n {0}".format(command))

    conn.execute_command(command)
    conn.close()
Exemple #9
0
def set_port(ctx, fortinet_host_ip, target_ip, port_id, port_alias):
    ctx.logger.info('Configure fw port ....')

    ctx.logger.info('Open connection to host {0} '.format(fortinet_host_ip))
    conn = FortiOS(fortinet_host_ip,
                   username=forti_username,
                   password=forti_password)
    conn.open()

    command = \
        'config system interface\n' \
        '   edit port%s\n' \
        '       set mode static\n' \
        '       set allowaccess ping\n' \
        '       set alias %s\n' \
        '       set ip %s  %s\n' \
        '   next\n' \
        'end' % (port_id, port_alias, target_ip, portMask)

    ctx.logger.info(">>:\n {0}".format(command))

    conn.execute_command(command)
    conn.close()
Exemple #10
0
def set_policy(ctx, fortinet_host_ip):
    ctx.logger.info('Open connection to host {0} '.format(fortinet_host_ip))
    conn = FortiOS(fortinet_host_ip,
                   username=forti_username,
                   password=forti_password)
    conn.open()

    command = \
        'config firewall policy\n' \
        '  edit 1\n' \
        '    set srcintf \"any\"\n' \
        '    set dstintf \"any\"\n' \
        '    set srcaddr \"all\"\n' \
        '    set dstaddr \"all\"\n' \
        '    set action accept\n' \
        '    set schedule \"always\"\n' \
        '    set service \"ALL\"\n' \
        '  next\n' \
        'end'

    ctx.logger.info(">>:\n {0}".format(command))

    conn.execute_command(command)
    conn.close()
Exemple #11
0
passwd = args['passwd']
file = args['file']
vdom = args['vdom']
'''
host = sys.argv[1]
vdom = sys.argv[2]
file = sys.argv[3]
user = sys.argv[4]
passwd = sys.argv[5]
'''

if __name__ == '__main__':

    #	try:

    d = FortiOS(hostname=host, vdom=vdom, username=user, password=passwd)
    d.open()

    d.load_config(empty_candidate=False)

    results = {}
    results['changed'] = False

    with open(file, "r") as c_file:
        data = c_file.read()

    d.load_config(config_text=data, in_candidate=True)

    regexp = re.compile('^(config |edit |set |delete |end$|next$)(.*)')
    current_block = d.candidate_config
    if isinstance(data, py23_compat.string_types):
Exemple #12
0
#!/usr/bin/env python

# Gets router bgp config from the device, then do some changes to the BGP parameters, deletes a neighbor,
# creates a new one, modifies another and computes the difference

from pyFG import FortiOS, FortiConfig
import sys

if __name__ == '__main__':
    hostname = sys.argv[1]

    d = FortiOS(hostname, vdom='vpn')
    d.open()
    d.load_config('router bgp')

    new_neigh = FortiConfig('10.6.6.8', 'edit')
    new_neigh.set_param('remote-as', '123')
    new_neigh.set_param('remotas', '123')
    d.candidate_config['router bgp']['neighbor'].set_block(new_neigh)
    d.candidate_config['router bgp']['neighbor']['10.6.6.6'].set_param(
        'remote-as', '444')
    d.candidate_config['router bgp']['neighbor'].del_block('10.6.6.7')

    print "This is the diff of the configs:"
    for line in d.compare_config(text=True):
        print line

    print "This is how to reach the desired state:"
    config_changes = d.compare_config()
    print config_changes
Exemple #13
0
#!/usr/bin/env python

# Gets router bgp config from the device, then do some changes to the BGP parameters, deletes a neighbor,
# creates a new one, modifies another and computes the difference

from pyFG import FortiOS, FortiConfig
import sys

if __name__ == '__main__':
    hostname = sys.argv[1]

    d = FortiOS(hostname, vdom='vpn')
    d.open()
    d.load_config('router bgp')

    new_neigh = FortiConfig('10.6.6.8', 'edit')
    new_neigh.set_param('remote-as', '123')
    new_neigh.set_param('remotas', '123')
    d.candidate_config['router bgp']['neighbor'].set_block(new_neigh)
    d.candidate_config['router bgp']['neighbor']['10.6.6.6'].set_param('remote-as', '444')
    d.candidate_config['router bgp']['neighbor'].del_block('10.6.6.7')


    print "This is the diff of the configs:"
    for line in d.compare_config(text=True):
        print line

    print "This is how to reach the desired state:"
    config_changes = d.compare_config()
    print config_changes
def main():
    argument_spec = dict(
        src=dict(type='str', default=None),
        filter=dict(type='str', default=""),
    )

    argument_spec.update(fortios_argument_spec)

    required_if = fortios_required_if

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=required_if,
    )

    result = dict(changed=False)

    # fail if pyFG not present
    if not HAS_PYFG:
        module.fail_json(
            msg=
            'Could not import the python library pyFG required by this module')

    #define device
    f = FortiOS(
        module.params['host'],
        username=module.params['username'],
        password=module.params['password'],
    )

    #connect
    try:
        f.open()
    except:
        module.fail_json(msg='Error connecting device')

    # get info
    facts = dict()

    facts['all_ipv4_addresses'] = list()

    interfaces = f.execute_command('get system interface')
    for interface in interfaces:
        if re.search('name:', interface):
            if re.search('0.0.0.0 0.0.0.0', interface) == None:
                ipv4_address = re.match(
                    '.*ip:\s([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})',
                    interface).group(1)
                facts['all_ipv4_addresses'].append(ipv4_address)

    #facts['all_ipv6_addresses'] = list()
    #facts['apparmor'] = dict()
    #facts['architecture'] = ''
    #facts['bios_date'] =''
    #facts['bios_version'] = ''
    #facts['date_time'] = dict()

    # get interface of default route
    defaultInterface = re.match(
        '.*,\s+(.*)$',
        f.execute_command('get router info routing-table all | grep 0.0.0.0')
        [0].lstrip()).group(1)

    # convert ppp1 to pppoe
    if re.match('ppp', defaultInterface):
        defaultInterface = 'pppoe'

    # get interface's info which is used on default route
    interfaces = f.execute_command('get system interface | grep ' +
                                   defaultInterface)

    for interface in interfaces:
        if re.search('status: up', interface) and re.search(
                defaultInterface, interface):
            default_ipv4_address = re.match(
                '.*ip:\s([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})',
                interface).group(1)

    facts['default_ipv4'] = dict()
    facts['default_ipv4'].update({'address': default_ipv4_address})
    facts['default_ipv4'].update({'interface': defaultInterface})

    #facts['default_ipv6'] = dict()

    # Version: Fortigate-50B v4.0,build0665,130514 (MR3 Patch 14)
    distribution_major_version = re.match(
        'Version:\s.*\s(.*),build',
        f.execute_command('get system status | grep Version')
        [0].lstrip()).group(1)
    distribution_version = re.match(
        'Version:\s.*\((.*)\)',
        f.execute_command('get system status | grep Version')
        [0].lstrip()).group(1)
    facts['distribution'] = 'FortiOS'
    facts['distribution_major_version'] = distribution_major_version
    facts[
        'distribution_version'] = distribution_major_version + ' ' + distribution_version

    #dns = f.execute_command('get system dns')[]

    #facts['dns'] = dict()
    #facts['domain'] = ''

    hostname = re.match(
        'Hostname:\s(.*)',
        f.execute_command('get system status | grep Hostname')
        [0].lstrip()).group(1)
    facts['fqdn'] = hostname
    facts['hostname'] = hostname

    #facts['interfaces'] = list()
    #facts['ip_addresses'] = list()
    #facts['kernel'] = ''
    #facts['lastboot'] = ''
    #facts['machine'] = ''
    #facts['machine_id'] = ''
    #facts['memfree_mb'] = ''

    memfree_mb = re.match(
        'Mem:\s*([0-9]*)\s*([0-9]*)\s*([0-9]*)',
        f.execute_command('diagnose hardware sysinfo memory | grep Mem:')
        [0].lstrip()).group(3)
    memfree_mb = math.floor(int(memfree_mb) / 1024 / 1024)
    facts['memfree_mb'] = memfree_mb

    memtotal_mb = re.match(
        'Mem:\s*([0-9]*)\s*([0-9]*)\s*([0-9]*)',
        f.execute_command('diagnose hardware sysinfo memory | grep Mem:')
        [0].lstrip()).group(1)
    memtotal_mb = math.floor(int(memtotal_mb) / 1024 / 1024)
    facts['memtotal_mb'] = memtotal_mb

    #facts['mounts'] = list()
    #facts['nodename'] = ''
    facts['os_family'] = 'FortiOS'

    results = f.execute_command('get hardware cpu')
    i = 0
    for result in results:
        if re.match('[pP]rocessor\s*:\s*(.*)', result.lstrip()) != None:
            i = i + 1

    #facts['processor'] = list()
    #facts['processor_cores'] = 0
    #facts['processor_count'] = 0
    #facts['processor_threads_per_core'] = 0
    facts['processor_vcpus'] = i

    product_name = re.match(
        'Version:\s(.*)\sv',
        f.execute_command('get system status | grep Version')
        [0].lstrip()).group(1)
    facts['product_name'] = product_name

    product_serial = re.match(
        'Serial-Number:\s(.*)',
        f.execute_command('get system status | grep Serial')
        [0].lstrip()).group(1)
    facts['product_serial'] = product_serial
    #facts['swapfree_mb'] = 0
    #facts['swaptotal_mb'] =  0
    #facts['system'] = "Win32NT"
    facts['system_vendor'] = "Fortinet"
    #facts['uptime_seconds'] = 767400
    facts['module_setup'] = True

    ansible_facts = dict()
    for key, value in iteritems(facts):
        key = 'ansible_%s' % key
        ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts)
Exemple #15
0
#!/usr/bin/env python

# Gets router bgp config from the device, then do some changes to the BGP parameters, deletes a neighbor,
# creates a new one, modifies another and computes the difference

from pyFG import FortiOS, FortiConfig

if __name__ == '__main__':
    f = open('running.conf', 'r')
    running = f.read()
    f.close()

    d = FortiOS('')
    d.load_config(config_text=running)

    d.candidate_config['router bgp'].set_param('as', 123)
    d.candidate_config['router bgp']['neighbor']['10.240.4.3'].set_param(
        'bfd', 'disable')
    d.candidate_config['router bgp']['neighbor'].del_block('10.240.4.24')

    new_neigh = FortiConfig('10.6.6.6', 'edit')
    new_neigh.set_param('as', '666')
    new_neigh.set_param('route-map-out', 'my_route_map')
    new_neigh.set_param('update-source', 'port6')
    new_neigh.set_param('bfd', 'enable')
    d.candidate_config['router bgp']['neighbor'].set_block(new_neigh)

    print "This is the diff of the conigs:"
    for line in d.compare_config(text=True):
        print line
Exemple #16
0
#!/usr/bin/env python

#Gets router bgp config from the device, then loads a file with the new bgp config we want and we
#compute the difference

from pyFG import FortiOS
import sys

if __name__ == '__main__':
    f = open('candidate.conf', 'r')
    candidate = f.read()
    f.close()

    hostname = sys.argv[1]

    d = FortiOS(hostname, vdom='vpn')
    d.open()
    d.load_config('router bgp', empty_candidate=True)
    d.load_config(config_text=candidate, in_candidate=True)
    d.close()

    print "This is the diff of the conigs:"
    for line in d.compare_config(text=True):
        print line

    print "\n\n"
    print "This is how to reach the desired state:"
    print d.compare_config()
Exemple #17
0
#!/usr/bin/env python
# Gets the entire config and prints it

from pyFG import FortiOS
import sys

if __name__ == '__main__':
    hostname = sys.argv[1]

    d = FortiOS(hostname, vdom='vpn')
    d.open()
    d.load_config('router bgp')
    d.close()
    print d.running_config.to_text()
def main():
    argument_spec = dict(
        src=dict(type='str', default=None),
        filter=dict(type='str', default=""),
    )

    argument_spec.update(fortios_argument_spec)

    required_if = fortios_required_if

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=required_if,
    )

    result = dict(changed=False)

    # fail if pyFG not present
    if not HAS_PYFG:
        module.fail_json(msg='Could not import the python library pyFG required by this module')

    # define device
    f = FortiOS(module.params['host'],
                username=module.params['username'],
                password=module.params['password'],
                timeout=module.params['timeout'],
                vdom=module.params['vdom'])

    # connect
    try:
        f.open()
    except:
        module.fail_json(msg='Error connecting device')

    # get  config
    try:
        f.load_config(path=module.params['filter'])
        result['running_config'] = f.running_config.to_text()

    except:
        module.fail_json(msg='Error reading running config')

    # backup config
    if module.params['backup']:
        backup(module, f.running_config.to_text())

    # update config
    if module.params['src'] is not None:
        # store config in str
        try:
            conf_str = module.params['src']
            f.load_config(in_candidate=True, config_text=conf_str)
        except:
            module.fail_json(msg="Can't open configuration file, or configuration invalid")

        # get updates lines
        change_string = f.compare_config()

        # remove not updatable parts
        c = FortiConfig()
        c.parse_config_output(change_string)

        for o in NOT_UPDATABLE_CONFIG_OBJECTS:
            c.del_block(o)

        change_string = c.to_text()

        if change_string != "":
            result['change_string'] = change_string
            result['changed'] = True

        # Commit if not check mode
        if module.check_mode is False and change_string != "":
            try:
                f.commit(change_string)
            except CommandExecutionException as e:
                module.fail_json(msg="Unable to execute command, check your args, the error was {0}".format(e.message))
            except FailedCommit as e:
                module.fail_json(msg="Unable to commit, check your args, the error was {0}".format(e.message))
            except ForcedCommit as e:
                module.fail_json(msg="Failed to force commit, check your args, the error was {0}".format(e.message))

    module.exit_json(**result)
Exemple #19
0
#!/usr/bin/env python

# Gets router bgp config from the device, then do some changes to the BGP parameters, deletes a neighbor,
# creates a new one, modifies another and computes the difference

from pyFG import FortiOS, FortiConfig

if __name__ == '__main__':
    f = open('running.conf', 'r')
    running = f.read()
    f.close()

    d = FortiOS('')
    d.load_config(config_text=running)

    d.candidate_config['router bgp'].set_param('as', 123)
    d.candidate_config['router bgp']['neighbor']['10.240.4.3'].set_param('bfd', 'disable')
    d.candidate_config['router bgp']['neighbor'].del_block('10.240.4.24')

    new_neigh = FortiConfig('10.6.6.6', 'edit')
    new_neigh.set_param('as', '666')
    new_neigh.set_param('route-map-out', 'my_route_map')
    new_neigh.set_param('update-source', 'port6')
    new_neigh.set_param('bfd', 'enable')
    d.candidate_config['router bgp']['neighbor'].set_block(new_neigh)

    print "This is the diff of the conigs:"
    for line in d.compare_config(text=True):
        print line

    print "\n\n"
Exemple #20
0
class AnsibleFortios(object):
    def __init__(self, module):
        if not HAS_PYFG:
            module.fail_json(
                msg=
                'Could not import the python library pyFG required by this module'
            )

        self.result = {
            'changed': False,
        }
        self.module = module

    def _connect(self):
        if self.module.params['file_mode']:
            self.forti_device = FortiOS('')
        else:
            host = self.module.params['host']
            username = self.module.params['username']
            password = self.module.params['password']
            timeout = self.module.params['timeout']
            vdom = self.module.params['vdom']

            self.forti_device = FortiOS(host,
                                        username=username,
                                        password=password,
                                        timeout=timeout,
                                        vdom=vdom)

            try:
                self.forti_device.open()
            except Exception as e:
                self.module.fail_json(msg='Error connecting device. %s' %
                                      to_text(e),
                                      exception=traceback.format_exc())

    def load_config(self, path):
        self.path = path
        self._connect()
        # load in file_mode
        if self.module.params['file_mode']:
            try:
                f = open(self.module.params['config_file'], 'r')
                running = f.read()
                f.close()
            except IOError as e:
                self.module.fail_json(
                    msg='Error reading configuration file. %s' % to_text(e),
                    exception=traceback.format_exc())
            self.forti_device.load_config(config_text=running, path=path)

        else:
            # get  config
            try:
                self.forti_device.load_config(path=path)
            except Exception as e:
                self.forti_device.close()
                self.module.fail_json(msg='Error reading running config. %s' %
                                      to_text(e),
                                      exception=traceback.format_exc())

        # set configs in object
        self.result[
            'running_config'] = self.forti_device.running_config.to_text()
        self.candidate_config = self.forti_device.candidate_config

        # backup if needed
        if self.module.params['backup']:
            backup(self.module, self.forti_device.running_config.to_text())

    def apply_changes(self):
        change_string = self.forti_device.compare_config()
        if change_string:
            self.result['change_string'] = change_string
            self.result['changed'] = True

        # Commit if not check mode
        if change_string and not self.module.check_mode:
            if self.module.params['file_mode']:
                try:
                    f = open(self.module.params['config_file'], 'w')
                    f.write(self.candidate_config.to_text())
                    f.close()
                except IOError as e:
                    self.module.fail_json(
                        msg='Error writing configuration file. %s' %
                        to_text(e),
                        exception=traceback.format_exc())
            else:
                try:
                    self.forti_device.commit()
                except FailedCommit as e:
                    # Something's wrong (rollback is automatic)
                    self.forti_device.close()
                    error_list = self.get_error_infos(e)
                    self.module.fail_json(
                        msg_error_list=error_list,
                        msg=
                        "Unable to commit change, check your args, the error was %s"
                        % e.message)

                self.forti_device.close()
        self.module.exit_json(**self.result)

    def del_block(self, block_id):
        self.forti_device.candidate_config[self.path].del_block(block_id)

    def add_block(self, block_id, block):
        self.forti_device.candidate_config[self.path][block_id] = block

    def get_error_infos(self, cli_errors):
        error_list = []
        for errors in cli_errors.args:
            for error in errors:
                error_code = error[0]
                error_string = error[1]
                error_type = fortios_error_codes.get(error_code, "unknown")
                error_list.append(
                    dict(error_code=error_code,
                         error_type=error_type,
                         error_string=error_string))

        return error_list

    def get_empty_configuration_block(self, block_name, block_type):
        return FortiConfig(block_name, block_type)
Exemple #21
0
#!/usr/bin/env python
# Gets the router bgp config and prints it

from pyFG import FortiOS
import sys

if __name__ == "__main__":
    hostname = sys.argv[1]

    d = FortiOS(hostname, vdom="vpn")
    d.open()
    d.load_config("router bgp")
    d.close()

    for neighbor, config in d.running_config["router bgp"]["neighbor"].iterblocks():
        print neighbor
        print "   AS: %s" % config.get_param("remote-as")
        print "   route-map-out: %s" % config.get_param("route-map-out")
        print "   route-map-in: %s" % config.get_param("route-map-in")
def main():
    argument_spec = dict(
        src=dict(type='str', default=None),
        filter=dict(type='str', default=""),
    )

    argument_spec.update(fortios_argument_spec)

    required_if = fortios_required_if

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=required_if,
    )

    result = dict(changed=False)

    # fail if pyFG not present
    if not HAS_PYFG:
        module.fail_json(
            msg=
            'Could not import the python library pyFG required by this module')

    #define device
    f = FortiOS(module.params['host'],
                username=module.params['username'],
                password=module.params['password'],
                timeout=module.params['timeout'],
                vdom=module.params['vdom'])

    #connect
    try:
        f.open()
    except:
        module.fail_json(msg='Error connecting device')

    #get  config
    try:
        f.load_config(path=module.params['filter'])
        result['running_config'] = f.running_config.to_text()

    except:
        module.fail_json(msg='Error reading running config')

    #backup config
    if module.params['backup']:
        backup(module, f.running_config.to_text())

    #update config
    if module.params['src'] is not None:
        #store config in str
        try:
            conf_str = module.params['src']
            f.load_config(in_candidate=True, config_text=conf_str)
        except:
            module.fail_json(
                msg="Can't open configuration file, or configuration invalid")

        #get updates lines
        change_string = f.compare_config()

        #remove not updatable parts
        c = FortiConfig()
        c.parse_config_output(change_string)

        for o in NOT_UPDATABLE_CONFIG_OBJECTS:
            c.del_block(o)

        change_string = c.to_text()

        if change_string != "":
            result['change_string'] = change_string
            result['changed'] = True

        #Commit if not check mode
        if module.check_mode is False and change_string != "":
            try:
                f.commit(change_string)
            except CommandExecutionException as e:
                module.fail_json(
                    msg=
                    "Unable to execute command, check your args, the error was {0}"
                    .format(e.message))
            except FailedCommit as e:
                module.fail_json(
                    msg="Unable to commit, check your args, the error was {0}".
                    format(e.message))
            except ForcedCommit as e:
                module.fail_json(
                    msg=
                    "Failed to force commit, check your args, the error was {0}"
                    .format(e.message))

    module.exit_json(**result)
Exemple #23
0
#!/usr/bin/env python
# Gets the entire config and prints it

from pyFG import FortiOS
import sys


if __name__ == '__main__':
    hostname = sys.argv[1]

    d = FortiOS(hostname, vdom='vpn')
    d.open()
    d.load_config('router bgp')
    d.close()
    print d.running_config.to_text()