def check_subnet_params(self, data): for i in (data['start_ip'], data['end_ip'], data['gateway']): if not is_ip_addr(i): _ip = i raise Exception("%s is not ip address" % _ip) if data.get('dns1') and not is_ip_addr(data['dns1']): raise Exception("%s is not ip address" % data['dns1']) if data.get('dns2') and not is_ip_addr(data['dns2']): raise Exception("%s is not ip address" % data['dns1']) _is_netmask, netmask_bits = is_netmask(data['netmask']) if not _is_netmask: raise Exception("%s netmask error" % data['netmask'])
def edu_desktop_groups(self, data): """ 教学桌面组列表 """ logger.debug( "get education desktop info, terminal_id:%s, terminal_ip:%s", data.get("terminal_id", 0), data.get("terminal_ip", "")) terminal_id = data.get("terminal_id", 0) if not terminal_id: logger.error("terminal id param error: %s" % terminal_id) return build_result("ParamError") terminal_ip = data.get("terminal_ip", "") if not is_ip_addr(terminal_ip): logger.error("terminal edu desktop group info error, %s not ip" % terminal_ip) return build_result("IPAddrError", ipaddr=terminal_ip) groups = db_api.get_group_with_all( {"group_type": constants.EDUCATION_DESKTOP}) terminal_group = None for group in groups: if group.start_ip and group.end_ip: if terminal_ip in find_ips(group.start_ip, group.end_ip): terminal_group = group break _groups = list() if not terminal_group: logger.error("terminal group not exist: %s" % terminal_ip) return build_result("Success", _groups) logger.debug( "get education desktop terminal ip: %s, terminal_group: %s", terminal_ip, terminal_group.uuid) terminal_id = int(terminal_id) # 查找分组 desktops = db_api.get_desktop_with_all({ "group_uuid": terminal_group.uuid, "active": True }) logger.debug("get education desktop terminal ip: %s, desktops_len: %s", terminal_ip, len(desktops)) for desktop in desktops: # 判断是否总数大于序号 if desktop.instance_num < terminal_id: continue _d = { "uuid": desktop.uuid, "name": desktop.name, "desc": desktop.template.desc, "active": desktop.active, "order_num": desktop.order_num, "os_type": desktop.os_type } _groups.append(_d) _groups = sorted(_groups, key=lambda _groups: _groups['order_num']) logger.debug("edu terminal_ip %s desktop group list: %s" % (terminal_ip, _groups)) return build_result("Success", _groups)
def terminal_instance_match(self, data): """ 所有终端ip对应的桌面ip""" # ips = data.get("ips", "") # ips = ips.split(",") # terminal_ips = list() # for i in ips: # if not is_ip_addr(i): # continue # terminal_ips.append(i) # items = {} groups = db_api.get_group_with_all( {"group_type": constants.EDUCATION_DESKTOP}) group_dict = dict() for group in groups: start_ip = group.start_ip end_ip = group.end_ip uuid = group.uuid group_dict[uuid] = find_ips(start_ip, end_ip) desktop_group_dict = {} desktops = db_api.get_desktop_with_all_by_groups( list(group_dict.keys())) for i in desktops: desktop_group_dict[i.uuid] = i.group_uuid terminals = list() for i in data: terminal_ip = i["terminal_ip"] if not is_ip_addr(terminal_ip): continue for uuid, ips in group_dict.items(): # start_ip = group.start_ip # end_ip = group.end_ip # if find_ips(start_ip, end_ip) if terminal_ip in ips: i["group_uuid"] = uuid terminals.append(i) break # 找到所有云桌面 ret = list() instances = db_api.get_instance_with_all( {"classify": constants.EDUCATION_DESKTOP}) for terminal in terminals: group_uuid = terminal["group_uuid"] terminal_id = terminal["terminal_id"] for instance in instances: desktop_uuid = instance.desktop_uuid _group_uuid = desktop_group_dict.get(desktop_uuid) _terminal_id = instance.terminal_id _instance_ip = instance.ipaddr if _group_uuid == group_uuid and terminal_id == _terminal_id and _instance_ip: terminal["desktop_ip"] = _instance_ip ret.append(terminal) break return build_result("Success", ret)
def education_group(self, data): terminal_ip = data.get("terminal_ip", "") if not is_ip_addr(terminal_ip): return build_result("ParamError") _group = None edu_groups = db_api.get_group_with_all( {"group_type": constants.EDUCATION_DESKTOP}) for group in edu_groups: start_ip = group.start_ip end_ip = group.end_ip if terminal_ip in find_ips(start_ip, end_ip): _group = group break if not _group: return build_result("Success") ret = { "name": _group.name, "uuid": _group.uuid, } return build_result("Success", ret)
def education_group(self, data): logger.info("get data: {}".format(data)) terminal_ip = data.get("terminal_ip", "") if not is_ip_addr(terminal_ip): return build_result("ParamError") _group = None edu_groups = db_api.get_item_with_all( models.YzyVoiGroup, {"group_type": constants.EDUCATION_DESKTOP}) for group in edu_groups: start_ip = group.start_ip end_ip = group.end_ip if terminal_ip in find_ips(start_ip, end_ip): _group = group break if not _group: return build_result("Success") ret = { "name": _group.name, "uuid": _group.uuid, } logger.info("return data: {}".format(ret)) return build_result("Success", ret)
def update_ip_info(): """ { "name": "eth0", "ip": "172.16.1.31", "netmask": "255.255.255.0", "gateway": "172.16.1.254", "dns1": "8.8.8.8", "dns2": "114.114.114.114" } :return: """ try: data = request.get_json() nic_name = data.get("name") ip = data.get("ip") netmask = data.get("netmask") gateway = data.get("gateway") dns1 = data.get("dns1") dns2 = data.get("dns2") if not (is_ip_addr(ip) and is_netmask(netmask)[0] and is_ip_addr(gateway)): current_app.logger.error("update nic %s ip, param error" % (nic_name)) return errcode.get_error_result("IpInfoParamError") if dns2 and not is_ip_addr(dns2): current_app.logger.error("update nic %s ip, dns2 error" % (nic_name)) return errcode.get_error_result("IpInfoParamError") resp = errcode.get_error_result() virtual_net_device = os.listdir('/sys/devices/virtual/net/') resp['data'] = {} utc = int((dt.datetime.utcnow() - dt.datetime.utcfromtimestamp(0)).total_seconds()) resp['data']['utc'] = utc nic_addrs = psutil.net_if_addrs() nic_stats = psutil.net_if_stats() physical_net_device = [ dev for dev in nic_addrs.keys() if dev not in virtual_net_device ] if nic_name not in physical_net_device: current_app.logger.error("add nic %s ip, not physical nic" % nic_name) return errcode.get_error_result("NotPhysicalNICError") nic_ifcfg = "/etc/sysconfig/network-scripts/ifcfg-%s" % nic_name if not os.path.exists(nic_ifcfg): resp = errcode.get_error_result(error="IpConfFileNoFound") return resp ifcfg_str = "TYPE=Ethernet\nPROXY_METHOD=none\nBROWSER_ONLY=no\nBOOTPROTO=static\nDEFROUTE=yes"\ "\nIPV4_FAILURE_FATAL=no\nIPV6INIT=yes\nIPV6_AUTOCONF=yes\nIPV6_DEFROUTE=yes\nIPV6_FAILURE_FATAL=no"\ "\nIPV6_ADDR_GEN_MODE=stable-privacy\nNAME={name}\nUUID={uuid}\nDEVICE={nic}\nONBOOT=yes\nIPADDR={ip}"\ "\nNETMASK={netmask}\nGATEWAY={gateway}\nDNS1={dns1}" uuid = create_uuid() ifcfg_str = ifcfg_str.format( **{ "uuid": uuid, "nic": nic_name, "ip": ip, "netmask": netmask, "gateway": gateway, "dns1": dns1, "name": nic_name }) os.system("ifdown %s" % nic_name) if dns2: ifcfg_str += "\nDNS2=%s" % dns2 with open(nic_ifcfg, "w") as f: f.write(ifcfg_str) # 维护路由表 # 判断新增网关是否能通 ret = icmp_ping(gateway) if ret: # 启动命令 ifup eth0:0 os.system("ifup %s" % nic_name) current_app.logger.info( "interface %s update ip %s, gateway %s is link", nic_name, ip, gateway) else: # 如果网关不通 # 需维护route 表 os.system("ifup %s" % nic_name) os.system("route del default gw %s" % gateway) current_app.logger.info( "interface %s update ip %s, gateway %s is not link", nic_name, ip, gateway) # 重启网络服务 os.system("systemctl restart network") current_app.logger.info("update nic %s ip success" % nic_name) resp["data"] = {"name": nic_name} return resp except Exception as err: current_app.logger.error(err) current_app.logger.error(''.join(traceback.format_exc())) resp = errcode.get_error_result(error="UpdateIpConfFileFailure") return resp
def modify_ip(self): try: resp = errcode.get_error_result() cmd_msg = CommandMsg() cmd_msg.cmdstr = 'update_ip' cmd_msg.BodyType = CommandBodyType.TEXT # Use dhcp config modify_ip_method = self.task.get("data").get("modify_ip_method") if modify_ip_method == "dhcp": group_uuid = self.task.get("data").get('group_uuid') table_api = db_api.YzyTerminalTableCtrl(current_app.db) terminals = table_api.select_terminal_by_group_uuid(group_uuid) ip_info = { "IsDhcp": 1, } for term in terminals: values = { 'mac': term.mac, 'conf_version': str(int(term.conf_version) + 1), 'is_dhcp': 1 } table_api.update_terminal_by_mac(**values) if term.status == "1": ip_info["Mac"] = term.mac body = str(json.dumps(ip_info).encode('utf-8'), encoding='utf-8') cmd_msg.Body = "Command:{}|{}".format( cmd_msg.cmdstr, body) logging.debug(cmd_msg) self.send_thrift_cmd(mac, cmd_msg) logging.debug("Modify group's %s terminals to dhcp success." % group_uuid) return resp mac_list = self.task.get("data").get("mac_list").split(',') ip_list = self.task.get("data").get("to_ip_list").split(',') gateway = self.task.get("data").get("gateway") mask = self.task.get("data").get("mask") dns1 = self.task.get("data").get("dns1", "") dns2 = self.task.get("data").get("dns2", "") if not (is_ip_addr(gateway) and is_netmask(mask)[0] and len(mac_list) == len(ip_list)): logging.error( "param error, gateway {}, mask {}, dns1 {}, dns2 {}". format(gateway, mask, dns1, dns2)) return errcode.get_error_result("RequestParamError") ip_info = { "IsDhcp": 0, "Ip": "", "Subnet": mask, "Gateway": gateway, "Mac": "", "DNS1": dns1, "DNS2": dns2, } for mac in mac_list: table_api = db_api.YzyTerminalTableCtrl(current_app.db) qry_terminal = table_api.select_terminal_by_mac(mac) ip = ip_list[mac_list.index(mac)] ip_info["Ip"] = ip ip_info["Mac"] = mac body = str(json.dumps(ip_info).encode('utf-8'), encoding='utf-8') cmd_msg.Body = "Command:{}|{}".format(cmd_msg.cmdstr, body) logging.debug(cmd_msg) if qry_terminal: terminal_values = { 'mac': mac, 'conf_version': str(int(qry_terminal.conf_version) + 1), 'ip': ip, 'mask': ip_info['Subnet'], 'gateway': ip_info['Gateway'], 'is_dhcp': int(ip_info['IsDhcp']), 'dns1': ip_info['DNS1'], 'dns2': ip_info['DNS2'] } table_api.update_terminal_by_mac(**terminal_values) if qry_terminal.status == '1': self.send_thrift_cmd(mac, cmd_msg) else: logging.warning( 'mac not found in yzy_terminal {}'.format(mac)) return resp except Exception as err: logging.error(err) logging.error(''.join(traceback.format_exc())) resp = errcode.get_error_result(error="OtherError") return resp