コード例 #1
0
ファイル: views.py プロジェクト: zhanghonged/scripts
def server_add(request):
    '''
    服务器添加方法,根据ip、port、username、password对服务器操作:远程登录、脚本上传、脚本远程执行
    :param request:
    :return:
    '''
    result = {'status':'error','data':''}
    if request.method == 'POST':
        ip = request.POST.get('ip')
        port = request.POST.get('port')
        username = request.POST.get('username')
        password = request.POST.get('password')
        print ip,port,username,password
        if ip and port and username and password:
            #save db
            equipment = Equipment()
            equipment.ip = ip
            equipment.port = port
            equipment.username = username
            equipment.password = password
            equipment.save()
            #连接远程虚拟机
            connect = connect_server(ip,port,username,password)
            if connect['status'] == 'success':
                trans = connect['data']
                # 用于文件上传和下载的sftp服务
                sftp = paramiko.SFTPClient.from_transport(trans)
                # 远程执行命令服务
                ssh = paramiko.SSHClient()
                ssh._transport = trans
                # 创建目录
                stdin,stdout,stderr = ssh.exec_command('mkdir CMDBClient')
                time.sleep(1)
                # 上传文件
                sftp.put('sftpDir/getData.py','CMDBClient/getData.py')
                sftp.put('sftpDir/sendData.py', 'CMDBClient/sendData.py')
                sftp.put('sftpDir/main.py', 'CMDBClient/main.py')
                # 调用脚本
                stdin,stdout,stderr = ssh.exec_command('python CMDBClient/main.py')
                trans.close()
                # 连接成功状态记录到数据库
                equipment = Equipment.objects.get(ip=ip)
                equipment.status = 'True'
                equipment.save()
            else:
                result['data'] = connect['data']
                # 连接失败状态记录到数据库
                equipment = Equipment.objects.get(ip = ip)
                equipment.status = 'False'
                equipment.save()
        else:
            result['data'] = 'ip and port and username and password not be null'
    else:
        result['data'] = 'your request must be post'
    return JsonResponse(result)
コード例 #2
0
ファイル: app.py プロジェクト: twilightgod/gocamp
def list_equipments():
    """
    Retrieve all known Equipment
    :return:
    """
    equipments = []
    equipment_all = sorted(get_json('LIST_EQUIPMENT'), key=lambda e: e['order'])
    for category in equipment_all:
        equipment = category['subEquipmentCategories']
        equipments.extend([Equipment(category['equipmentCategoryId'],e['subEquipmentCategoryId'],e['localizedValues'][0]['name']) for e in equipment])
    return equipments
コード例 #3
0
ファイル: test_post_views.py プロジェクト: jbenjoy2/swolemate
    def setUp(self):
        """create test client, add sample data"""
        db.drop_all()
        db.create_all()

        self.client = app.test_client()

        self.testuser = User.signup(email='*****@*****.**', password="******",
                                    username='******', first_name='Test', last_name='User', image_url=User.image_url.default.arg, cover_url=User.cover_url.default.arg)
        self.testuser_id = 1234
        self.testuser.id = self.testuser_id

        db.session.commit()
        p1 = Post(id=5678, title='testpost1', details='this is a test post',
                  is_private=False, user_id=self.testuser_id, timestamp=None)

        db.session.add(p1)
        db.session.commit()

        p1 = Post.query.get(5678)
        self.testuser.likes.append(p1)
        self.testuser_likes = self.testuser.likes
        db.session.commit()
        self.p1 = p1
        self.p1_id = self.p1.id
        db.session.commit()

        biceps = Muscle(name='biceps', body_part='arms')
        triceps = Muscle(name='triceps', body_part='arms')
        deltoids = Muscle(name='deltoids', body_part='shoulders')

        db.session.add_all([biceps, triceps, deltoids])
        db.session.commit()

        barbell = Equipment(name='barbell')
        kettlebell = Equipment(name='kettlebell')
        dumbbells = Equipment(name='dumbbells')

        db.session.add_all([barbell, kettlebell, dumbbells])
        db.session.commit()
