def validate_arguments(arguments): """ Validate argument values: <CIDRS> :param arguments: Docopt processed arguments """ # Validate CIDR cidrs = arguments.get("<CIDRS>") start_ip = arguments.get("<START_IP>") end_ip = arguments.get("<END_IP>") if cidrs: for cidr in cidrs: if not validate_cidr(cidr): print "Invalid CIDR specified %s" % cidr sys.exit(1) elif start_ip or end_ip: if not (validate_ip(start_ip, 4) or validate_ip(start_ip, 6)): print "Invalid START_IP specified." sys.exit(1) elif not (validate_ip(end_ip, 4) or validate_ip(end_ip, 6)): print "Invalid END_IP specified." sys.exit(1) elif IPAddress(start_ip).version != IPAddress(end_ip).version: print "START_IP and END_IP must be the same ip version" sys.exit(1) elif not IPAddress(start_ip) < IPAddress(end_ip): print "START_IP must be a smaller ip address than END_IP" sys.exit(1)
def validate_arguments(arguments): """ Validate argument values: <PEER_IP> <AS_NUM> Arguments not validated: :param arguments: Docopt processed arguments """ # Validate IPs peer_ip_ok = arguments.get("<PEER_IP>") is None or \ validate_ip(arguments["<PEER_IP>"], 4) or \ validate_ip(arguments["<PEER_IP>"], 6) asnum_ok = True asnum = arguments.get("<AS_NUM>") if asnum: asnum_ok = validate_asn(asnum) # Print error messages if not peer_ip_ok: print "Invalid IP address specified." if not asnum_ok: print "Invalid AS Number specified." # Exit if not valid arguments if not (peer_ip_ok and asnum_ok): sys.exit(1)
def validate_arguments(arguments): """ Validate argument values: <PEER_IP> <AS_NUM> Arguments not validated: :param arguments: Docopt processed arguments """ # Validate IPs peer_ip_ok = arguments.get("<PEER_IP>") is None or \ validate_ip(arguments["<PEER_IP>"], 4) or \ validate_ip(arguments["<PEER_IP>"], 6) asnum_ok = True if arguments.get("<AS_NUM>"): try: asnum = int(arguments["<AS_NUM>"]) asnum_ok = 0 <= asnum <= 4294967295 except ValueError: asnum_ok = False # Print error messages if not peer_ip_ok: print "Invalid IP address specified." if not asnum_ok: print "Invalid AS Number specified." # Exit if not valid arguments if not (peer_ip_ok and asnum_ok): sys.exit(1)
def validate_arguments(arguments): """ Validate argument values: <IP> Arguments not validated: <CONTAINER> <INTERFACE> :param arguments: Docopt processed arguments """ # Validate IP requested_ip = arguments.get("<IP>") if not (requested_ip is None or validate_ip(requested_ip, 4) or validate_ip(requested_ip, 6) or validate_cidr(requested_ip) or requested_ip.lower() in ('ipv4', 'ipv6')): print_paragraph("Invalid IP address specified. Argument must be a " "valid IP or CIDR.") sys.exit(1) # Validate POOL if requested_ip is not None and '/' in requested_ip: requested_pool = IPNetwork(requested_ip) try: client.get_ip_pool_config(requested_pool.version, requested_pool) except KeyError: print_paragraph("Invalid CIDR specified for desired pool. " "No pool found for {0}.".format(requested_pool)) sys.exit(1) # Validate PROFILE endpoint.validate_arguments(arguments)
def validate(self): if float(self['lower_bound'].get()) >= float(self['higher_bound'].get()): raise ValueError('Нижняя граница должна быть меньше верхней') if int(self['clusters'].get()) <= 0: raise ValueError('Количество кластеров должно быть положительным числом') if not validate_ip(self['server_ip'].get()): raise ValueError('Введён невалидный IP-адрес')
def validate_arguments(arguments): """ Validate argument values: <IP> :param arguments: Docopt processed arguments """ # Validate IP container_ip_ok = arguments.get("<IP>") is None or \ validate_ip(arguments["<IP>"], 4) or \ validate_ip(arguments["<IP>"], 6) # Print error message and exit if not valid argument if not container_ip_ok: print "Invalid IP address specified." sys.exit(1)
def create_asset(*arg, **kwargs): try: #指定输出内容 output = ['os', 'cpu', 'nu_ram', 'nu_disk', 'ram'] #获取前端参数的值 data = request.get_json()['params'] #进行对数据的检查是否符合需求 for _key in 'sn,inner_ip,hostname,os,ram,cpu,disk'.split(','): _value = data.get(_key).strip() if _value == '': return json.dumps({ 'code': 1, 'errmsg': '%s Not allowed to empty!' % _key }) for _key in 'ram,disk'.split(','): _value = data.get(_key).strip(',') if not _value.isdigit(): return json.dumps({ 'code': 1, 'errmsg': '%s Must be an integer!' % _key }) if app.config['cursor'].get_one_result('asset', output, { 'sn': data['sn'], 'status': 0 }): return json.dumps({'code': 1, 'errmsg': "sn already is exist!"}) if app.config['cursor'].get_one_result('asset', output, { 'hostname': data['hostname'], 'status': 0 }): return json.dumps({ 'code': 1, 'errmsg': "hostname already is exist!" }) if not utils.validate_ip(data['inner_ip']): return json.dumps({ 'code': 1, 'errmsg': "Inner IP does not conform to the rules!" }) # if not utils.validate_ip(data['app_ip']): # return json.dumps({'code': 1, 'errmsg': "Application IP does not conform to the rules!"}) # if not utils.validate_ip(data['remote_ip']): # return json.dumps({'code': 1, 'errmsg': "Remote IP does not conform to the rules!"}) # if not app.config['cursor'].get_one_result('idc',['name'],{'id':data['idc_id']}): # return json.dumps({'code': 1, 'errmsg': "Idc_id is not exist"}) #执行插入数据 app.config['cursor'].execute_insert_sql('asset', data) #执行记录日志 utils.write_log('api').info("create asset success: %s" % data['sn']) return json.dumps({ 'code': 0, 'result': 'create server assets success!' }) except: #捕捉异常 utils.write_log('api').error("Create asset error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'Create asset failed'})
def _parse_proxies(url): response = requests.get(url) body = fromstring(response.text) proxy_list = set() for row in body.xpath("//tbody/tr"): ip = row.xpath(".//td[1]/text()") port = row.xpath(".//td[2]/text()") https = row.xpath(".//td[7]/text()") if len(ip) == 0 or len(port) == 0 or len(https) == 0: continue if not validate_ip(ip[0]): continue scheme = "http" if https[0] == "yes": scheme += "s" proxy = f"{scheme}://{ip[0]}:{port[0]}" proxy_list.add(proxy) return proxy_list
def validate_arguments(arguments): """ Validate argument values: <IP> <IP6> <PEER_IP> <AS_NUM> <DETACH> Arguments not validated: <DOCKER_IMAGE_NAME> <LOG_DIR> :param arguments: Docopt processed arguments """ # Validate IPs ip_ok = arguments.get("--ip") is None or \ validate_ip(arguments.get("--ip"), 4) ip6_ok = arguments.get("--ip6") is None or \ validate_ip(arguments.get("--ip6"), 6) container_ip_ok = arguments.get("<IP>") is None or \ validate_ip(arguments["<IP>"], 4) or \ validate_ip(arguments["<IP>"], 6) peer_ip_ok = arguments.get("<PEER_IP>") is None or \ validate_ip(arguments["<PEER_IP>"], 4) or \ validate_ip(arguments["<PEER_IP>"], 6) runtime_ok = arguments.get("--runtime") in [None, "none", "docker"] asnum_ok = True asnum = arguments.get("<AS_NUM>") or arguments.get("--as") if asnum: asnum_ok = validate_asn(asnum) detach_ok = True if arguments.get("<DETACH>") or arguments.get("--detach"): detach_ok = arguments.get("--detach") in ["true", "false"] detach_libnetwork_ok = (arguments.get("--detach") == "true" or not arguments.get("--libnetwork")) # Print error message if not ip_ok: print "Invalid IPv4 address specified with --ip argument." if not ip6_ok: print "Invalid IPv6 address specified with --ip6 argument." if not container_ip_ok or not peer_ip_ok: print "Invalid IP address specified." if not asnum_ok: print "Invalid AS Number specified." if not detach_ok: print "Valid values for --detach are 'true' and 'false'" if not detach_libnetwork_ok: print "The only valid value for --detach is 'true' when using libnetwork" if not runtime_ok: print "Runtime must be 'docker' or 'none'." # Exit if not valid argument if not (ip_ok and ip6_ok and container_ip_ok and peer_ip_ok and asnum_ok and detach_ok and detach_libnetwork_ok and runtime_ok): sys.exit(1)
def validate_arguments(arguments): """ Validate argument values: <IP> Arguments not validated: <CONTAINER> <INTERFACE> :param arguments: Docopt processed arguments """ # Validate IP requested_ip = arguments.get("<IP>") if not (requested_ip is None or validate_ip(requested_ip, 4) or validate_ip(requested_ip, 6) or validate_cidr(requested_ip) or requested_ip.lower() in ('ipv4', 'ipv6')): sys.exit('Invalid IP address specified. Argument must be an IP, ' 'a cidr, "ipv4" or "ipv6". ' '"{0}" was given'.format(requested_ip)) # Validate POOL if requested_ip is not None and '/' in requested_ip: try: requested_pool = IPNetwork(requested_ip) except TypeError: sys.exit('Invalid cidr specified for desired pool. ' '"{0}" was given."'.format(pool)) try: pool = client.get_ip_pool_config(requested_pool.version, requested_pool) except KeyError: sys.exit('Invalid cidr specified for desired pool. ' 'No pool found for "{0}"'.format(requested_pool)) # Validate PROFILE endpoint.validate_arguments(arguments)
def vm_modify(**kwargs): try: # 获取前端传来的数据 data = request.get_json()['params'] # 获取where条件 where = data.get('where', None) # 获取要更新这条的数据 data = data.get('data', None) # 指定输出的内容 #output = [ # 'id', 'uuid', 'ip', 'mac', 'cpu', 'ram', 'disk', 'vm', 'business', 'admin', 'remark', 'status', 'host_id','use_status','des_use_id' #] # 对进行传入的数据进行检查书否符合需求 for _key in 'uuid,ip,mac,cpu,ram,disk,vm,host_id'.split(','): _value = data.get(_key).strip() if _value == '': return json.dumps({ 'code': 1, 'errmsg': '%s Not allowed to empty!' % _key }) for _key in 'ram,disk'.split(','): _value = data.get(_key).strip(',') if not _value.isdigit(): return json.dumps({ 'code': 1, 'errmsg': '%s Must be an integer!' % _key }) # if app.config['cursor'].get_one_result('vm',output,{'uuid':data['uuid']}) and \ # app.config['cursor'].get_one_result('vm', output, {'uuid': data['uuid']})['id'] != \ # app.config['cursor'].get_one_result('vm', output, {'id': data['id']})['id']: # return json.dumps({'code': 1, 'errmsg': "uuid already is exist!"}) if not app.config['cursor'].get_one_result('asset', ['hostname'], { 'id': data['host_id'], 'status': 0 }): return json.dumps({'code': 1, 'errmsg': "hostname is not exist"}) if not utils.validate_ip(data['ip']): return json.dumps({ 'code': 1, 'errmsg': "IP does not conform to the rules!" }) # 进行更新数据 app.config['cursor'].execute_update_sql('vm', data, where) # 写入日志 utils.write_log('api').info("update vm success: %s" % data['vm']) return json.dumps({'code': 0, 'result': 'Update server vm success!'}) except: # 捕捉异常 utils.write_log('api').error("Update vm error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'Update server vm failed'})
def portmapping_delete_api(): """ Implementation Notes Deletes a port mapping rule. If no parameters given, delete all rules. If only publicIP given, delete all rules on that IP. If both publicIP and publicPort given, delete that single rule. Parameters Parameter Description Parameter Type Data Type publicIp Public IP Address. query string publicPort Public port. query integer Response Messages HTTP Status Code Reason Response Model Headers 200 Port mapping rule(s) deleted. """ public_ip = request.args.get('publicIp', type=str) public_port = request.args.get('publicPort', type=int) log.debug('publicIp=%s,publicPort=%s' % (public_ip, public_port)) if public_ip is None and public_port is not None: return err_return("Port specified without IP", "IPNotSpecified", "", 400) if public_ip and not validate_ip(public_ip): return err_return('IP(%s) invalid' % public_ip, 'ParameterInvalid', '', 400) if public_port is not None and public_port <= 0: return err_return('Port(%s) invalid' % public_port, 'ParameterInvalid', '', 400) if public_ip and public_port: db_portmaps = portmap_db_get_all(public_ip=public_ip, public_port=public_port) elif public_ip: db_portmaps = portmap_db_get_all(public_ip=public_ip) else: db_portmaps = portmap_db_get_all() if not db_portmaps: log.debug('db_portmaps is None') return Response(), 200 for db_portmap in db_portmaps: portid = port_ip_db_get_one('port_id', ip_address=db_portmap['public_ip']) routerid = port_db_get_one('device_id', id=portid) if not rt_deconf_nat_one_to_one( routerid, 6, db_portmap['public_ip'], db_portmap['ip'], db_portmap['public_port'], db_portmap['port']): return Response(json.dumps(NEUTRON_500)), 500 portmap_db_delete(public_ip=db_portmap['public_ip'], public_port=db_portmap['public_port']) return Response(), 200
def post(self): json = request.json try: if validate_ip(json['ip']): g.db.execute('insert into entries ( ip , acc_str ) values ( ? , ? ) ', [ json['ip'] , json['acc_str'] ]) g.db.commit() pdu_data = query_db('select * from entries where ip = ? ' ,[ json['ip'] ] , one = True ) return { 'id' : pdu_data[0] } else: return { 'Error' : 'invalid address' } except sqlite3.IntegrityError as e: return { 'Error' : 'ip address already exists' } except: print 'unhandled exception has occurred ' return { 'Error' : 'Bad request' }
def validate_arguments(arguments): """ Validate argument values: <IP> <IP6> <PEER_IP> <AS_NUM> <DETACH> Arguments not validated: <DOCKER_IMAGE_NAME> <LOG_DIR> :param arguments: Docopt processed arguments """ # Validate IPs ip_ok = arguments.get("--ip") is None or \ validate_ip(arguments.get("--ip"), 4) ip6_ok = arguments.get("--ip6") is None or \ validate_ip(arguments.get("--ip6"), 6) container_ip_ok = arguments.get("<IP>") is None or \ validate_ip(arguments["<IP>"], 4) or \ validate_ip(arguments["<IP>"], 6) peer_ip_ok = arguments.get("<PEER_IP>") is None or \ validate_ip(arguments["<PEER_IP>"], 4) or \ validate_ip(arguments["<PEER_IP>"], 6) asnum_ok = True if arguments.get("<AS_NUM>") or arguments.get("--as"): try: asnum = int(arguments["<AS_NUM>"] or arguments["--as"]) asnum_ok = 0 <= asnum <= 4294967295 except ValueError: asnum_ok = False detach_ok = True if arguments.get("<DETACH>") or arguments.get("--detach"): detach_ok = arguments.get("--detach") in ["true", "false"] # Print error message if not ip_ok: print "Invalid IPv4 address specified with --ip argument." if not ip6_ok: print "Invalid IPv6 address specified with --ip6 argument." if not container_ip_ok or not peer_ip_ok: print "Invalid IP address specified." if not asnum_ok: print "Invalid AS Number specified." if not detach_ok: print "Valid values for --detach are 'true' and 'false'" # Exit if not valid argument if not (ip_ok and ip6_ok and container_ip_ok and peer_ip_ok and asnum_ok and detach_ok): sys.exit(1)
def vm_create(**kwargs): try: #指定输出内容 output = [ 'id', 'uuid', 'ip', 'mac', 'cpu', 'ram', 'disk', 'vm', 'business', 'admin', 'remark', 'status', 'host_id' ] #获取前端参数的值 data = request.get_json()['params'] #进行对数据的检查是否符合需求 for _key in 'ip,mac,cpu,ram,disk,vm'.split(','): _value = data.get(_key).strip() if _value == '': return json.dumps({ 'code': 1, 'errmsg': '%s Not allowed to empty!' % _key }) for _key in 'ram,disk'.split(','): _value = data.get(_key).strip(',') if not _value.isdigit(): return json.dumps({ 'code': 1, 'errmsg': '%s Must be an integer!' % _key }) # if app.config['cursor'].get_one_result('vm',output,{'uuid':data['uuid']}): # return json.dumps({'code': 1, 'errmsg': "uuid already is exist!"}) if app.config['cursor'].get_one_result('vm', output, { 'ip': data['ip'], 'status': 0 }): return json.dumps({'code': 1, 'errmsg': "ip already is exist!"}) if not utils.validate_ip(data['ip']): return json.dumps({ 'code': 1, 'errmsg': "IP does not conform to the rules!" }) #执行插入数据 app.config['cursor'].execute_insert_sql('vm', data) #执行记录日志 utils.write_log('api').info("create vm success: %s" % data['vm']) return json.dumps({'code': 0, 'result': 'create server vm success!'}) except: #捕捉异常 utils.write_log('api').error("Create vm error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'Create vm failed'})
def __parse_proxylist(self, proxylist): result = {} for proxy in proxylist: # Strip spaces from proxy string. proxy = proxy.strip() if len(proxy) < 9: log.debug('Invalid proxy address: %s', proxy) continue parsed = { 'hash': None, 'ip': None, 'port': None, 'protocol': self.protocol, 'username': None, 'password': None } # Check and separate protocol from proxy address. if '://' in proxy: pieces = proxy.split('://') proxy = pieces[1] if pieces[0] == 'http': parsed['protocol'] = ProxyProtocol.HTTP elif pieces[0] == 'socks4': parsed['protocol'] = ProxyProtocol.SOCKS4 elif pieces[0] == 'socks5': parsed['protocol'] = ProxyProtocol.SOCKS5 else: log.error('Unknown proxy protocol in: %s', proxy) continue if parsed['protocol'] is None: log.error('Proxy protocol is not set for: %s', proxy) continue # Check and separate authentication from proxy address. if '@' in proxy: pieces = proxy.split('@') if ':' not in pieces[0]: log.error('Unknown authentication format in: %s', proxy) continue auth = pieces[0].split(':') parsed['username'] = auth[0] parsed['password'] = auth[1] proxy = pieces[1] # Check and separate IP and port from proxy address. if ':' not in proxy: log.error('Proxy address port not specified in: %s', proxy) continue pieces = proxy.split(':') if not validate_ip(pieces[0]): log.error('IP address is not valid in: %s', proxy) continue parsed['ip'] = pieces[0] parsed['port'] = pieces[1] parsed['hash'] = Proxy.generate_hash(parsed) result[parsed['hash']] = parsed log.info('Successfully parsed %d proxies.', len(result)) return result
def validate(self): if not validate_ip(self['server_ip'].get()): raise ValueError('Введён невалидный IP-адрес')
def is_valid(self): return any([ address.is_valid() and utils.validate_ip(address.ip) for address in self.items ])
def is_valid(self): return any([address.is_valid() and utils.validate_ip(address.ip) for address in self.items])
def update_asset(*arg, **kwargs): try: #获取前端传来的数据 data = request.get_json()['params'] #获取where条件 where = data.get('where', None) #获取要更新这条的数据 data = data.get('data', None) #指定输出的内容 output = ['id', 'os', 'cpu', 'nu_ram', 'nu_disk', 'ram'] #对进行传入的数据进行检查书否符合需求 for _key in 'sn,inner_ip,hostname,os,ram,cpu,disk'.split(','): _value = data.get(_key).strip() if _value == '': return json.dumps({ 'code': 1, 'errmsg': '%s Not allowed to empty!' % _key }) for _key in 'ram,disk'.split(','): _value = data.get(_key).strip(',') if not _value.isdigit(): return json.dumps({ 'code': 1, 'errmsg': '%s Must be an integer!' % _key }) if app.config['cursor'].get_one_result('asset', output, { 'sn': data['sn'], 'status': 0 }) and app.config['cursor'].get_one_result('asset', output, { 'sn': data['sn'], 'status': 0 })['id'] != app.config['cursor'].get_one_result( 'asset', output, { 'id': data['id'], 'status': 0 })['id']: return json.dumps({'code': 1, 'errmsg': "sn already is exist!"}) if app.config['cursor'].get_one_result('asset', output, { 'hostname': data['hostname'], 'status': 0 }) and app.config['cursor'].get_one_result('asset', output, { 'hostname': data['hostname'], 'status': 0 })['id'] != app.config['cursor'].get_one_result( 'asset', output, { 'id': data['id'], 'status': 0 })['id']: return json.dumps({ 'code': 1, 'errmsg': "hostname already is exist!" }) if not utils.validate_ip(data['inner_ip']): return json.dumps({ 'code': 1, 'errmsg': "Inner IP does not conform to the rules!" }) # if not utils.validate_ip(data['app_ip']): # return json.dumps({'code': 1, 'errmsg': "Application IP does not conform to the rules!"}) # if not utils.validate_ip(data['remote_ip']): # return json.dumps({'code': 1, 'errmsg': "Remote IP does not conform to the rules!"}) # if not app.config['cursor'].get_one_result('idc', ['name'], {'id': data['idc_id']}): # return json.dumps({'code': 1, 'errmsg': "Idc_id is not exist"}) #进行更新数据 _data = app.config['cursor'].get_one_result('changelog', output, where) app.config['cursor'].execute_update_sql('asset', data, where) __data = app.config['cursor'].get_one_result('changelog', output, where) print _data print __data print set(_data) ^ set(__data) #写入日志 utils.write_log('api').info("update asset success: %s" % data['sn']) return json.dumps({ 'code': 0, 'result': 'Update server assets success!' }) except: #捕捉异常 utils.write_log('api').error("Update asset error: %s" % traceback.format_exc()) return json.dumps({'code': 1, 'errmsg': 'Update server assets failed'})