コード例 #1
0
def data_organizer(raw_data: dict) -> dict:
    """
    Take unorganized dict data and produce an organized dict data.
    :param raw_data: Unorganized dict.
    :return: Organized dict.
    """
    main = raw_data.get('main')
    sys = raw_data.get('sys')
    data = dict(
        city=raw_data.get('name'),
        country=sys.get('country'),
        temp=main.get('temp'),
        temp_max=main.get('temp_max'),
        temp_min=main.get('temp_min'),
        humidity=main.get('humidity'),
        pressure=main.get('pressure'),
        sky=raw_data['weather'][0]['main'],
        sunrise=time_converter(sys.get('sunrise')),
        sunset=time_converter(sys.get('sunset')),
        wind=raw_data.get('wind').get('speed'),
        wind_deg=raw_data.get('deg'),
        dt=time_converter(raw_data.get('dt')),
        cloudiness=raw_data.get('clouds').get('all')
    )
    return data
コード例 #2
0
ファイル: weather.py プロジェクト: The-BigPanda/weather
def data_organizer(raw_data: dict) -> dict:
    """
    Take unorganized dict data and produce an organized dict data.
    :param raw_data: Unorganized dict.
    :return: Organized dict.
    """
    main = raw_data.get('main')
    sys = raw_data.get('sys')
    data = dict(
        city=raw_data.get('name'),
        country=sys.get('country'),
        temp=main.get('temp'),
        temp_max=main.get('temp_max'),
        temp_min=main.get('temp_min'),
        humidity=main.get('humidity'),
        pressure=main.get('pressure'),
        sky=raw_data['weather'][0]['main'],
        sunrise=time_converter(sys.get('sunrise')),
        sunset=time_converter(sys.get('sunset')),
        wind=raw_data.get('wind').get('speed'),
        wind_deg=raw_data.get('deg'),
        dt=time_converter(raw_data.get('dt')),
        cloudiness=raw_data.get('clouds').get('all')
    )
    return data
コード例 #3
0
ファイル: ks2apple.py プロジェクト: simon2077/matrix
def parse_system_info(report):
    '''Parse system information from report.
    @return header lines
    '''

    sys = get_system_info(report)
    if not sys:
        return []
    info = get_report_info(report)

    _s = lambda x: sys.get(x, '')
    _i = lambda x: info.get(x, '')

    headers = ['System Info: {']
    device = _s('machine')
    if device_map.has_key(device):
        device = device_map[device]
    headers.append('    Device:      {0}'.format(device))
    headers.append('    OS Version:  {0} {1} ({2})'.format(_s('system_name'), _s('system_version'), _s('os_version')))

    user_info = report.get("user", None)
    if user_info and user_info.get('WeChat'):
        jb_info = user_info.get('WeChat').get('Jailbreak', None) 
        if jb_info:
            headers.append('    Jailbreak:   {0}'.format(jb_info))

    mem = sys.get("memory")
    if mem:
        fmt = lambda x: "    Mem {0:6}:  {1:4} M".format(x, int(mem[x])/1024/1024)
        headers.append(fmt("usable")) 
        headers.append(show_color(fmt("free"))) 
        headers.append(fmt("size")) 

    headers.append('}')
    return headers
コード例 #4
0
def format_output(raw_data):
    main = raw_data.get('main')
    sys = raw_data.get('sys')

    data = dict(city=raw_data.get('name'),
                country=sys.get('country'),
                temp=main.get('temp'),
                temp_max=main.get('temp_max'),
                temp_min=main.get('temp_min'),
                humidity=main.get('humidity'),
                pressure=main.get('pressure'),
                sky=raw_data['weather'][0]['main'],
                sunrise=time_converter(sys.get('sunrise')),
                sunset=time_converter(sys.get('sunset')),
                wind=raw_data.get('wind').get('speed'),
                wind_deg=raw_data.get('deg'),
                dt=time_converter(raw_data.get('dt')),
                cloudiness=raw_data.get('clouds').get('all'))
    data['m_symbol'] = '\xb0' + 'C'
    s = '''---------------------------------------
  Current weather in: {city}, {country}:
  {temp}{m_symbol} {sky}
  Max: {temp_max}, Min: {temp_min}

  Wind Speed: {wind}, Degree: {wind_deg}
  Humidity: {humidity}
  Cloud: {cloudiness}
  Pressure: {pressure}
  Sunrise at: {sunrise}
  Sunset at: {sunset}

  Last update from the server: {dt}
  ---------------------------------------'''

    return s.format(**data)
コード例 #5
0
ファイル: client.py プロジェクト: pengchant/msgbox-client
    def createmsg_list(self, msg_info_data):
        """
        添加信息列表
        :param msg_info_data:  消息列表
        :return:
        """
        # 先清空root根下面的所有的历史消息
        self.tree.clear()
        # 设置根节点
        self.root = QTreeWidgetItem(self.tree)  # 设置根节点
        self.root.setText(0, "cssrc消息盒子(未读消息)")  # 设置根节点的名字
        self.root.setIcon(0, QIcon("static/loc.png"))  # 设置 根节点的图片

        try:
            msg_list = msg_info_data.get('data').get('msgs')
            sys_list = msg_info_data.get('data').get('sys')
            for sys in sys_list:
                child = QTreeWidgetItem()
                child.setText(0, sys.get("sysname"))
                child.setIcon(0, QIcon("static/app.png"))
                child.setText(1, "")
                child.setText(2, "")
                # 添加到根节点上
                self.root.addChild(child)
                # 添加二级节点
                for msg in msg_list:
                    # 将该系统下的所有的消息加载到节点上
                    if msg.get("from_sys") == sys.get("id"):
                        status = msg.get("msg_status")
                        sec_child = QTreeWidgetItem(child)
                        # sec_child.setToolTip("")
                        sec_child.setText(0, msg.get("msg_title"))
                        sec_child.setText(1, msg.get("msg_push_time"))
                        sec_child.setText(
                            2,
                            str(msg.get("id")) + "|" +
                            str(msg.get("msg_url")) + "|" + status)
                        if status == "WAITTING_READ":
                            sec_child.setIcon(0, QIcon("static/msg_alert.png"))
                        else:
                            sec_child.setIcon(0, QIcon("static/xx.png"))
        except Exception as e:
            print("解析异常")

        # 加载根节点的所有属性 与子控件
        self.tree.addTopLevelItem(self.root)

        # 给节点点击添加响应事件
        try:
            self.tree.clicked.disconnect(self.onClicked)  # 先取消绑定
        except:
            pass
        self.tree.clicked.connect(self.onClicked)

        # 节点全部展开看
        self.tree.expandAll()

        # 添加到父容器中设置位置
        self.tree.setGeometry(0, 0, 400, 580)