コード例 #4
0
def new_gauge():
    """
    Add a new Equipment
    """
    form = gEquipmentForm(request.form)

    if request.method == 'POST' and form.validate():
        # save the album
        equipment = Equipment()
        his = History()
        gsave_changes(his, equipment, form, new=True)
        flash('Equipment added successfully!')
        return redirect('/')
    print(form.make)
    return render_template('new_gauge.html', form=form)
コード例 #5
0
def new_instrument():
    """
    Add a new Equipment
    """
    form = iEquipmentForm(request.form)

    if request.method == 'POST' and form.validate():
        # save the album
        equipment = Equipment()
        his = History()
        isave_changes(his, equipment, form, new=True)
        flash('Equipment added successfully!')
        flash('Itemcode is ' + equipment.itemcode)
        return redirect('/')

    return render_template('new_instrument.html', form=form)
コード例 #6
0
def add_eq(request):
    for i in range(100):
        e = Equipment()
        e.hostname = "localhost_%s" % i
        e.IP = "192.168.1.%s" % (i + 2)
        e.System = random.choice([
            "win7_32",
            "win7_64",
            "centos.6_32",
            "centos.7",
        ])
        e.Statue = random.choice(["True", "False"])
        e.Mac = random.choice(["00:0c:29:92:85:4e", "00:0c:29:5b:2a:a1"])
        e.user = "******"
        e.Password = "******"
        e.save()
    return JsonResponse({"statue": "ahh"})
コード例 #7
0
async def api_create_equipment(request, *, name, model, asset_number,
                               acessories, warehouse, scrapped):
    check_admin(request)
    if not name or not name.strip():
        raise APIValueError('name', 'name cannot be empty.')
    if not model or not model.strip():
        raise APIValueError('model', 'model cannot be empty.')
    if not asset_number or not asset_number.strip():
        raise APIValueError('asset_number', 'asset_number cannot be empty.')
    equipment = Equipment(name=name.strip(),
                          model=model.strip(),
                          asset_number=asset_number.strip(),
                          acessories=acessories.strip(),
                          warehouse=warehouse.strip(),
                          scrapped=scrapped.strip(),
                          user_id='',
                          user_name='',
                          user_image='')
    await equipment.save()
    return equipment
コード例 #8
0
def eq_add(request):
    result = {"state": "error", "data": ""}
    if request.method == "POST":
        data = request.POST
        ip = data.get("ip")
        port = data.get("port")
        user = data.get("username")
        password = data.get("password")
        if ip and port and user and password:
            eq = Equipment()
            eq.IP = ip
            eq.User = user
            eq.Password = password
            try:
                trans = paramiko.Transport(ip, port)
                trans.connect(username=user, password=password)
                sftp = paramiko.SFTPClient.from_transport(trans)
                ssh = paramiko.SSHClient()
                ssh._transport = trans
                stdin, stdout, stderr = ssh.exec_command("mkdir CMDBClient")
                sftp.put("sftpDir/getData.py", "/root/CMDBClient/getData.py")
                sftp.put("sftpDir/sendData.py", "/root/CMDBClient/sendData.py")
                sftp.put("sftpDir/main.py", "/root/CMDBClient/main.py")
                stdin, stdout, stderr = ssh.exec_command(
                    "python /root/CMDBClient/main.py")
                trans.close()
                result["state"] = "success"
                result["data"] = "操作成功!"
                eq.Statue = "True"
            except Exception as e:
                eq.Statue = "False"
                result["data"] = "远程连接错误:%s" % e
            finally:
                eq.save()
        else:
            result["data"] = "IP、port、user、password不能为空,请检查"
    else:
        result["data"] = "请求错误,请刷新重试"
    return JsonResponse(result)
