def retrieve_machine_list(domain=None): """ retrieve machine list in the current domain. result will be saved to machines table in data/machines.db """ start_time = time() if not domain: domain = get_current_domain() with db.session.no_autoflush: for m in get_machines_in_domain(domain): machine = Machine() machine.name = m machine.domain = domain ''' # del if existing old = Machine.query.filter_by(name=m).first() if old: db.session.delete(old) db.session.commit() ''' db.session.add(machine) sys.stdout.write('.') db.session.commit() print ' Runtime:', time() - start_time, 'seconds'
def handle(self): dt = timestamp() data_json = self.request.recv(4096).strip() data = json.loads(data_json) mac = data.get("mac", None) if not mac: self.request.sendall( "err 1: No MAC address supplied.".encode("ascii")) return 1 key = data.pop("secret", None) if data["type"] == "setup": username = data.get("username", None) u = User.query().filter(User.username == username).first() if u: new = Machine(mac, u.id, data.get("nickname", None)) new.save() return 0 string = f"err 4: No user exists with username: '******'" self.request.sendall(string.encode("ascii")) return 4 else: m = Machine.query().filter(Machine.mac_address == mac).first() if not m: string = "err 2: No machine with supplied mac registered." self.request.sendall(string.encode("ascii")) return 2 elif m.secret_key and m.secret_key != key: string = "err 3: Key supplied doesn't match the one stored." self.request.sendall(string.encode("ascii")) return 3 if data["type"] == "sys_details": check_sys_details(data, m) command_sender(m, self.request) return 0 elif data["type"] == "sys_status": add_sys_status(dt, data, m) command_sender(m, self.request) return 0 elif data["type"] == "cmd_out": if data.get("output", None): m.output = f'"{data.get("command")},{data.get("output")}"' command_sender(m, self.request) return 0 self.request.sendall("err 6: No output supplied") return 6 return 5
def machine_json(machineid): m = Machine.get(machineid) if m: status = m.sys_status return dumps(status) else: return abort(404)
def index(userid): m = Machine.query().join(users_machines).join(User) \ .filter(User.id == userid).all() return render_template("dashboard/dashboard.html", title="Dashboard", user=current_user, machines=m)
def remove_pending(): m = Machine.query().filter(Machine.id == request.form.get("machine_id")) \ .filter(Machine.pending_owner_id == current_user.id).first() if m and str(current_user.id) == request.form.get("user_id"): m.delete() return dumps("{status: success}") return abort(500)
def machine_add(): print(session['admin']) print(session['admin_id']) form = MachineForm() if form.validate_on_submit(): data = form.data machine = Machine( name=data["name"], url=data["url"], CPU=data["CPU"], RAM=data["RAM"], IPMI=data["IPMI"], machineroom_id=data["machineroom_id"], platform_id=data["platform_id"], putontime=data["putontime"], ) db.session.add(machine) # db.session.commit() # 加入操作日志 adminlog = Oplog(admin_id=session['admin_id'], ip=request.remote_addr, reason='添加机器:{}信息'.format(data['name'])) db.session.add(adminlog) db.session.commit() flash("添加机器成功!", "ok") return redirect(url_for('admin.machine_list', page=1)) return render_template("admin/machine_add.html", form=form)
def accept_pending(): m = Machine.query().filter( Machine.id == request.form.get("machine_id")).first() if m and str(current_user.id) == request.form.get("user_id"): current_user.machines.append(m) current_user.update() m.update(pending_owner_id=None) return dumps("{status: success}") return abort(500)
def add_machine(): form = AddMachineForm() if form.validate_on_submit(): machine = Machine(project=form.project.data, serialnum=form.serialnum.data, customer=form.customer.data, description=form.description.data) db.session.add(machine) db.session.commit() flash('Machine added') return redirect(url_for('index')) return render_template('add_machine.html', title='Add Machine', form=form)
def add_machine(jobnum): form = AddMachineForm() # test = test_var # jobnum = 'HS5279' p = Project.query.filter_by(jobnum=jobnum).first_or_404() if form.validate_on_submit(): machine = Machine(serialnum=form.serialnum.data, job=p) db.session.add(machine) db.session.commit() flash('Machine added') return redirect('/' + jobnum) return render_template('add_machine.html', form=form, jobnum=jobnum)
def handle_config_request(client_ip, filename): m = re.search(MAC_FILE_REGEX, filename) machine = Machine.by_mac(m.group(1).replace('-', ':').lower()) if m else None use_def_config = any( re.search(regex, filename) for regex in DEFAULT_FILE_REGEXES) if machine or use_def_config: return render_config(is_pxelinux_path(filename), machine) else: return None
def machine_more(machineid): m = Machine.get(machineid) if not m.nickname == "": title = f"Machine (#{m.id}): {m.nickname}" else: title = f"Machine: #{m.id}" u = User.query().join(users_machines) \ .join(Machine).filter(Machine.id == machineid).all() return render_template("dashboard/machine.html", m=m, u=u, user=current_user, title=title)
def create_machines_admin(): logger.info("Machine created by %s" % g.user.username) if not g.user.admin: flash('Permission denied', 'error') return redirect(url_for('.get_machines_admin')) logger.info("Machine added by %s" % g.user.username) form = validations.CreateMachineForm(request.form) validations.CreateMachineForm.populate_choices(form, g) if form.validate(): # XXX: Think about adding a new object for PDU and Serial logger.info("after validation") new_machine = Machine(name=form.name.data, bmc_id=form.bmc_id.data, bmc_info=form.bmc_info.data, pdu=form.pdu.data, pdu_port=form.pdu_port.data, serial=form.serial.data, serial_port=form.serial_port.data, netboot_enabled=False) db.session.add(new_machine) try: db.session.commit() flash('Machine added successfully', 'success') except IntegrityError as e: db.session.rollback() flash('Integrity Error: either name or MAC are not unique', 'error') return redirect(url_for('.get_machines_admin')) db.session.refresh(new_machine) for mac_field in form.macs: mac = mac_field.data if mac and mac != '': new_interface = Interface(machine_id=new_machine.id, mac=mac) db.session.add(new_interface) try: db.session.commit() except IntegrityError as e: db.session.rollback() flash('Integrity Error: failed to add mac: %s' % mac, 'error') else: flash_form_errors(form) return redirect(url_for('.get_machines_admin'))
def machine_add_user(machineid): username = request.form.get("data") user = User.query() \ .filter(User.username == username).first() if not user: return { "error": f"Error: User with username '{username}' does not exist." }, 415 machine = Machine.get(machineid) for m in user.machines: if machine.id == m.id: return { "error": "Error: This user already has access to this machine." }, 415 user.machines.append(machine) user.save() return {"username": username}, 200
def machine_command(machineid): m = Machine.get(machineid) command = request.form.get("data") m.command = command while True: for out in m.output: if out[0] == command: if out[:4] == "<br>": out = out[4:] return { "output": out[1].replace("\r\n", "<br>").replace("\n", "<br>").replace( "\r", "<br>") }, 200 sleep(1) m = m.update()
def dbinit(): db.create_all() config = Config() machine = Machine("本机") machine.ip = config.localip machine.cpu = multiprocessing.cpu_count() machine.system = platform.system().lower() machine.disk = config.disk machine.memory = config.memory db.session.add(machine) db.session.commit() print('dbinit ok')
def index(): hwaddr = request.args.get('hwaddr') if not hwaddr: abort(400) machine = Machine.by_mac(hwaddr) if not machine: abort(404) interface = Interface.by_mac(hwaddr) if not interface: abort(404) # query param ?hwaddr= # response: # { # "ipv4": "", # "next-server": "", # "options": [ # { "option": number, "value": "" } # ] # } # option 67 is bootfile data = { 'options': [] } if machine.netboot_enabled: data['next-server'] = app.config['DHCP_TFTP_PROXY_HOST'] data['options'].append({'option': 67, 'value': app.config['DHCP_DEFAULT_BOOTFILE']}) use_static = True if interface.static_ipv4 else False if interface.reserved_ipv4 and not use_static: data['ipv4'] = interface.reserved_ipv4 return jsonify(data), 200
def create_machines_admin(): logger.info("Machine created by %s" % g.user.username) if not g.user.admin: flash('Permission denied', 'error') return redirect(url_for('.get_machines_admin')) logger.info("Machine added by %s" % g.user.username) form = validations.CreateMachineForm(request.form) if form.validate(): # XXX: Think about adding a new object for PDU and Serial logger.info("after validation") new_machine = Machine(name=form.name.data, mac=form.mac.data, bmc_id=form.bmc_id.data, bmc_info=form.bmc_info.data, pdu=form.pdu.data, pdu_port=form.pdu_port.data, serial=form.serial.data, serial_port=form.serial_port.data, kernel_id=form.kernel_id.data, kernel_opts=form.kernel_opts.data, initrd_id=form.initrd_id.data, preseed_id=form.preseed_id.data, netboot_enabled=form.netboot_enabled.data) db.session.add(new_machine) try: db.session.commit() flash('Machine added successfully', 'success') except IntegrityError as e: db.session.rollback() flash('Integrity Error: either name or MAC are not unique', 'error') else: flash_form_errors(form) return redirect(url_for('.get_machines_admin'))
def import_machines(file): # import csv from app.models import Machine from app import db import os # work comp # os.chdir('C:\\Users\\WDG1DCR\\Desktop\\my_projects\\web\\machine_data\\external') # home comp os.chdir('C:\\Users\\gratten\\Documents\\python\\projects\\machine_data\\external') print('importing machine data...') entry_list = [] with open(file, newline='') as csvfile: for row in csvfile: entry = (row.split(';')) entry_list.append(entry) for num in range(len(entry_list)): new_entry = Machine(project=entry_list[num][0], prodline=entry_list[num][1], serialnum=entry_list[num][2], customer=entry_list[num][3], description=entry_list[num][4]) db.session.add(new_entry) db.session.commit()
def gen_fake_data(): # 生成假管理员。 a1 = Admin(name='刘延', phone_num=app.config['SUPER_ADMIN_PHONE_NUM']) a2 = Admin(name='王宁', phone_num='15511127075') db.session.add_all([a1, a2]) db.session.commit() # 生成假机器。 m1 = Machine( latitude='38.0348631337', # QQ地图坐标拾取器。 http://lbs.qq.com/tool/getpoint/ longitude='114.5281523466', admin_id=1, state=1, info='育才街,金领大厦。') m2 = Machine(latitude='38.0481544341', longitude='114.3547850847', admin_id=1, state=-2, info='御园路。') m3 = Machine(latitude='38.0342006313', longitude='114.4178228152', admin_id=2, state=-1, info='裕华西路,苑东街。') db.session.add_all([m1, m2, m3]) db.session.commit() # 生成假用户。 u1 = User(openid='wx_test1') u2 = User(openid='wx_test2') db.session.add_all([u1, u2]) db.session.commit() # 生成假车。 c1 = Car(name='测试车1') c2 = Car(name='测试车2') db.session.add_all([c1, c2]) db.session.commit() # 生成假订单。 o1 = Order(transaction_id='fake_1', status=1, user=u1, machine=m1, admin=m1.admin, car=c1, fee=1000) o2 = Order(transaction_id='fake_2', status=1, user=u1, machine=m2, admin=m2.admin, car=c2, fee=1500) o3 = Order(transaction_id='fake_3', status=1, user=u2, machine=m3, admin=m3.admin, car=c1, fee=1000) o4 = Order(transaction_id='fake_4', status=1, user=u2, machine=m1, admin=m1.admin, car=c1, fee=1001) db.session.add_all([o1, o2, o3, o4]) db.session.commit()
def newMachine(): info = {"result": True, "errorMsg": None} rsacontent = request.form.get("privatekey") ip = request.form.get("ip").strip() user = request.form.get("user") password = request.form.get("password") sshtype = request.form.get("sshtype") port = int(request.form.get("port")) or 22 try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if sshtype == "password": logger.info("ip: %s port: %s user: %s password: %s" % (ip, port, user, password)) ssh.connect(hostname=ip, port=port, username=user, password=password, timeout=10) elif sshtype == "privatekey": key = StringIO(rsacontent) pkey = paramiko.RSAKey.from_private_key(key) ssh.connect(hostname=ip, port=port, username=user, pkey=pkey, timeout=10) else: info["result"] = False info["errorMsg"] = "unsupport sshtype" return jsonify(info) stdin, stdout, stderr = ssh.exec_command("whoami") if user != stdout.readline().strip(): info["result"] = False info["errorMsg"] = stderr.read().decode() return jsonify(info) cmd_disk = "df -m" stdin, stdout, stderr = ssh.exec_command(cmd_disk) diskinfos = stdout.readlines() diskinfo = diskinfos[1] if "%" in diskinfos[1] else diskinfos[2] disk = [i.strip() for i in diskinfo.split(" ") if i.strip()][1] cmd_mem = "free -m" stdin, stdout, stderr = ssh.exec_command(cmd_mem) mem = [i.strip() for i in stdout.readlines()[1].split(" ") if i.strip()][1] cmd_cpu = "cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c" stdin, stdout, stderr = ssh.exec_command(cmd_cpu) cpu = stdout.read().strip() logger.info("disk: %s memory: %s cpu: %s" % (disk, mem, cpu)) ssh.close() machine = Machine( request.form.get("name"), ip=ip, sshtype=sshtype, user=user, port=port, password=password, rsa=rsacontent, memory="%sM" % mem, cpu=cpu, disk="%sM" % disk, username=current_user.nickname ) db.session.add(machine) db.session.commit() db.session.close() except Exception as e: logger.error(traceback.format_exc()) info["result"] = False info["errorMsg"] = str(e) finally: return jsonify(info)