コード例 #6
0
def dataPath(sys, exp, id, setup, dtc, options={}):
    datapath = '/tmp'
    section = '%s mode:%s' % (dtc, setup)

    # backwards compatibility
    try:
        if options['testing']:
            datapath = sys.get('testing', 'datafolder')
        else:
            datapath = sys.get('experiment', 'folder', '')
        commonlocalpath = exp.get('common parameters', 'localdata', '')
        localdata = exp.get(section, 'localdata', commonlocalpath)
        if localdata:
            datapath = localdata
    except:
        # now we count on that the new way is successfull below
        pass

    # new way override old way above
    try:
        places = lowercaseKeysDict(sys.vars('storage places'))
        defaults = lowercaseKeysDict(sys.vars('storage defaults'))

        if options['testing']:
            datapath = places['test']
        else:
            dtcdefault = defaults.get(dtc, 'main')
            if dtcdefault in places:
                datapath = places[dtcdefault]
            else:
                # full path specified
                datapath = dtcdefault

        # check experiment file and override defaults if datafolder is specified
        commondefault = exp.get('common parameters', 'datafolder', datapath)
        if commondefault in places:
            datapath = places[commondefault]
        else:
            datapath = commondefault

        # and last check for setup specific override
        setupoverride = exp.get(section, 'datafolder', '')
        if setupoverride:
            if setupoverride in places:
                datapath = places[setupoverride]
            else:
                datapath = setupoverride
    except:
        # assumes old way if we get here
        pass

    datapath = os.path.join(datapath, id)
    return datapath
コード例 #7
0
    def initialize_connection(self):
        """
        The model followed with EMC XtremIO can be explained as follows:
        Each node has a initiator group created, when logged in for the first time. To this initiator group
        the initiator name is added for all the interfaces available on the node. The volumes are associated with
        the initiator group, thus making sure multipathing is established automatically.
        """

        sys = self.mgmt.request('clusters', 'GET', idx=1)['content']
        use_chap = (sys.get('chap-authentication-mode', 'disabled') !=
                    'disabled')
        discovery_chap = (sys.get('chap-discovery-mode', 'disabled') !=
                          'disabled')
        initiator = self._get_initiator()
        try:
            # check if the IG already exists
            self.mgmt.request('initiator-groups', 'GET',
                              name=self._get_ig())['content']
        except DeviceExceptionObjNotFound:
            # create an initiator group to hold the the initiator
            data = {'ig-name': self._get_ig()}
            self.mgmt.request('initiator-groups', 'POST', data)
        try:
            init = self.mgmt.request('initiators', 'GET',
                                     name=initiator)['content']
            if use_chap:
                chap_passwd = init['chap-authentication-initiator-' 'password']
                # delete the initiator to create a new one with password
                if not chap_passwd:
                    Message.new(
                        Info=
                        'initiator has no password while using chap removing it'
                    )
                    self.mgmt.request('initiators', 'DELETE', name=initiator)
                    # check if the initiator already exists
                    raise DeviceExceptionObjNotFound
        except DeviceExceptionObjNotFound:
            # create an initiator
            data = {
                'initiator-name': initiator,
                'ig-id': self._get_ig(),
                'port-address': initiator
            }
            if use_chap:
                data['initiator-authentication-user-name'] = 'chap_user'
                chap_passwd = self._get_password()
                data['initiator-authentication-password'] = chap_passwd
            if discovery_chap:
                data['initiator-discovery-user-name'] = 'chap_user'
                data['initiator-discovery-' 'password'] = self._get_password()
            self.mgmt.request('initiators', 'POST', data)
コード例 #8
0
    def initialize_connection(self):
        """
        The model followed with EMC XtremIO can be explained as follows:
        Each node has a initiator group created, when logged in for the first time. To this initiator group
        the initiator name is added for all the interfaces available on the node. The volumes are associated with
        the initiator group, thus making sure multipathing is established automatically.
        """

        sys = self.mgmt.request('clusters', 'GET', idx=1)['content']
        use_chap = (sys.get('chap-authentication-mode', 'disabled') !=
                    'disabled')
        discovery_chap = (sys.get('chap-discovery-mode', 'disabled') !=
                         'disabled')
        initiator = self._get_initiator()
        try:
            # check if the IG already exists
            self.mgmt.request('initiator-groups', 'GET',
                              name=self._get_ig())['content']
        except DeviceExceptionObjNotFound:
            # create an initiator group to hold the the initiator
            data = {'ig-name': self._get_ig()}
            self.mgmt.request('initiator-groups', 'POST', data)
        try:
            init = self.mgmt.request('initiators', 'GET',
                                     name=initiator)['content']
            if use_chap:
                chap_passwd = init['chap-authentication-initiator-'
                                   'password']
                # delete the initiator to create a new one with password
                if not chap_passwd:
                    Message.new(Info='initiator has no password while using chap removing it')
                    self.mgmt.request('initiators', 'DELETE', name=initiator)
                    # check if the initiator already exists
                    raise DeviceExceptionObjNotFound
        except DeviceExceptionObjNotFound:
            # create an initiator
            data = {'initiator-name': initiator,
                    'ig-id': self._get_ig(),
                    'port-address': initiator}
            if use_chap:
                data['initiator-authentication-user-name'] = 'chap_user'
                chap_passwd = self._get_password()
                data['initiator-authentication-password'] = chap_passwd
            if discovery_chap:
                data['initiator-discovery-user-name'] = 'chap_user'
                data['initiator-discovery-'
                     'password'] = self._get_password()
            self.mgmt.request('initiators', 'POST', data)
コード例 #9
0
def get_info(ipmi_ip=IPMI_IP, userid=USERNAME, pswd=PASSWORD):
    log.info("Getting Fan Info")
    fan_info_list = []
    # Mantle_utils
    # get_ceredentials (host_ip)
    # initialize the redpool
    # check_refish_supported
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    url = ("https://%s/redfish/v1/Chassis/" % ipmi_ip)
    response = requests.get(url, auth=(userid, pswd), verify=False)
    for sys in response.json().get("Members"):
        sub_url = sys.get("@odata.id")
        sys_url = ("https://%s%s" % (ipmi_ip, sub_url))
        resp = requests.get(sys_url, auth=(userid, pswd), verify=False)
        thermal_sub_url = resp.json().get("Thermal").get("@odata.id")
        thermal_url = ("https://%s%s" % (ipmi_ip, thermal_sub_url))
        thermal_resp = requests.get(thermal_url,
                                    auth=(userid, pswd),
                                    verify=False)
        for fan in thermal_resp.json().get("Fans"):
            fan_dict = {}
            fan_dict["Name"] = fan.get("Name")
            fan_dict["Status"] = fan.get("Status")
            fan_dict["ReadingUnits"] = fan.get("ReadingUnits")
            fan_dict["Reading"] = fan.get("Reading")
            fan_info_list.append(fan_dict)

    log.info("Fan Info List %s" % fan_info_list)
    return fan_info_list