コード例 #9
0
ファイル: __init__.py プロジェクト: jumpjumpdog/MQTT
def add_data(scope):
    from models import Admin,Owner,THistory,HHistory,Equipment
    # 创建表
    db = scope['db']

    admin = Admin('sjw','123')
    db.session.add(admin)
    db.session.commit()

    owner = Owner('李强','123')
    db.session.add(owner)
    db.session.commit()

    owner2 = Owner('王建林','123')
    db.session.add(owner2)
    db.session.commit()

    eqp_name = '设备2'
    eqp_uuid = getUuid()
    print(eqp_uuid)
    eqp = Equipment(_id=eqp_uuid,name=eqp_name,max_t=40,min_t=0,max_h=50,min_h=10,owner_id=owner.id,create_date=None)
    db.session.add(eqp)
    db.session.commit()
コード例 #10
0
def list_site_availability(camp_area, start_date, end_date, equipment_type):
    """
    Retrieve the Availability for all Sites in a Camp Area which can host the selected Equipment within a date range
    :param camp_area:
    :param start_date:
    :param end_date:
    :param equipment_type:
    :return:
    """
    data = {
        'mapId': camp_area.map_id,
        'bookingCategoryId': 0,
        'startDate': start_date.isoformat(),
        'endDate': end_date.isoformat(),
        'isReserving': True,
        'getDailyAvailability': True,
        'partySize': 1,
        'equipmentId': equipment_type,
        'subEquipmentId': equipment_type,
        'generateBreadcrumbs': False,
    }
    results = post_json('MAPDATA', data)
    sites_availability = {}
    for entry in results['resourcesOnMap']:
        site = Site(entry['resourceId'], entry['localizedValues'][0]['name'],
                    entry['localizedValues'][0]['description'])
        allowed_equipment = [
            Equipment(e['item1'], e['item2'], None)
            for e in entry['allowedEquipment']
        ]
        availability = [
            SiteAvailability(site, e['availability'], allowed_equipment)
            for e in results['resourceAvailabilityMap'][str(site.resource_id)]
        ]
        sites_availability[site] = availability
    return OrderedDict(
        sorted(sites_availability.items(), key=lambda sa: sa[0].name.zfill(3)))
