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()
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)
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()
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()
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)
#!/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()
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):
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)
#!/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