コード例 #10
0
def get_info(ipmi_ip=IPMI_IP, userid=USERNAME, pswd=PASSWORD):
    print("Getting Power Info")
    power_info_list = []
    # Mantle_utils
    # get_ceredentials (host_ip)
    # initialize the redpool
    # check_refish_supported
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    url = ("https://%s/redfish/v1/Chassis/" % ipmi_ip)
    response = requests.get(url, auth=(userid, pswd), verify=False)
    print("Request response: %s" % response.json())
    for sys in response.json().get("Members"):
        sub_url = sys.get("@odata.id")
        sys_url = ("https://%s%s" % (ipmi_ip, sub_url))
        resp = requests.get(sys_url, auth=(userid, pswd), verify=False)
        power_sub_url = resp.json().get("Power").get("@odata.id")
        power_url = ("https://%s%s" % (ipmi_ip, power_sub_url))
        power_resp = requests.get(power_url, auth=(userid, pswd), verify=False)
        for power_supply in power_resp.json().get("PowerSupplies"):
            power_dict = {}
            power_dict["Name"] = power_supply.get("Name")
            power_dict["Status"] = power_supply.get("Status")
            power_dict["PowerSupplyType"] = power_supply.get("PowerSupplyType")
            power_dict["Model"] = power_supply.get("Model")
            power_dict["FirmwareVersion"] = power_supply.get("FirmwareVersion")
            power_info_list.append(power_dict)

    print("Power Info List\n %s" % power_info_list)
    return power_info_list
コード例 #11
0
def get_info(ipmi_ip=IPMI_IP, userid=USERNAME, pswd=PASSWORD):
    print("Getting Bios version")
    bios_info_list = []
    # Mantle_utils
    # get_ceredentials (host_ip)
    # initialize the redpool
    # check_refish_supported
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    url = ("https://%s/redfish/v1/Systems/" % ipmi_ip)
    response = requests.get(url, auth=(userid, pswd), verify=False)
    print("Request response: %s" % response.json())
    for sys in response.json().get("Members"):
        sub_url = sys.get("@odata.id")
        sys_url = ("https://%s%s" % (ipmi_ip, sub_url))
        resp = requests.get(sys_url, auth=(userid, pswd), verify=False)
        bios_info = {}
        bios_info["Manufacturer"] = resp.json().get("Manufacturer")
        bios_info["Model"] = resp.json().get("Model")
        bios_info["Version"] = resp.json().get("BiosVersion")
        bios_info["UUID"] = resp.json().get("UUID")
        bios_info["PartNumber"] = resp.json().get("PartNumber")
        bios_info["SerialNumber"] = resp.json().get("SerialNumber")
        bios_info_list.append(bios_info)

    print("BIOS Info List:\n %s" % bios_info_list)
    return bios_info_list
コード例 #12
0
def get_info(ipmi_ip=IPMI_IP, userid=USERNAME, pswd=PASSWORD):
    print("Getting BMC version")
    bmc_info_list = []
    # Mantle_utils
    # get_ceredentials (host_ip)
    # initialize the redpool
    # check_refish_supported
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    url = ("https://%s/redfish/v1/Managers/" % ipmi_ip)
    response = requests.get(url, auth=(userid, pswd), verify=False)
    print("Request response: %s" % response.json())
    for sys in response.json().get("Members"):
        sub_url = sys.get("@odata.id")
        sys_url = ("https://%s%s" % (ipmi_ip, sub_url))
        resp = requests.get(sys_url, auth=(userid, pswd), verify=False)
        pprint.pprint(resp.json())
        bmc_info = {}
        bmc_info["Manager type"] = resp.json().get("ManagerType")
        bmc_info["Model"] = resp.json().get("Model")
        bmc_info["Version"] = resp.json().get("FirmwareVersion")
        bmc_info["UUID"] = resp.json().get("UUID")
        bmc_info["Status"] = resp.json().get("Status")
        bmc_info_list.append(bmc_info)

    print("BMC Info List:\n %s" % bmc_info_list)
    return bmc_info_list
コード例 #13
0
def unifi_info():
    info = dict()

    data = unifi_get_stat('health')
    if data:
        subs = {
            sub['subsystem']: sub
            for sub in data if sub.get('subsystem') in ['wlan', 'lan']
        }

        wlan = subs.get('wlan')
        info['wlan_status'] = wlan.get('status')
        info['wlan_users'] = wlan.get('num_user')

        lan = subs.get('lan')
        info['lan_status'] = lan.get('status')
        info['lan_users'] = lan.get('num_user')

    data = unifi_get_stat('sysinfo')
    if data and len(data) > 0:
        sys = data[0]
        uptime = sys.get('uptime')
        info['uptime'] = floor(uptime / 3600)

    return info
コード例 #14
0
ファイル: NSeries.py プロジェクト: kyeagles76/omsdk
def check_classifier(myListoFDict, cls=None):
    sys_obj_str = 'SNMPv2-SMI::enterprises.674.10895.30'
    if isinstance(myListoFDict, list):
        for sys in myListoFDict:
            if sys_obj_str in sys.get('SysObjectID', "NA"):
                return (True, sys)
    elif isinstance(myListoFDict, dict):
        return (True, myListoFDict)
    return (False, myListoFDict)
コード例 #15
0
def parse_system_info(report):
    '''Parse system information from report.
    @return header lines
    '''

    sys = get_system_info(report)
    if not sys:
        return []
    info = get_report_info(report)

    _s = lambda x: sys.get(x, '')
    _i = lambda x: info.get(x, '')

    headers = ['System Info: {']
    device = _s('machine')
    headers.append('    Device:      {0}'.format(device))
    headers.append('    CpuArch:     {0}'.format(_s('cpu_arch')))
    headers.append('    OS Version:  {0} {1} ({2})'.format(
        _s('system_name'), _s('system_version'), _s('os_version')))
    global os_table
    os_table = '%s_%s' % (_s('system_version').replace('.',
                                                       '_'), _s('os_version'))
    if _s('cpu_arch') == "arm64e":
        os_table += '_%s' % _s('cpu_arch')
    print "os_table:", os_table

    user_info = report.get("user", None)
    if user_info and user_info.get('WeChat'):
        jb_info = user_info.get('WeChat').get('Jailbreak', None)
        if jb_info:
            headers.append('    Jailbreak:   {0}'.format(jb_info))

    mem = sys.get("memory")
    if mem:
        fmt = lambda x: "    Mem {0:6}:  {1:4} M".format(
            x,
            int(mem[x]) / 1024 / 1024)
        headers.append(fmt("usable"))
        headers.append(show_color(fmt("free")))
        headers.append(fmt("size"))

    headers.append('}')
    return headers
コード例 #16
0
def check_classifier(myListoFDict, cls=None):
    # Full OID to be expanded and added to list
    sobj_list = ['SNMPv2-SMI::enterprises.6027.1.3.20']
    if isinstance(myListoFDict, list):
        for sys in myListoFDict:
            if sys.get('SysObjectID', "NA") in sobj_list:
                return (True, sys)
    elif isinstance(myListoFDict, dict):
        return (True, myListoFDict)
    return (False, myListoFDict)