コード例 #11
0
ファイル: equipment_view.py プロジェクト: h3idan/flask-asset
def addequipment():

    if request.method == "POST":
        print 'ssssssssss22'
        #pdb.set_trace()
        name = request.form.get('name')  #设备名称
        code = request.form.get('code')  #设备代码
        type_code = request.form.get('type_code')  #类别代码
        type_name = request.form.get('type_name')  #类别名称
        brand = request.form.get('brand')  #品牌
        type_model = request.form.get('type_model')  #规格型号
        equ_num = request.form.get('equ_num')  #机身号
        by_use = request.form.get('by_use')  #用途
        use_unit = request.form.get('use_unit')  #使用单位
        unit_num = request.form.get('unit_num')  #单位代码
        depository = request.form.get('depository')  #保管人
        location = request.form.get('location')  #存放地点
        buy_time = request.form.get('buy_date')  #购置日期
        put_time = request.form.get('put_date')  #更新日期
        out_time = request.form.get('out_date')  #打印日期
        details = request.form.get('details')  #备注
        status = request.form.get('status')
        #移动载体
        secret_degree = request.form.get('secret_degree', '')  #保密级别(密级)
        #计算机数据
        system = request.form.get('system', '')  #操作系统
        mac_addr = request.form.get('MAC', '')  #MAC地址
        upd_sys_time = request.form.get('upd_sys_time', '0000-00-00')  #系统更新时间
        disk_num = request.form.get('disk_num', 0)  #硬盘个数
        disk_type = request.form.get('disk_type', '')  #硬盘型号
        disk_volume = request.form.get('disk_volume', '')  #硬盘容量
        disk_code = request.form.get('disk_code', '')  #硬盘序列号
        ip_address = request.form.get('ip_address', '')  #IP地址
        hostname = request.form.get('hostname', '')  #主机名
        license = request.form.get('license', '')  #使用许可证号
        cpu = request.form.get('cpu', '')  #CPU规格
        memory_capacity = request.form.get('memory_capacity', '')  #内存容量
        cd_type = request.form.get('cd_type', '')  #光驱类型
        cd_type_num = request.form.get('cd_type_num', '')  #光驱型号
        fd = request.form.get('fd', 0)  #有无软驱
        card_reader = request.form.get('card_reader', 0)  #有无读卡器
        external = request.form.get('external', '')  #外接设备

        equ_type = request.form.get('equ_type')
        if int(status) == 0: status = u'已废弃'
        else: status = u'使用中'
        if int(fd) == 0: fd = u'无光驱'
        else: fd = u'有光驱'
        if int(card_reader) == 0: card_reader = u'无读卡器'
        else: card_reader = u'有读卡器'
        try:
            e = Equipment(name=name,
                          code=code,
                          type_code=type_code,
                          type_name=type_name,
                          brand=brand,
                          type_model=type_model,
                          equ_num=equ_num,
                          by_use=by_use,
                          use_unit=use_unit,
                          unit_num=unit_num,
                          depository=depository,
                          location=location,
                          buy_time=buy_time,
                          put_time=put_time,
                          out_time=out_time,
                          details=details,
                          status=status,
                          secret_degree=secret_degree,
                          system=system,
                          mac_addr=mac_addr,
                          upd_sys_time=upd_sys_time,
                          disk_num=disk_num,
                          disk_type=disk_type,
                          disk_volume=disk_volume,
                          disk_code=disk_code,
                          ip_address=ip_address,
                          hostname=hostname,
                          license=license,
                          cpu=cpu,
                          memory_capacity=memory_capacity,
                          cd_type=cd_type,
                          cd_type_num=cd_type_num,
                          fd=fd,
                          card_reader=card_reader,
                          external=external,
                          equ_type=equ_type)
            db.session.add(e)
            db.session.commit()
        except Exception, err:
            print err
        return redirect('/VEQ/1')
