def main(): # Parse for command line argument for fgt ip if len(sys.argv) < 2: # Requires fgt ip and password print("Please specify fgt ip address") exit() # Initilize fgt connection ip = sys.argv[1] try: passwd = sys.argv[2] except: passwd = '' #fgt = FGT(ip) # Hard coded vdom value for all requests vdom = "root" # Login to the FGT ip fgt = FortiOSAPI() fgt.login(ip, 'admin', passwd, verify=False) # take note that below srcintf, dstintf, etc is not checked whether it exists or not... it can be error if not exists ! data = {'policyid': "66"} fgt.delete('firewall', 'policy', vdom="root", data=data) data = {'name': 'apiset'} fgt.delete('antivirus', 'profile', vdom="root", data=data) fgt.logout()
def main(): # Parse for command line argument for fgt ip if len(sys.argv) < 2: # Requires fgt ip and vdom print "Please specify fgt ip address" exit() # Initilize fgt connection ip = sys.argv[1] #fgt = FGT(ip) # Hard coded vdom value for all requests vdom = "root" # Login to the FGT ip fgt = FortiOSAPI() fgt.login(ip, 'admin', '') parameters = {'global': '1'} upload_data = {'source': 'upload', 'scope': 'global'} files = {'file': ('license', open("license.lic", 'r'), 'text/plain')} fgt.upload('system/vmlicense', 'upload', data=upload_data, parameters=parameters, files=files) fgt.logout()
def main(): # Parse for command line argument for fgt ip if len(sys.argv) < 2: # Requires fgt ip and password print("Please specify fgt ip address") exit() # Initilize fgt connection ip = sys.argv[1] try: passwd = sys.argv[2] except: passwd = '' #fgt = FGT(ip) # Hard coded vdom value for all requests vdom = "root" # Login to the FGT ip fgt = FortiOSAPI() fgt.login(ip, 'admin', passwd, verify=False) # take note that below srcintf, dstintf, etc is not checked whether it exists or not... it can be error if not exists ! hasil = fgt.monitor('router', 'ipv4') print(hasil['results']) fgt.logout()
def main(): # Parse for command line argument for fgt ip if len(sys.argv) < 2: # Requires fgt ip and password print "Please specify fgt ip address" exit() # Initilize fgt connection ip = sys.argv[1] try: passwd = sys.argv[2] except: passwd = '' #fgt = FGT(ip) # Hard coded vdom value for all requests vdom = "root" # Login to the FGT ip fgt = FortiOSAPI() fgt.login(ip, 'fgtadmin', passwd, verify=False) data = { 'name': "APItest", 'subnet': "10.20.0.0 255.255.255.0", 'type': "ipmask" # associated_interface: "port2" } fgt.set('firewall', 'address', vdom="root", data=data) fgt.logout()
def main(): # Parse for command line argument for fgt ip if len(sys.argv) < 2: # Requires fgt ip and password print("Please specify fgt ip address") exit() # Initilize fgt connection ip = sys.argv[1] try: passwd = sys.argv[2] except: passwd = '' # fgt = FGT(ip) # Hard coded vdom value for all requests vdom = "root" # Login to the FGT ip fgt = FortiOSAPI() fgt.login(ip, 'admin', passwd, verify=False) yamldata = ''' antivirus: profile: apiset: 'name': "apiset" "scan-mode": "quick" 'http': {"options": "scan avmonitor",} "emulator": "enable" firewall: policy: 66: 'name': "Testfortiosapi" 'action': "accept" 'srcintf': [{"name": "internal"}] 'dstintf': [{"name": "virtual-wan-link"}] 'srcaddr': [{"name": "all"}] 'dstaddr': [{"name": "all"}] 'schedule': "always" 'service': [{"name": "HTTPS"}] "utm-status": "enable" "profile-type": "single" 'av-profile': "apiset" 'profile-protocol-options': "default" 'ssl-ssh-profile': "certificate-inspection" 'logtraffic': "all" ''' yamldict = yaml.load(yamldata, Loader=yaml.FullLoader) fgt.setoverlayconfig(yamltree=yamldict) fgt.logout()
def main(): vdom = "root" fgt = FortiOSAPI() fgt.login('192.168.1.99', 'admin', 'tas19751975', verify=False) hasil = fgt.monitor('virtual-wan', 'health-check') print("----------------") print(pprint.pprint(hasil['results'])) print("----------------") fgt.logout()
def main(): # Parse for command line argument for fgt ip if len(sys.argv) < 2: # Requires fgt ip and password print "Please specify fgt ip address" exit() # Initilize fgt connection ip = sys.argv[1] try: passwd = sys.argv[2] except: passwd = '' #fgt = FGT(ip) # Hard coded vdom value for all requests vdom = "root" # Login to the FGT ip fgt = FortiOSAPI() fgt.login(ip, 'admin', passwd) data = { 'name': "apiset", "scan-mode": "quick", 'http': {"options": "scan avmonitor", }, "emulator": "enable", } fgt.set('antivirus', 'profile', vdom="root", data=data) data = { 'policyid': "66", 'name': "Testfortiosapi", 'action': "accept", 'srcintf': [{"name": "port1"}], 'dstintf': [{"name": "port2"}], 'srcaddr': [{"name": "all"}], 'dstaddr': [{"name": "all"}], 'schedule': "always", 'service': [{"name": "HTTPS"}], "utm-status": "enable", "profile-type": "single", 'av-profile': "apiset", 'profile-protocol-options': "default", 'ssl-ssh-profile': "certificate-inspection", 'logtraffic': "all", } fgt.set('firewall', 'policy', vdom="root", data=data) fgt.logout()
def _send_request(call): logger.info( '_send_request request_props:{}'.format(call)) host = call.get('host') username = call.get('username') password = call.get('password') use_ssl = call.get('use_ssl', False) verify_ssl = call.get('verify_ssl', False) vdom = call.get('vdom', 'root') path = call.get('path') name = call.get('name') data = call.get('data', {}) method = call.get('method') # TODO# add api key method option and client certificate verifications # TODO# upload license call / check license when connection is on fgt_instance = FortiOSAPI() if use_ssl == True: fgt_instance.https('on') else: fgt_instance.https(status='off') fgt_instance.login(host, username, password, verify=verify_ssl) if method == "LICENSE": code, response = fgt_instance.license() logger.debug('---> Method: {} \n code: {} \n response: \n {}'.format(method, code, response)) if method == "GET": code, response = fgt_instance.get(path, name, vdom=None, mkey=None, parameters=None) logger.debug('---> Method: {} \n code: {} \n response: \n {}'.format(method, code, response)) # if method == "UPDATE": # if method == "SET": # if method == "REPLACE": # if method == "CLONE": if method == "SETOVERLAY": code, response = fgt_instance.setoverlayconfig(data, vdom=vdom) logger.debug('---> Method: {} \n code: {} \n response: \n {}'.format(method, code, response)) fgt_instance.logout() return code, response
def change_forti_hostname(username, password, host, port, new_hostname): FG = FortiOSAPI() credentials = { 'host': host + ":" + port, 'username': username, 'password': password } hostname_update_payload = {'hostname': new_hostname} FG.login(**credentials) out = FG.get('system', 'global') click.echo("Old hostname : {0}".format(out['results']['hostname'])) FG.set('system', 'global', data=hostname_update_payload) # Check new hostname: out = FG.get('system', 'global') click.echo("New hostname : {0}".format(out['results']['hostname'])) # logout FG.logout()
from pprint import pprint from fortiosapi import FortiOSAPI FG = FortiOSAPI() # Source _host FG_HOST = os.environ['FG_HOST'] FG_USER = os.environ['FG_USER'] FG_PASS = os.environ['FG_PASS'] DEVICE = { 'host': FG_HOST, 'username': FG_USER, 'password': FG_PASS, } FG.login(**DEVICE) param = { 'config_id': 1, } out = FG.download('system', 'config-revision/file', parameters=param) with open("fg_revision.txt", "w") as f: f.write(out.text) pprint(out) FG.logout()
from fortiosapi import FortiOSAPI from getpass import getpass from pprint import pprint fgt = FortiOSAPI() # get information from user host = input("Host IP: ") username = input("Username: "******"Password: "******"host": host, "username": username, "password": passwd} # verify=False due to self signed cert on internal interface fgt.login(**device, verify=False) out = fgt.monitor("system", "status") pprint(out) out = fgt.get("system", "global") pprint(out) fgt.logout()
class FortiOS6Driver(NetworkDriver): """Napalm driver for FortiGate FortiOS 6.x.""" def __init__(self, hostname, username, password, timeout=60, optional_args=None): """Constructor.""" self.device = None self.hostname = hostname self.username = username self.password = password self.timeout = timeout if optional_args is None: optional_args = {} else: self.transport = optional_args.get("transport", "https") self.port = optional_args.get('port', 443) self.device = FortiOSAPI() def open(self): """Implement the NAPALM method open (mandatory)""" try: self.device.login(host=self.hostname, username=self.username, password=self.password) except ConnectionError: print('Connection Error') def close(self): """Implement the NAPALM method close (mandatory)""" self.device.logout() def get_facts(self): facts = {} system_global = self.device.get('system', 'global') print(system_global) system_dns = self.device.get('system', 'dns')['results'] print(system_dns) facts['hostname'] = system_global['results']['hostname'] facts['fqdn'] = facts['hostname'] + '.' + system_dns['domain'] facts['vendor'] = 'Fortinet' facts['model'] = None # Unable to get from API facts['serial_number'] = system_global['serial'] facts['os_version'] = system_global['version'] facts['uptime'] = None # Unable to get from API facts['interface_list'] = None return facts def is_alive(self): """Returns a flag with the state of the connection.""" is_alive = False # Only consider device alive after logged in and successful response try: is_alive = self.device.get('system', 'status')['http_status'] except NotLogged: # except fortiosapi.exceptions.NotLogged: is_alive = True print('cool') # except ConnectTimeout: # pass except Exception as e: print(e.__class__) print(e.__class__ == NotLogged) print('Unknown Error') if is_alive: return {'is_alive': True} else: return {'is_alive': False}
def main(): fields = { "host": { "required": True, "type": "str" }, "username": { "required": True, "type": "str" }, "password": { "required": True, "type": "str", "no_log": True }, "vdom": { "required": False, "type": "str", "default": "root" }, "https": { "required": False, "type": "bool", "default": True }, "ssl_verify": { "required": False, "type": "bool", "default": False }, 'gather_subset': { "required": False, "type": "list", "default": ['system'] } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: # for now only support local connection mode module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) gather_subset = module.params['gather_subset'] runable_subsets = set() for subset in gather_subset: if not subset.startswith(tuple(VALID_SUBSETS)): module.fail_json(msg='Subset must be one of [%s], got %s' % (', '.join(VALID_SUBSETS), subset)) for valid_subset in VALID_SUBSETS: if subset.startswith(valid_subset): runable_subsets.add((subset, valid_subset)) if not runable_subsets: runable_subsets.update(VALID_SUBSETS) facts = dict() facts['gather_subset'] = list(runable_subsets) instances = list() for (subset, valid_subset) in runable_subsets: instances.append(FACT_SUBSETS[valid_subset](module, fos, subset)) # Populate facts for instances for inst in instances: inst.populate_facts() facts.update(inst.facts) fos.logout() module.exit_json(ansible_facts=facts)