コード例 #17
0
def sync():
    global host
    global crit
    global warn
    global command
    global result
    global check_exit
    global ex

    result = None

    tempxml = '/CMD0/box_info.xml'
    tempurl = 'https://' + host + tempxml

    ssl.match_hostname = lambda cert, hostname: True
    req = urllib.request.Request(tempurl)

    credentials = ('%s:%s' % (username, password))
    encoded_credentials = base64.b64encode(credentials.encode('ascii'))
    req.add_header('Authorization',
                   'Basic %s' % encoded_credentials.decode("ascii"))

    res = urllib.request.urlopen(req)
    res_body = res.read()

    with open(xmlpath + command + host + '.xml', 'wb') as f:
        f.write(res_body)
    tree = ET.parse(xmlpath + command + host + '.xml')
    root = tree.getroot()

    for sys in root.iter('sys'):
        sync = sys.get('sync')

    if sync == "-":
        result = "no sync (" + sync + ")"
        check_exit = "CRITICAL"
        print(check_exit + ' - ' + result)
        ex(CRITICAL)

    elif sync != "BRI*" or "PRI*":
        result = "Sync Interface = " + sync
        check_exit = "OK"
        print(check_exit + ' - ' + result)
        ex(OK)

    else:
        print("Unknown Error!")
        ex(UNKNOWN)
コード例 #18
0
def resetreq():
    global host
    global crit
    global warn
    global command
    global result
    global check_exit
    global ex

    result = None

    tempxml = '/CMD0/box_info.xml'
    tempurl = 'https://' + host + tempxml

    ssl.match_hostname = lambda cert, hostname: True
    req = urllib.request.Request(tempurl)

    credentials = ('%s:%s' % (username, password))
    encoded_credentials = base64.b64encode(credentials.encode('ascii'))
    req.add_header('Authorization',
                   'Basic %s' % encoded_credentials.decode("ascii"))

    res = urllib.request.urlopen(req)
    res_body = res.read()

    with open(xmlpath + command + host + '.xml', 'wb') as f:
        f.write(res_body)
    tree = ET.parse(xmlpath + command + host + '.xml')
    root = tree.getroot()

    for sys in root.iter('sys'):
        rreset = sys.get('reset-required')

    if rreset != None:
        result = "Reset Required: " + rreset
        check_exit = "WARNING"
        print(check_exit + ' - ' + result)
        ex(WARNING)

    elif rreset is None:
        result = "No Reset Required"
        check_exit = "OK"
        print(check_exit + ' - ' + result)
        ex(OK)

    else:
        print("Unknown Error!")
        ex(UNKNOWN)
コード例 #19
0
ファイル: NGM.py プロジェクト: kyeagles76/omsdk
def check_classifier(myListoFDict, cls=None):
    # print('IN NGMs Satisfy me')
    # pprint(myListoFDict)
    valid = False
    flist = []
    type_dict = {
        "System": 2000,
        "Devices": 2000,
        "ComputeDevice": 1000,
        "IOModule": 4000
    }
    type_x = type_dict.get(cls, 2000)
    for sys in myListoFDict:
        if sys.get('Type', 0) == type_x:
            flist.append(sys)
    if flist:
        valid = True
    return (valid, flist)
コード例 #20
0
def parse_stack_info(report):
    result = []
    stack_info = report.get('stack_string', [])
    if not stack_info:
        return 'empty stack_string'

    sys = get_system_info(report)
    _s = lambda x: sys.get(x, '')
    system_name = _s('system_name')
    mask_pc = True
    if system_name == 'macOS':
        mask_pc = False

    app = report["report"]['process_name']
    img_info = get_binary_img_info(report)
    parse_backtrace(result, img_info, stack_info, mask_pc)

    text_stack = ['stack_info:']
    format_stack(text_stack, '  ', result)

    return text_stack
コード例 #21
0
def get_info(ipmi_ip=IPMI_IP, userid=USERNAME, pswd=PASSWORD):
    print("Getting CPU Info")
    cpu_info_list = []
    # Mantle_utils
    # get_ceredentials (host_ip)
    # initialize the redpool
    # check_refish_supported
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    url = ("https://%s/redfish/v1/Chassis/" % ipmi_ip)
    response = requests.get(url, auth=(userid, pswd), verify=False)
    print("Request response: %s" % response.json())
    for sys in response.json().get("Members"):
        sub_url = sys.get("@odata.id")
        sys_url = ("https://%s%s" % (ipmi_ip, sub_url))
        resp = requests.get(sys_url, auth=(userid, pswd), verify=False)
        thermal_sub_url = resp.json().get("Thermal").get("@odata.id")
        thermal_url = ("https://%s%s" % (ipmi_ip, thermal_sub_url))
        thermal_resp = requests.get(thermal_url,
                                    auth=(userid, pswd),
                                    verify=False)
        for temp in thermal_resp.json().get("Temperatures"):
            if "CPU" in temp.get("Name"):
                cpu_dict = {}
                cpu_dict["Name"] = temp.get("Name")
                cpu_dict["ReadingCelsius"] = temp.get("ReadingCelsius")
                proc_sub_url = temp.get("RelatedItem")[0].get("@odata.id")
                proc_url = ("https://%s%s" % (ipmi_ip, proc_sub_url))
                proc_resp = requests.get(proc_url,
                                         auth=(userid, pswd),
                                         verify=False)
                cpu_dict["Manufacturer"] = proc_resp.json().get("Manufacturer")
                cpu_dict["Model"] = proc_resp.json().get("Model")
                cpu_dict["Status"] = proc_resp.json().get("Status")
                cpu_dict["TotalCores"] = proc_resp.json().get("TotalCores")
                cpu_dict["TotalThreads"] = proc_resp.json().get("TotalThreads")
                cpu_info_list.append(cpu_dict)

    print("CPU Info List\n %s" % cpu_info_list)
    return cpu_info_list
コード例 #22
0
def get_info(ipmi_ip=IPMI_IP, userid=USERNAME, pswd=PASSWORD):
  print("Getting Memory Info")
  memory_info_list = []
  # Mantle_utils
  # get_ceredentials (host_ip)
  # initialize the redpool
  # check_refish_supported
  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  url = ("https://%s/redfish/v1/Systems/" % ipmi_ip)
  response = requests.get(url, auth=(userid, pswd), verify=False)
  print("Request response: %s" % response.json())
  for sys in response.json().get("Members"):
    sub_url = sys.get("@odata.id")
    sys_url = ("https://%s%s" % (ipmi_ip, sub_url))
    resp = requests.get(sys_url, auth=(userid, pswd), verify=False)
    thermal_sub_url = resp.json().get("Memory").get("@odata.id")
    thermal_url = ("https://%s%s" % (ipmi_ip, thermal_sub_url))
    memory_resp = requests.get(thermal_url, auth=(userid, pswd),
                                verify=False)
    for memory in memory_resp.json().get("Members"):
      mem_sub_url = memory.get("@odata.id")
      mem_url = ("https://%s%s" % (ipmi_ip, mem_sub_url))
      mem_resp = requests.get(mem_url, auth=(userid, pswd),
                                verify=False)
      mem_dict = {}
      mem_dict["Name"] = mem_resp.json().get("Name")
      mem_dict["CapacityMiB"] = mem_resp.json().get("CapacityMiB")
      mem_dict["MemoryType"] = mem_resp.json().get("MemoryType")
      mem_dict["MemoryDeviceType"] = mem_resp.json().get("MemoryDeviceType")
      mem_dict["Manufacturer"] = mem_resp.json().get("Manufacturer")
      mem_dict["Status"] = mem_resp.json().get("Status")
      memory_info_list.append(mem_dict)




  print("Memory Info List\n %s" % memory_info_list)
  return memory_info_list