コード例 #12
0
def craftEquipment(inputs):
    """ @param inputs a json object with inputs."""
    # TODO: Break up this code into functional pieces.
    # TODO: Validate inputs.
    # TODO: Think hard about redesigning the crafting logic.
    equipment_template_key = inputs['equipment_template_key']
    # Make sure the player has all of the necessary resources.
    cost_to_craft = EQUIPMENT_TEMPLATE_CRAFT_COSTS[equipment_template_key]
    player_key = ndb.Key(urlsafe=inputs['player_id'])  # TODO: error handle.
    player = player_key.get()
    resources_to_put = []
    formula_input = {}
    # TODO: Make this more generic, instead of checking each. DRY this up.
    if cost_to_craft.metal > 0:
        # Check for adequate metal resources.
        if 'metal_resource_key' not in inputs:
            logging.error('metal_resource_key missing from input!')
            # TODO: handle failure better than returning none.
            return None
        resource_key = ndb.Key(urlsafe=inputs['metal_resource_key'])
        if resource_key in player.resources:
            resource = resource_key.get()
            template = resource.resource_template.get()
            if (resource.quantity >= cost_to_craft.metal
                    and template.resource_type
                    == RESOURCE_TYPES_INT_MAPPING[METAL_KEY]):
                resource.quantity -= cost_to_craft.metal
                resources_to_put.append(resource)
                formula_input[METAL_KEY] = template
                # TODO: Add crafting power formulas logic here!
            else:
                logging.error(
                    'Metal Quantity too low, or resource is not metal!')
                # TODO: handle failure better than returning none.
                return None
        else:
            logging.error('Player does not own metal resource!')
            # TODO: handle failure better than returning none.
            return None
    if cost_to_craft.wood > 0:
        # Check for adequate wood resources.
        if 'wood_resource_key' not in inputs:
            logging.error('wood_resource_key missing from input!')
            # TODO: handle failure better than returning none.
            return None
        resource_key = ndb.Key(urlsafe=inputs['wood_resource_key'])
        if resource_key in player.resources:
            resource = resource_key.get()
            template = resource.resource_template.get()
            if (resource.quantity >= cost_to_craft.wood
                    and template.resource_type
                    == RESOURCE_TYPES_INT_MAPPING[WOOD_KEY]):
                resource.quantity -= cost_to_craft.wood
                resources_to_put.append(resource)
                formula_input[WOOD_KEY] = template
                # TODO: Add crafting power formulas logic here!
            else:
                logging.error(
                    'Wood Quantity too low, or resource is not wood!')
                # TODO: handle failure better than returning none.
                return None
        else:
            logging.error('Player does not own wood resource!')
            # TODO: handle failure better than returning none.
            return None
    if cost_to_craft.leather > 0:
        # Check for adequate leather resources.
        if 'leather_resource_key' not in inputs:
            logging.error('leather_resource_key missing from input!')
            # TODO: handle failure better than returning none.
            return None
        resource_key = ndb.Key(urlsafe=inputs['leather_resource_key'])
        if resource_key in player.resources:
            resource = resource_key.get()
            template = resource.resource_template.get()
            if (resource.quantity >= cost_to_craft.leather
                    and template.resource_type
                    == RESOURCE_TYPES_INT_MAPPING[LEATHER_KEY]):
                resource.quantity -= cost_to_craft.leather
                resources_to_put.append(resource)
                formula_input[LEATHER_KEY] = template
                # TODO: Add crafting power formulas logic here!
            else:
                logging.error(
                    'Leather Quantity too low, or resource is not leather!')
                # TODO: handle failure better than returning none.
                return None
        else:
            logging.error('Player does not own leather resource!')
            # TODO: handle failure better than returning none.
            return None

    # Validation has passed. Create the equipment.
    equipment_type = EQUIPMENT_TEMPLATE_TO_TYPE_MAPPING[equipment_template_key]
    crafted_equipment = Equipment(equipment_type=equipment_type,
                                  player=player_key)

    if equipment_type == EQUIPMENT_TYPE_INT_MAPPING[WEAPON_KEY]:
        crafted_equipment.weapon_data = Weapon(
            weapon_type=WEAPON_TYPE_INT_MAPPING[equipment_template_key],
            power=int(
                getAttributeValue(
                    formula_input,
                    WEAPON_POWER_FORMULA[equipment_template_key])),
            reliability=getAttributeValue(
                formula_input,
                WEAPON_RELIABILITY_FORMULA[equipment_template_key]))
        player.equipment.append(crafted_equipment.put())
        player.put()

    # TODO: Handle armor crafting.

    # Crafting complete. Now update the resources.
    ndb.put_multi(resources_to_put)
コード例 #13
0
import sqlalchemy
import sqlalchemy.orm
from sqlalchemy import *
from sqlalchemy.orm import *
from create_db import connect_to_db

engine = connect_to_db()
Session = sessionmaker(bind=engine)
session = Session()

timeNominal1 = 1448254800
timeDeferred = 1448255460
timeNominal2 = 1448256545

e = Equipment(name='Temperature Controller',
              location='Power Plant',
              info='This piece of equipment controlls temperature set points')

di = DataInfo(equipment_id=2,
              name='Temperature',
              unit='C',
              longunit='Celsius',
              mType='setpoint')

d1 = Data(info_id=2,
          value=float(45),
          timestamp=datetime.datetime.fromtimestamp(float(timeNominal1)))
d2 = Data(info_id=2,
          value=float(40),
          timestamp=datetime.datetime.fromtimestamp(float(timeDeferred)))
