Пример #1
0
  def add_group(self, **cfg):
    section='user group'
    name = cfg['name']
    new_userg = FortiConfig(config_type='edit', name=cfg['name'])

    new_userg.set_param('member', quote(cfg['group_members']))

    self.d.load_config(section)
    self.d.candidate_config[section][name] = new_userg
Пример #2
0
  def add_interface(self, **cfg):
    section='system interface'
    new_int = FortiConfig(config_type='edit', name=cfg['name'])
    name = cfg['name']
    del cfg['name']

    for e in cfg:
      new_int.set_param(e, cfg[e])

    self.d.candidate_config[section][name] = new_int
Пример #3
0
  def add_static_route(self, name=None, gateway = None, dst = None, device = None, vdom=None, comment = None):
    section = 'router static'
    new_r = FortiConfig(config_type='edit', name=name)

    if gateway: new_r.set_param('gateway', gateway)
    if comment: new_r.set_param('comment', comment)
    new_r.set_param('device', device)
    new_r.set_param('dst', dst)

    self.d.load_config(section)
    self.d.candidate_config[section][name] = new_r
Пример #4
0
  def add_user(self, **cfg):
    section='user local'
    name = cfg['name']
    new_user = FortiConfig(config_type='edit', name=cfg['name'])

    new_user.set_param('passwd', cfg['passwd'])
    new_user.set_param('email-to', cfg['email'])
    new_user.set_param('type', cfg['type'])

    self.d.load_config(section)
    self.d.candidate_config[section][name] = new_user
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)
Пример #6
0
 def get_empty_configuration_block(self, block_name, block_type):
     return FortiConfig(block_name, block_type)
Пример #7
0
            continue
        if 'snmp-index' in line:
            continue
        line = line.strip()
        result = regexp.match(line)

        #print 'check result'

        if result is not None:
            action = result.group(1).strip()
            detail = result.group(2).strip()

            if action == 'config' or action == 'edit':
                detail = detail.replace('"', '')
                if detail not in current_block.get_block_names():
                    config_block = FortiConfig(detail, action, current_block)
                    current_block[detail] = config_block
                else:
                    config_block = current_block[detail]
                current_block = config_block
                #print current_block.to_text()
                results['current_block'] = current_block.to_text()
            elif action == 'end' or action == 'next':
                current_block = current_block.get_parent()
            elif action == 'delete':
                current_block.del_block(detail)
                #print current_block.to_text()
                results['current_block'] = current_block.to_text()

    #print d.candidate_config.to_text()
Пример #8
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
Пример #9
0
  def add_fw_vip(self, name = None, vdom='root', extip = None, 
      protocol = None,
      extintf = 'any', portforward=None, mappedip = None, 
      extport = None, mappedport = None, comment = None):

    if not name: return None
    section = 'firewall vip'
    new_vip = FortiConfig(config_type='edit', name=name)
    new_vip.set_param('extip', extip)
    new_vip.set_param('extintf', extintf)
    new_vip.set_param('mappedip', mappedip)
    if portforward == 'enable':
      new_vip.set_param('portforward', portforward)
      new_vip.set_param('extport', extport)
      new_vip.set_param('mappedport', mappedport)
    if protocol:
      new_vip.set_param('protocol', protocol)

    if comment:
      new_vip.set_param('comment', '"%s"' % comment)

    self.d.load_config(section)
    self.d.candidate_config['firewall vip'][name] = new_vip
Пример #10
0
  def add_fw_entry(self,
      vdom=None,
      name=None, srcintf=None, dstintf=None, srcaddr=None,
      dstaddr=None, service=None, nat="disable",
      auth_redirect_addr=None,
      auth_cert=None,
      status=None,
      profile_protocol_options=None,
      ips_sensor=None,
      utm_status=None,
      groups=None,
      action="accept", schedule='always', ippool=None, logtraffic=None, 
      logtraffic_start=None,
      comments=""):

    section = 'firewall policy'
    new_fw = FortiConfig(config_type='edit', name=name)
    new_fw.set_param('srcintf', quote(srcintf))
    new_fw.set_param('dstintf', quote(dstintf))
    new_fw.set_param('srcaddr', quote(srcaddr))
    new_fw.set_param('dstaddr', quote(dstaddr))
    new_fw.set_param('service', quote(service))
    new_fw.set_param('schedule', quote(schedule))
    new_fw.set_param('nat', nat)
    new_fw.set_param('action', action)

    if status:
      new_fw.set_param('status', '"%s"' % status)
    if groups:
      new_fw.set_param('groups', '"%s"' % groups)
    if logtraffic:
      new_fw.set_param('logtraffic', '"%s"' % logtraffic)
    if logtraffic_start:
      new_fw.set_param('logtraffic_start', '"%s"' % logtraffic_start)
    if comments:
      new_fw.set_param('comments', '"%s"' % comments)

    self.d.load_config(section)
    self.d.candidate_config['firewall policy'][name] = new_fw
Пример #11
0
  def add_address(self, name=None, subnet=None, fqdn=None, country=None, type=None, vdom=None, member=None, start_ip=None, end_ip=None, interface=None, comment=None):
    section = 'firewall address'

    new_addr = FortiConfig(config_type='edit', name=name)
    if comment:
      new_addr.set_param('comment', '"%s"' % comment)
    if country:
      type = 'geography'
      new_addr.set_param('country', country)
    if type:
      new_addr.set_param('type', type)
    if subnet:
      new_addr.set_param('subnet', subnet)
    if fqdn:
      new_addr.set_param('fqdn', fqdn)
    if start_ip and end_ip:
      new_addr.set_param('iprange', type)
      new_addr.set_param('start-ip', start_ip)
      new_addr.set_param('end-ip', end_ip)

    if member:
      new_addr.set_param('member', quote(member))
      section = 'firewall addrgrp'
    if interface:
      new_addr.set_param('associated-interface', quote(interface))

    self.d.load_config(section)
    self.d.candidate_config[section][name] = new_addr
Пример #12
0
  def add_service(self, name=None, tcp_portrange=None, udp_portrange=None, vdom=None, comment=None, 
      visibility=None, category='General'):

    section = 'firewall service custom'
    new_ser = FortiConfig(config_type='edit', name=name)

    new_ser.set_param('category', '"%s"' % category)

    if comment:
      new_ser.set_param('comment', '"%s"' % comment)
    if tcp_portrange:
      new_ser.set_param('tcp-portrange', quote(tcp_portrange))
    if udp_portrange:
      new_ser.set_param('udp-portrange', quote(udp_portrange))
    if visibility:
      new_ser.set_param('visibility', visibility)

    self.d.load_config(section)
    self.d.candidate_config[section][name] = new_ser
Пример #13
0
# 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"
    print "This is how to reach the desired state:"
    print d.compare_config()
Пример #14
0
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)
Пример #15
0
# 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"
    print "This is how to reach the desired state:"
    print d.compare_config()
Пример #16
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