コード例 #23
0
ファイル: example.py プロジェクト: DontTouchMyMind/education
from sys import getrecursionlimit as get


def fac(n):
    """
    Function calculates factorial of the number
    :param n:
    :return:
    """
    global count
    if n == 0:
        return 1
    else:
        count += 1
        return n * fac(n-1)


count = 0
result = fac(5)
print(result)
print(get())
print(count)
コード例 #24
0
ファイル: sysinfo.py プロジェクト: zhizhi100/HelloPython2
class Sysinfo(object):
    
    dao = None
    getsql = 'select value from g3server where param=?'
    setsql = 'update g3server set value=? where param=?'
    
    def __init__(self):
        myenv = env.Gtenv("")
        dir = myenv.getpath()    
        self.dao = mydao.Dao(path=dir + "/" + "HTTPD.dll",initsqls='')
        
    def set(self,key,val):
        succ,msg = self.dao.save(self.setsql, [val,key])
        return succ,msg
    
    def get(self,key):
        succ,msg,res = self.dao.get(self.getsql, [key])
        if succ:
            if res is None or len(res)!=1:
                return None
            else:
                return  res[0]
        else:
            return None
        
if __name__ == '__main__':
    sys = Sysinfo();
    print sys.set('servertime', 'val2')
    print sys.get('servertime')
    pass
コード例 #25
0
    def load_entity_type(self, world, filename, funcholder=None):
        """Returns an EntityType instance.

        The filename is one of the entity type filenames
        described by the world. EntityType must be called
        to create the instance after processing the file's
        content."""

        try:
            item_types = []  # Entity's item definitions

            etype = etree.parse(open(filename), parser=LineTrackingParser())
            name = etype.getroot().get('name')
            id = etype.getroot().get('id')

            functions = {}
            base = {'attr': {}, 'flags': set()}
            variants = {}
            systems = []
            default = {}

            def import_attr(el, level=1):
                href = el.get('href')
                imported = etree.parse(open(href), parser=LineTrackingParser())

                for a in imported.getroot():
                    if a.tag == "attribute":
                        if a.get('key') not in default:
                            default[a.get('key')] = eval(a.get('value'))

                    elif a.tag == "declare":
                        default[a.get('key')] = None

                    elif a.tag == "import":
                        import_attr(a, level + 1)

                    elif a.tag == "flag":
                        base['flags'].add(a.get('name'))

                    elif a.tag == "unflag":
                        base['flags'] -= {a.get('name')}

                    elif a.tag == "static" and a.get(
                            'name') not in base['attr']:
                        base['attr'][a.get('name')] = eval(a.get('value'))

                    elif a.tag == "function":
                        if (a.get('name') not in functions) or (
                                level <= getattr(functions[a.get('name')],
                                                 '__priority', 0)):
                            fname = a.get('name')

                            for fnc in funcholder.quick(
                                    "{}-{}".format(
                                        imported.getroot().get('name'),
                                        a.get('name')),
                                    a.text,
                                    linepad=a._start_line,
                                    filename=href).values():
                                if fnc.__lookup_name__ == fname:
                                    setattr(fnc, '__priority', level)
                                    setattr(fnc, '__funcspace',
                                            imported.getroot().get('name'))

                                    functions[fname] = fnc

                                    break

                            else:
                                raise RuntimeError(
                                    "No matching function for method '{}' in while parsing Attribute Imports '{}' referenced by Entity Type '{}'!"
                                    .format(fname,
                                            imported.getroot().get('name'),
                                            id))

                    elif a.tag == 'item':
                        name = a.get('name')

                        i = {
                            'name': name,
                            'functions': {},
                            'attr': {},
                            'flags': set()
                        }

                        for char in a:
                            if char.tag == 'function':
                                i['functions'][char.get(
                                    'name')] = funcholder.quick(
                                        '{}-{}'.format(a.get('name'),
                                                       char.get('name')),
                                        char.text,
                                        linepad=char._start_line,
                                        filename=href)

                            elif char.tag == 'attribute':
                                val = char.get('value')

                                if val:
                                    i['attr'][char.get('key')] = eval(val)

                                else:
                                    i['attr'][char.get('key')] = None

                            elif char.tag == 'flag':
                                i['flags'].add(char.get('name'))

                        item_types.append(i)

            _f = funcholder is None

            if _f:
                funcholder = embedcode.CodeHolder()

            for sub in etype.getroot():
                if sub.tag == "functions":
                    for f in sub:
                        if f.tag == "function":
                            fname = f.get('name')

                            for fnc in funcholder.quick(
                                    "{}-{}".format(id, f.get('name')),
                                    f.text,
                                    linepad=f._start_line,
                                    filename=filename).values():
                                if fnc.__lookup_name__ == fname:
                                    functions[fname] = fnc
                                    break

                            else:
                                raise RuntimeError(
                                    "No matching function for method '{}' while parsing Entity Type '{}'!"
                                    .format(f.get('name'), id))

                elif sub.tag == "base":
                    for a in sub:
                        if a.tag == "attr":
                            base['attr'][a.get('name')] = eval(a.get('value'))

                        elif a.tag == "flag":
                            base['flags'].add(a.get('name'))

                        elif a.tag == "unflag":
                            base['flags'] -= {a.get('name')}

                elif sub.tag == "systems":
                    for sys in sub:
                        if sys.tag == "system":
                            sname = sys.get('name')

                            for fnc in funcholder.quick(
                                    "{}-{}".format(id, sname),
                                    open(sys.get('href')).read(),
                                    filename=sys.get('href')).values():
                                if fnc.__lookup_name__ == sname:
                                    systems.append(fnc)
                                    break

                            else:
                                raise RuntimeError(
                                    "No matching function for system '{}' while parsing Entity Type '{}'!"
                                    .format(sys.get('name'), id))

                elif sub.tag == "default":
                    for att in sub:
                        if att.tag == "import":
                            # print("Importing attribute library: {}".format(a.get('name')))
                            import_attr(att)

                        elif a.tag == "declare":
                            default[att.get('key')] = None

                        elif att.tag == "attribute":
                            default[att.get('key')] = eval(att.get('value'))

                elif sub.tag == "itemdefs":
                    for item in sub:
                        if item.tag == 'item':
                            i = {
                                'name': item.get('name'),
                                'functions': {},
                                'attr': {},
                                'flags': set()
                            }

                            for char in item:
                                if char.tag == 'function':
                                    cname = char.get('name')

                                    for fnc in funcholder.quick(
                                            '{}-{}'.format(i['name'], cname),
                                            char.text,
                                            linepad=char._start_line,
                                            filename=filename).values():
                                        if fnc.__lookup_name__ == cname:
                                            i['functions'][cname] = fnc
                                            break

                                    else:
                                        raise RuntimeError(
                                            "No matching function for item function '{}' while parsing item '{}' in Entity Type '{}'!"
                                            .format(cname, i['name'], id))

                                elif char.tag == 'attribute':
                                    val = char.get('value')

                                    if val:
                                        i['attr'][char.get('key')] = eval(val)

                                    else:
                                        i['attr'][char.get('key')] = None

                                elif char.tag == 'flag':
                                    i['flags'].add(char.get('name'))

                            item_types.append(i)

                elif sub.tag == "variants":
                    for va in sub:
                        v = {
                            'name': va.get('name'),
                            'id': va.get('id'),
                            'attr': {},
                            'flags': set(),
                            'default': {},
                            'systems': []
                        }

                        for a in va:
                            if a.tag == "attr":
                                v['attr'][a.get('name')] = eval(a.get('value'))

                            elif a.tag == "flag":
                                v['flags'].add(a.get('name'))

                            elif a.tag == "unflag":
                                v['flags'] -= {a.get('name')}

                            elif a.tag == "default":
                                v['default'][a.get('key')] = eval(
                                    a.get('value'))

                            elif a.tag == "system":
                                sname = sys.get('name')

                                for fnc in funcholder.quick(
                                        "{}-{}-{}".format(id, sname),
                                        v['id'],
                                        open(sys.get('href')).read(),
                                        filename=sys.get('href')).values():
                                    if fnc.__lookup_name__ == sname:
                                        v.systems.append(fnc)
                                        break

                                else:
                                    raise RuntimeError(
                                        "No matching function for system '{}' while parsing Entity Type '{}'!"
                                        .format(sys.get('name'), id))

                        variants[va.get('id')] = v

        finally:
            if _f:
                funcholder.deinit()

        logging.debug(
            "Imported Entity Type {}, with {} variants, {} functions and {} item types loaded."
            .format(name, len(variants), len(functions), len(item_types)))

        return (EntityType(name, id, base, variants, functions, systems,
                           default), item_types)