d3 = Data(info_id=2,
コード例 #14
0
ファイル: main.py プロジェクト: almandBAS/gissmo
    # Search linked channels
    url = channel_url + '&station=%s' % s.code
    channels = get(url)
    for channel in channels:
        c = Channel(api_url, channel)
        c.station = s  # Add a link from channel to station
        s.channels.append(c)
        if c.network and c.network.code not in s.networks:
            s.networks.append(c.network.code)
        # Search linked parameters
        url = params_url + '&channel=%s' % c.id
        params = get(url)
        for param in params:
            p = Parameter(api_url, param)
            c.parameters.append(p)
    # Search equipments linked to the station, but not linked to a channel
    station_equipment_url = equipment_url + '&station=%s' % searched_site_code
    equipments = get(station_equipment_url)
    for equipment in equipments:
        e = Equipment(api_url, equipment)
        s.equipments.append(e)
    # Remember station
    result.append(s)

# FINALLY DISPLAY RESULT
for station in result:
    print(s)

# Bye bye!
sys.exit(0)
コード例 #15
0
from models import Data, DataInfo, Equipment
import time
import datetime
import sqlalchemy
import sqlalchemy.orm
from sqlalchemy import *
from sqlalchemy.orm import *
from create_db import connect_to_db

engine = connect_to_db()
Session = sessionmaker(bind=engine)
session = Session()

e = Equipment(name='Hertz Meter',
              location='Power Plant',
              info='This is a sensor that performs frequency readings')

di = DataInfo(equipment_id=1,
              name='frequency',
              unit='Hz',
              longunit='Hertz',
              mType='sensor')

session.add_all([e, di])

with open('dummydata.txt') as f:
    content = f.readlines()

for line in content:
    tup = line.split()
コード例 #16
0
ファイル: view.py プロジェクト: Z-YunFei/yunanfuwu
def addEquipment():
    '''
        新增设备
        将新设备添加至数据库
    :return: 数据添加结果
    '''
    child = request.args.get('child', None)
    user_id = child if child and child != 'None' else session.get('id')

    if not user_id:
        return jsonify({'msg': 'fail', 'data': 'please to login'})
    user = User.query.filter(User.id == user_id).first()

    name = request.form.get('name')
    class_ = request.form.get('class_')
    use_department = request.form.get('use_department')
    location = request.form.get('location')
    gaode_location = request.form.get('gaode_location')
    manufacturer = request.form.get('manufacturer')
    model = request.form.get('model')
    SIM_id = request.form.get("SIM_id")
    remarks = request.form.get('remarks')

    gaode_longitude, gaode_latitude = [
        float(x) for x in gaode_location.split(',')
    ]

    cityData = requests.get(
        'https://restapi.amap.com/v3/geocode/regeo?output=json&location={}&key=1f5f34e6c96735e4be689afb6ec22a82&radius=10&extensions=base'
        .format(gaode_location)).json()

    position_province = cityData['regeocode']['addressComponent']['province']
    position_city = cityData['regeocode']['addressComponent']['city']
    position_district = cityData['regeocode']['addressComponent']['district']

    position_province = position_province if position_province else None
    position_city = position_city if position_city else None
    position_district = position_district if position_district else None

    equipmentInfo = {
        'name': name,
        'use_department': use_department,
        'location': location,
        'gaode_latitude': gaode_latitude,
        'gaode_longitude': gaode_longitude,
        'class_': class_,
        'manufacturer': manufacturer,
        'model': model,
        'remarks': remarks,
        'SIM_id': SIM_id,
        'admin': user,
        'position_province': position_province,
        'position_city': position_city,
        'position_district': position_district
    }

    if equipmentInfo['class_'] == '电气':
        equipmentInfo['id'] = 'e_' + str(int(time.time()))

    try:
        equipment = Equipment(**equipmentInfo)
        equipment.group.append(user.group)
        while user.parent_id:
            user = user.parent
            equipment.group.append(user.group)
        db.session.add(equipment)
        db.session.commit()
    except Exception as e:
        print(e)
        return jsonify({
            'msg': 'fail',
            'data': 'add equipment error when commit database'
        })
    return jsonify({'msg': 'success', 'data': 'add success'})