コード例 #26
0
def Misson_Gen(argv=''):

    # print(argv)
    if "/?" in argv:
        print("Canonn System Numberwang:")
        print(" /new = Force all new data")
        print(" /safe = Do not post results to Google")
        print(" /wait = Pause console at end to review output")
        print(" /schedule = Run according to Patrol Schedule")

        quit

    # check if any action is scheduled and apply the specified argument, exit if no action scheduled
    if "/schedule" in argv:
        schedule = CSNSchedule()
        if schedule:
            argv += [f"/{schedule}"]
        else:
            print('No Schedule')
            return None

    bubble = Bubble.Bubble()
    faction_systems = bubble.localspace
    factionnames = bubble.factionnames
    orides = list

    if LOCAL_OVERRIDE:
        # Local Overrides
        oridefile = f'data\\{factionnames[0]}Overrides.csv'
        if os.path.isfile(oridefile):
            with open(oridefile, newline='') as io:
                reader = csv.reader(io, delimiter='\t')
                orides = list(reader)
            for x in orides[1:]:  # Yeah, can probably be done in 1 statement
                x[1] = int(x[1])
    elif '/safe' in argv:
        # Google Sheet Via Read
        orides = CSNOverRideReadSafe()
    else:
        # Google Sheet via API
        orides = CSNOverRideRead()

    try:
        with open(f'data\\{factionnames[0]}Message.json', 'r') as io:
            oldmessage = json.load(io)
    except:
        oldmessage = []

    try:
        with open(f'data\\{factionnames[0]}Invaders.json', 'r') as io:
            invaders = json.load(io)
    except:
        invaders = []

    messages = []
    active_states = []
    pending_states = []
    recovering_states = []
    ootsystems = []
    detected_retreats = []

    dIcons = {
        "war": '<:EliteEagle:231083794700959744> ',
        "election": ':ballot_box: ',
        "civilwar": '<:EliteEagle:231083794700959744> ',
        "override": '<:canonn:231835416548999168> ',
        "push": '<:Salute2:500679418692501506> ',
        "data": ':eyes: ',
        "infgap": ':dagger: ',
        "mininf": ':chart_with_downwards_trend: ',
        "info": ':information_source: ',
        "end": ':clap: ',
        "FC": ':anchor: '
    }

    print(f'CSN Missions:')
    # Create a single Message for each faction system
    faction_systems = dict(filter(lambda x: x[1], faction_systems.items()))
    for i, key in enumerate(faction_systems):
        update_progress(i / len(faction_systems), key)
        sys = faction_systems[key]
        if sys:
            sys['factions'].sort(key=lambda x: x['influence'], reverse=True)
            factions = sys['factions']
            empire = sys['empire']
            happytext = empire['faction_details']['faction_presence'][
                'happiness']
            happy = 'Elated' if happytext == '$faction_happinessband1;' else 'Happy' if happytext == '$faction_happinessband2;' else 'Pieved'

            conflict = None

            if len(factions) > 1:
                gap = factions[0]["influence"] - factions[1]["influence"]
                gapfromtop = factions[0]["influence"] - (empire['influence'])
            else:
                gap = 100
                gapfromtop = 0

            updated = Bubble.EliteBGSDateTime(sys["updated_at"])
            age = datetime.now() - updated
            oride = list(filter(lambda x: x[0] == sys["system_name"], orides))
            faction_systems[key][
                'override'] = oride[0][4] if oride else 'Natural'

            if sys['name'] == 'DEBUG':
                print(f'Debug')

            # Single Message per sysme for Patrol
            if faction_systems[key]['override'] != 'Natural':  # OVERRIDE!
                for newmessage in oride:
                    messages.append(
                        amessage(
                            sys, newmessage[1], newmessage[2].format(
                                gap=gap, inf=empire['influence'], happy=happy)
                            + '*', dIcons['override']
                            if newmessage[3] == '' else dIcons[newmessage[3]]))

            if faction_systems[key]['override'] != 'Override':
                # Conflict Active
                if len(
                        list(
                            filter(
                                lambda x: x['state'] in
                                {'war', 'election', 'civilwar'},
                                empire['active_states']))) > 0:
                    conflict = empire["conflicts"][0]
                    messages.append(
                        amessage(
                            sys,
                            2,
                            '{3} against {0} ({1} v {2})'.format(
                                conflict["opponent_name"],
                                conflict["days_won"],
                                bubble.dayswon(sys["system_name"],
                                               conflict["opponent_name"]),
                                conflict["type"].title()),
                            dIcons[conflict["type"]],
                        ))
                # Conflict Pending
                elif len(
                        list(
                            filter(
                                lambda x: x['state'] in
                                {'war', 'election', 'civilwar'},
                                empire['pending_states']))) > 0:
                    conflict = empire["conflicts"][0]
                    messages.append(
                        amessage(
                            sys,
                            2,
                            '{1} Pending with {0}. No action required while Pending, but you can prepare'
                            .format(conflict["opponent_name"],
                                    conflict["type"].title()),
                            dIcons[conflict["type"]],
                        ))

                if (not conflict) and faction_systems[key]['override'] in {
                        'Addition', 'Natural'
                }:
                    # Not yet in control
                    if factions[0]['name'] not in factionnames:
                        messages.append(
                            amessage(
                                sys, 3,
                                f'Urgent: {sys["empire"]["name"]} {availableactions(faction_systems[key],factionnames)} to gain system control (gap {gapfromtop:4.3}%)',
                                dIcons['push']))
                    # Gap to 2nd place is low
                    elif gap < M_INFGAP:
                        messages.append(
                            amessage(
                                sys, 4,
                                f'Required: {sys["empire"]["name"]} {availableactions(faction_systems[key],factionnames)} ({factions[1]["name"]} is threatening, gap is only {gap:4.3}%)',
                                dIcons['infgap']))

            # Multi Messages
            # Data out of date
            if age.days > (factions[0]['influence'] / 10):
                messages.append(
                    amessage(
                        sys, 11,
                        f'Scan System to update data {int(age.days)} days old',
                        dIcons['data']))

            # Pending Tritium Refinary Low Price
            if (len(
                    list(
                        filter(
                            lambda x: x[
                                'state'] in {'drought', 'blight', 'terrorism'},
                            empire['pending_states']))) > 0) and sys.get(
                                'sellsTritium', False):
                messages.append(
                    amessage(sys, 25, f'Tritium Opportunity Warning',
                             dIcons['data']))

            # Active Tritium Refinary Low Price
            if (len(
                    list(
                        filter(
                            lambda x: x[
                                'state'] in {'drought', 'blight', 'terrorism'},
                            empire['active_states']))) > 0) and sys.get(
                                'sellsTritium', False):
                messages.append(
                    amessage(sys, 24, f'Tritium Opportunity Active',
                             dIcons['data']))

            # GOLDRUSH
            if next(
                (x for x in empire['active_states'] + empire['pending_states']
                 if x['state'] in {'infrastructurefailure'}), None):
                if next((x for x in sys['stations']
                         if x['economy'] in {'$economy_extraction;'}), None):
                    messages.append(
                        amessage(
                            sys, 24, "Super " if next(
                                (x for x in empire['active_states'] +
                                 empire['pending_states']
                                 if x['state'] in {'civil liberty'}), None)
                            else "" + f"Gold Rush Active or Pending",
                            dIcons['data']))

            # Conflict Complete Info - Additional Message, not for Patrol, but for Discord
            if len(
                    list(
                        filter(
                            lambda x: x['state'
                                        ] in {'war', 'election', 'civilwar'},
                            empire['recovering_states']))) > 0:
                conflict = empire["conflicts"][0]
                if conflict["days_won"] == bubble.dayswon(
                        sys["system_name"], conflict["opponent_name"]):
                    # Draw
                    asset = ''
                elif conflict["days_won"] > bubble.dayswon(
                        sys["system_name"], conflict["opponent_name"]):
                    # Won
                    asset = bubble.assetatrisk(sys["system_name"],
                                               conflict["opponent_name"])
                    if asset != '':
                        asset = 'Gained ' + asset
                else:
                    # Lost
                    asset = conflict["stake"]
                    if asset != '':
                        asset = 'Lost ' + asset

                messages.append(
                    amessage(
                        sys, 21,
                        '{3} against {0} Complete ({1} v {2}) {4}'.format(
                            conflict["opponent_name"], conflict["days_won"],
                            bubble.dayswon(sys["system_name"],
                                           conflict["opponent_name"]),
                            conflict["type"].title(), asset), dIcons["info"]))

            # Record All States for Usefull Summary Information
            for x in empire['active_states']:
                active_states.append([sys["system_name"], x["state"]])
            for x in empire['pending_states']:
                pending_states.append([sys["system_name"], x["state"]])
            for x in empire['recovering_states']:
                recovering_states.append([sys["system_name"], x["state"]])

            # Look for active Retreats
            for faction in sys['factions']:
                if next((x for x in faction['active_states']
                         if x['state'] == 'retreat'),
                        None) and sys['name'] not in detected_retreats:
                    detected_retreats.append(sys['name'])

    update_progress(1)

    # Add Detected Retreats
    if detected_retreats:
        print('')
        messages.append(
            amessage('Retreats Detected in', 25, ', '.join(detected_retreats),
                     dIcons['data']))

    # All Canonn Systems Processed
    # Messages for External Systems
    for ex in orides[1:]:
        if sum(faction_systems[x]["system_name"] == ex[0]
               for x in faction_systems) == 0:
            #exsys = bubble.findsystem(ex[0])
            exsys = api.getsystem(ex[0])
            if exsys:
                ex[2] = ex[2].replace(
                    '{inf}', f"{round(exsys['factions'][0]['influence'],1)}")
                messages.append(
                    amessage(
                        exsys, ex[1], ex[2] + '*',
                        dIcons['override'] if ex[3] == '' else dIcons[ex[3]],
                        'None'))
            else:
                print(f'!Override Ignored : {ex[0]} {ex[2]}')

    # Invasion Alert
    if '/new' in argv:  # Only worth processing once per day after the EDDB Data Dump at about 06:00
        invaders = InvasionAlert(factionnames[0])
    for sys in invaders:
        sys["system_name"] = sys["name"]
        # trim spurious data that was giving circular reference errors when trying to save
        sys['minor_faction_presences'] = list()
        sys['xcube'] = list()
        if sys['controlling_minor_faction'] in sys[
                'pf']:  # Policy is we allow NPC to arrive so they fill the system and block PC factions
            messages.append(
                amessage(
                    sys, 10,
                    f"{sys['controlling_minor_faction']} are targeting {sys['invading']} within {sys['cycles']} cycles : We should do something about this ({round(sys['influence'],1)}%)",
                    dIcons['data']))

    # Lowest Gaps for PUSH message
    l = list(
        filter(
            lambda x: faction_systems[x]['override'] == 'Addition' or
            not hasmessage(messages, faction_systems[x]['system_name']),
            faction_systems))

    l.sort(key=lambda s: faction_systems[s]['factions'][0]['influence'] -
           faction_systems[s]['factions'][1]['influence']
           if len(faction_systems[s]['factions']) > 1 else 100)

    for x in l[:3]:
        sys = faction_systems[x]
        if sys["factions"][0]["influence"] - sys["factions"][1][
                "influence"] < 35:  # At a 35% Gap, it becomes spam
            messages.append(
                amessage(
                    sys, 5,
                    f'Suggestion: {sys["empire"]["name"]} {availableactions(sys,factionnames)} (gap to {sys["factions"][1]["name"]} is {sys["factions"][0]["influence"]-sys["factions"][1]["influence"]:4.3}%)',
                    dIcons['mininf']))

    messages.sort()

    # Fleet Carrier Locations
    carriers = CSNFleetCarrierRead()
    for carrier in carriers:
        currentsystem = None
        if carrier['id'][0] != '!':
            try:
                thiscarrier = api.getfleetcarrier(carrier['id'])
                currentsystem = api.eddbSystem(thiscarrier['current_system'])
                messages.append(
                    amessage(currentsystem, 9,
                             f'{carrier["name"]} ({carrier["role"]})',
                             dIcons['FC'], 'Canonn'))
            except:
                pass
            if not currentsystem:
                print(f'!!! Fleet Carrier {carrier["id"]} Failed !!!')

    # Looks for changes in Discord suitable Messages since last run for WebHook
    messagechanges = []
    for x in messages:
        if (x not in oldmessage) or ('/new' in argv):
            messagechanges.append(x)
    # Looks to see what systems no longer have a message of any type
    for x in oldmessage:
        s = list(
            filter(
                lambda y: y[1] == x[1] and y[8] not in
                [dIcons['FC'], dIcons['info']], messages))
        if len(s) == 0 and x[8] not in [dIcons['FC'], dIcons['info']]:
            messagechanges.append(x)
            messagechanges[len(messagechanges) - 1][7] = '~~' + \
                messagechanges[len(messagechanges) - 1][7] + \
                '~~ : Mission Complete'
            messagechanges[len(messagechanges) - 1][8] = dIcons['end']

    for m in messages:
        print(f'{m[1]} : {m[7]}')

    # Write Orders various formats
    with open(f'data\\{factionnames[0]}Patrol.Csv',
              'w') as io:  # CSV for Humans
        io.writelines(f'System,X,Y,Z,Priority,Message\n')
        io.writelines(f'{x[1]},{x[2]},{x[3]},{x[4]},{x[5]},{x[7]}\n'
                      for x in messages)
    with open(f'data\\{factionnames[0]}DiscordPatrol.txt',
              'w') as io:  # Text Version for Discord
        io.writelines(f'Canonn System Numberwang\n')
        io.writelines(
            f'{x[8]}{x[1]} : {x[7]}\n'
            for x in filter(lambda x: x[0] < 11 or x[0] > 20, messages))
    with open(f'data\\{factionnames[0]}DiscordWebhook.txt',
              'w') as io:  # Webhook Text Version for Discord
        io.writelines(
            f'{x[8]}{x[1]} : {x[7]}\n'
            for x in filter(lambda x: x[0] < 11 or x[0] > 20, messagechanges))
    with open(f'data\\{factionnames[0]}Message.json',
              'w') as io:  # Dump to file for comparison next run
        json.dump(messages, io, indent=4)
    with open(f'data\\{factionnames[0]}Invaders.json',
              'w') as io:  # Dump to file for comparison next run
        json.dump(invaders, io, indent=4)

    # Discord Webhook
    if CSNSettings.wh_id and len(
            list(filter(lambda x: x[0] < 11 or x[0] > 20,
                        messagechanges))) > 0:
        wh_text = ''
        wh = Webhook.partial(CSNSettings.wh_id,
                             CSNSettings.wh_token,
                             adapter=RequestsWebhookAdapter())
        for x in filter(lambda x: x[0] < 11 or x[0] > 20, messagechanges):
            wh_text += f'{x[8]}{x[1]} : {x[7]}\n'
        if wh_text != '':
            wh.send(
                f'{"**Full Report**" if ("/new" in argv) else "Latest News"} <:canonn:231835416548999168> \n{wh_text}'
            )

    # Patrol to send to Google
    patrol = []
    for x in filter(lambda x: x[0] <= 20, messages):
        patrol.append(x[1:9])
    if not ('/safe' in argv):
        CSNPatrolWrite(patrol)

    if '/new' in argv:
        CSNAttractions(faction_systems)

    print('*** Missions Generated : Consuming {0} requests ***'.format(
        api.NREQ))
    if ('/wait') in argv:
        input("Press Enter to continue...")
コード例 #27
0
def temp():
    global host
    global crit
    global warn
    global command
    global result
    global check_exit
    global ex

    result = None

    tempxml = '/CMD0/box_info.xml'
    tempurl = 'https://' + host + tempxml

    ssl.match_hostname = lambda cert, hostname: True
    req = urllib.request.Request(tempurl)

    credentials = ('%s:%s' % (username, password))
    encoded_credentials = base64.b64encode(credentials.encode('ascii'))
    req.add_header('Authorization',
                   'Basic %s' % encoded_credentials.decode("ascii"))

    res = urllib.request.urlopen(req)
    res_body = res.read()

    with open(xmlpath + command + host + '.xml', 'wb') as f:
        f.write(res_body)
    tree = ET.parse(xmlpath + command + host + '.xml')
    root = tree.getroot()

    for sys in root.iter('sys'):
        systemp = sys.get('temp')

    if systemp is None:
        result = "Temperature not available"

        check_exit = "UNKNOWN"
        print(check_exit + ' - ' + result)
        ex(UNKNOWN)

    elif systemp > crit:
        result = "Temprature is " + systemp + "°C | Temprature=" + systemp + ";" + warn + ";" + crit
        check_exit = "CRITICAL"
        print(check_exit + ' - ' + result)
        ex(CRITICAL)

    elif systemp > warn:
        result = "Temprature is " + systemp + "°C | Temprature=" + systemp + ";" + warn + ";" + crit
        check_exit = "WARNING"
        print(check_exit + ' - ' + result)
        ex(WARNING)

    elif systemp < warn:
        result = "Temprature is " + systemp + "°C | Temprature=" + systemp + ";" + warn + ";" + crit
        check_exit = "OK"
        print(check_exit + ' - ' + result)
        ex(OK)

    else:
        print("Unknown Error!")
        ex(UNKNOWN)
コード例 #28
0
ファイル: settings.py プロジェクト: free8011/wormhole_whApp
            print mv.VERSION
            print mv.sw_path_1
            '''

    XSI_VERSION_LIST = VersionCheck.Xsi()
    NUKE_VERSION_LIST = VersionCheck.Nuke()
    #print VersionCheck.Python()

    MAX_VERSION_LIST = VersionCheck.Max()
    '''
    if (MAX_VERSION_LIST):
        for mx in MAX_VERSION_LIST:
            print mx.VERSION
            print mx.sw_path_1
            '''


#------------------------------------------#

sys = {'Windows': SYSTEM_TYPE.SYS_WINDOWS, 'Darwin': SYSTEM_TYPE.SYS_OSX}

SYSTEM_INFO = sys.get(platform.system())

switch = {
    SYSTEM_TYPE.SYS_WINDOWS: set_sys_window,
    SYSTEM_TYPE.SYS_OSX: set_sys_osx
}

f = switch.get(SYSTEM_INFO)
f()