Python uuid 模块,getnode() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用uuid.getnode()

项目:AlexaPi    作者:alexa-pi    | 项目源码 | 文件源码
def index(self):
        sd = json.dumps({
            "alexa:all": {
                "productID": config['alexa']['Device_Type_ID'],
                "productInstanceAttributes": {
                    "deviceSerialNumber": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest()
                }
            }
        })

        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url() + "code"
        payload = {
            "client_id": config['alexa']['Client_ID'],
            "scope": "alexa:all",
            "scope_data": sd,
            "response_type": "code",
            "redirect_uri": callback
        }
        req = requests.Request('GET', url, params=payload)
        prepared_req = req.prepare()
        raise cherrypy.HTTPRedirect(prepared_req.url)
项目:JimV-N    作者:jamesiter    | 项目源码 | 文件源码
def __init__(self):
        self.conn = None
        self.dirty_scene = False
        self.guest = None
        self.guest_mapping_by_uuid = dict()
        self.hostname = ji.Common.get_hostname()
        self.node_id = uuid.getnode()
        self.cpu = psutil.cpu_count()
        self.memory = psutil.virtual_memory().total
        self.interfaces = dict()
        self.disks = dict()
        self.guest_callbacks = list()
        self.interval = 60
        # self.last_host_cpu_time = dict()
        self.last_host_traffic = dict()
        self.last_host_disk_io = dict()
        self.last_guest_cpu_time = dict()
        self.last_guest_traffic = dict()
        self.last_guest_disk_io = dict()
        self.ts = ji.Common.ts()
        self.ssh_client = None
项目:guiabolso2csv    作者:hugombarreto    | 项目源码 | 文件源码
def __init__(self, email, password):
        self.email = email
        self.password = password
        self.device_token = hashlib.md5(str(uuid.getnode())).hexdigest()
        self.session = requests.Session()
        self.login()
        basic_info = self.get_basic_info()
        self.categories = basic_info["GB.categories"]
        self.months = basic_info["GB.months"]
        self.statements = basic_info["GB.statements"]
        self.fieldnames = [u'name', u'label', u'date', u'account', u'category',
                           u'subcategory', u'duplicated', u'currency',
                           u'value', u'deleted']

        self.category_resolver = {}
        for categ in self.categories:
            for sub_categ in categ['categories']:
                self.category_resolver[sub_categ['id']] = \
                    (categ['name'], sub_categ['name'])

        self.account_resolver = {}
        for account in self.statements:
            for sub_account in account['accounts']:
                self.account_resolver[sub_account['id']] = sub_account['name']
项目:gdistcc    作者:apeabody    | 项目源码 | 文件源码
def list_instances(project, zone, globalinstances, distro, includeterm):

    # NOT thread safe
    credentials = GoogleCredentials.get_application_default()
    compute = discovery.build('compute', 'v1', credentials=credentials)

    result = compute.instances().list(project=project, zone=zone).execute()
    if ('items' in result):
        print('%s instances in zone %s:' % (project, zone))
        instancenames = []
        name = prefix + '-' + distro
        if not globalinstances:
            name += '-' + format(str(uuid.getnode())[:8:-1])
        for instance in result['items']:
            if name in instance['name']:
                print(' - ' + instance['name'] + ' - ' + instance['status'])
                if (instance['status'] == 'RUNNING' or includeterm): 
                    instancenames.append(instance['name'])
        return instancenames if (len(instancenames) > 0) else False
    return False
# [END list_instances]


# [START check_gceproject]
项目:alexa-client    作者:ewenchou    | 项目源码 | 文件源码
def index(self):
        sd = json.dumps({
            "alexa:all": {
                "productID": PRODUCT_ID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": uuid.getnode()
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url() + "authresponse"
        payload = {
            "client_id": CLIENT_ID,
            "scope": "alexa:all",
            "scope_data": sd,
            "response_type": "code",
            "redirect_uri": callback
        }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:monique    作者:monique-dashboards    | 项目源码 | 文件源码
def uuid_with_timestamp(microseconds, lowest_val=False, randomize=False):
    ts = int(microseconds * 10) + long(0x01b21dd213814000)
    time_low = ts & long(0xffffffff)
    time_mid = (ts >> 32) & long(0xffff)
    time_hi_version = (ts >> long(48)) & long(0x0fff)
    if randomize:
        cs = random.randrange(1 << long(14))
        clock_seq_low = cs & long(0xff)
        clock_seq_hi_variant = (cs >> long(8)) & long(0x3f)
        node = uuid.getnode()
    else:
        if lowest_val: # uuid with lowest possible clock value
            clock_seq_low = 0 & long(0xff)
            clock_seq_hi_variant = 0 & long(0x3f)
            node = 0 & long(0xffffffffffff) # 48 bits
        else: # UUID with highest possible clock value
            clock_seq_low = long(0xff)
            clock_seq_hi_variant = long(0x3f)
            node = long(0xffffffffffff) # 48 bits
    return uuid.UUID(
        fields=(time_low, time_mid, time_hi_version,
                clock_seq_hi_variant, clock_seq_low, node),
        version=1
    )
项目:vxTrader    作者:vex1023    | 项目源码 | 文件源码
def __init__(self, account, password):

        # ?????
        super(yjbLoginSession, self).__init__(account=account, password=password)

        # ???????
        self.mac_address = ("".join(c + "-" if i % 2 else c for i, c in \
                                    enumerate(hex(uuid.getnode())[2:].zfill(12)))[:-1]).upper()

        # TODO disk_serial_id and cpuid machinecode ???????
        self.disk_serial_id = "ST3250890AS"
        self.cpuid = "-41315-FA76111D"
        self.machinecode = "-41315-FA76111D"

        # ?????
        self.code_rule = re.compile("^[0-9]{4}$")

        if datetime.now() > datetime(year=2016, month=11, day=30, hour=0):
            # raise TraderAPIError('?????????2016?11?30???')
            logger.warning('?????????2016?11?30???')
        else:
            logger.warning('?????????2016?11?30???')
项目:vxTrader    作者:vex1023    | 项目源码 | 文件源码
def __init__(self, account, password):

        # ?????
        super(gfLoginSession, self).__init__(account=account, password=password)

        # TODO ??????????
        self.disknum = "S2ZWJ9AF517295"
        self.mac_address = ("".join(c + "-" if i % 2 else c for i, c in \
                                    enumerate(hex(uuid.getnode())[2:].zfill(12)))[:-1]).upper()
        # ?????????
        self.code_rule = re.compile("^[A-Za-z0-9]{5}$")

        # ????sessionId
        self._dse_sessionId = None

        # ??????
        self.margin_flags = False
项目:orange3-imageanalytics    作者:biolab    | 项目源码 | 文件源码
def __init__(self, model="inception-v3", layer="penultimate",
                 server_url='api.garaza.io:443'):
        super().__init__(server_url)
        model_settings = self._get_model_settings_confidently(model, layer)
        self._model = model
        self._layer = layer
        self._target_image_size = model_settings['target_image_size']

        cache_file_path = self._cache_file_blueprint.format(model, layer)
        self._cache_file_path = join(cache_dir(), cache_file_path)
        self._cache_dict = self._init_cache()

        self._session = cachecontrol.CacheControl(
            requests.session(),
            cache=cachecontrol.caches.FileCache(
                join(cache_dir(), __name__ + ".ImageEmbedder.httpcache"))
        )

        # attribute that offers support for cancelling the embedding
        # if ran in another thread
        self.cancelled = False
        self.machine_id = \
            QSettings().value('error-reporting/machine-id', '', type=str)  \
            or str(uuid.getnode())
        self.session_id = None
项目:decoding_challenge_cortana_2016_3rd    作者:kingjr    | 项目源码 | 文件源码
def get_machid():
    """Get (mostly) unique machine ID

    Returns
    -------
    ids : array (length 2, int32)
        The machine identifier used in MNE.
    """
    mac = b('%012x' % uuid.getnode())  # byte conversion for Py3
    mac = re.findall(b'..', mac)  # split string
    mac += [b'00', b'00']  # add two more fields

    # Convert to integer in reverse-order (for some reason)
    from codecs import encode
    mac = b''.join([encode(h, 'hex_codec') for h in mac[::-1]])
    ids = np.flipud(np.fromstring(mac, np.int32, count=2))
    return ids
项目:pyrecord    作者:Aakashdeveloper    | 项目源码 | 文件源码
def tuling(self, info, apiKey = None):
        tuling_server = "http://www.tuling123.com/openapi/api"

        assert isinstance(info, str), "Info must be a string"
        assert apiKey is None or isinstance(apiKey, str), "`apiKey` must be `None` or a string"
        #using Rain's defaul tuline's keys
        if apiKey is None: apiKey = "fd2a2710a7e01001f97dc3a663603fa1"

        mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:]

        url = tuling_server + "?key=" +apiKey + "&info=" + info

        re = urlopen(url).read()
        re_dict = json.loads(re)
        answer = re_dict['text']

        return answer

    # nuance header
项目:jabbapylib3    作者:jabbalaci    | 项目源码 | 文件源码
def get_fingerprint(md5=False):
    """
    Fingerprint of the current operating system/platform.

    If md5 is True, a digital fingerprint is returned.
    """
    sb = []
    sb.append(p.node())
    sb.append(p.architecture()[0])
    sb.append(p.architecture()[1])
    sb.append(p.machine())
    sb.append(p.processor())
    sb.append(p.system())
    sb.append(str(uuid.getnode()))    # MAC address
    text = '#'.join(sb)
    if md5:
        return string_to_md5(text)
    else:
        return text
项目:kiota    作者:Morteo    | 项目源码 | 文件源码
def unique_id():
  import uuid
  return uuid.getnode()
项目:facerecognition    作者:guoxiaolu    | 项目源码 | 文件源码
def get_mac_address():
    import uuid
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:]
    return mac
项目:deb-python-cassandra-driver    作者:openstack    | 项目源码 | 文件源码
def test_times_from_uuid1(self):
        node = uuid.getnode()
        now = time.time()
        u = uuid.uuid1(node, 0)

        t = util.unix_time_from_uuid1(u)
        self.assertAlmostEqual(now, t, 2)

        dt = util.datetime_from_uuid1(u)
        t = calendar.timegm(dt.timetuple()) + dt.microsecond / 1e6
        self.assertAlmostEqual(now, t, 2)
项目:geekcloud    作者:Mr-Linus    | 项目源码 | 文件源码
def is_latest():
    node = uuid.getnode()
    jsn = uuid.UUID(int=node).hex[-12:]
    with open(os.path.join(BASE_DIR, 'version')) as f:
        current_version = f.read()
    lastest_version = urllib.urlopen('http://www.jumpserver.org/lastest_version.html?jsn=%s' % jsn).read().strip()

    if current_version != lastest_version:
        pass
项目:geekcloud    作者:Mr-Linus    | 项目源码 | 文件源码
def get_mac_address():
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:]
    return mac
项目:linchpin    作者:CentOS-PaaS-SIG    | 项目源码 | 文件源码
def setup_rundb(self):
        """
        Configures the run database parameters, sets them into extra_vars
        """

        rundb_conn_default = '~/.config/linchpin/rundb-::mac::.json'
        rundb_conn = self.get_cfg(section='lp',
                                  key='rundb_conn',
                                  default=rundb_conn_default)
        rundb_type = self.get_cfg(section='lp',
                                  key='rundb_type',
                                  default='TinyRunDB')
        rundb_conn_type = self.get_cfg(section='lp',
                                       key='rundb_conn_type',
                                       default='file')
        self.rundb_hash = self.get_cfg(section='lp',
                                       key='rundb_hash',
                                       default='sha256')

        if rundb_conn_type == 'file':
            rundb_conn_int = rundb_conn.replace('::mac::', str(get_mac()))
            rundb_conn_int = os.path.expanduser(rundb_conn_int)
            rundb_conn_dir = os.path.dirname(rundb_conn_int)

            if not os.path.exists(rundb_conn_dir):
                os.mkdir(rundb_conn_dir)


        self.set_evar('rundb_type', rundb_type)
        self.set_evar('rundb_conn', rundb_conn_int)
        self.set_evar('rundb_hash', self.rundb_hash)


        return BaseDB(DB_DRIVERS[rundb_type], rundb_conn_int)
项目:dingdang-robot    作者:wzpan    | 项目源码 | 文件源码
def get_speech(self, phrase):
        if self.token == '':
            self.token = self.get_token()
        query = {'tex': phrase,
                 'lan': 'zh',
                 'tok': self.token,
                 'ctp': 1,
                 'cuid': str(get_mac())[:32],
                 'per': self.per
                 }
        r = requests.post('http://tsn.baidu.com/text2audio',
                          data=query,
                          headers={'content-type': 'application/json'})
        try:
            r.raise_for_status()
            if r.json()['err_msg'] is not None:
                self._logger.critical('Baidu TTS failed with response: %r',
                                      r.json()['err_msg'],
                                      exc_info=True)
                return None
        except Exception:
            pass
        with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
            f.write(r.content)
            tmpfile = f.name
            return tmpfile
项目:voicetools    作者:namco1992    | 项目源码 | 文件源码
def get_mac_address():
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e+2] for e in range(0, 11, 2)])
项目:NortheasternCTF2016    作者:wilkening-mark    | 项目源码 | 文件源码
def __init__(self, logger, device_key):
        self.logger = logger
        self.conn = None
        self.device_id = str(get_mac())
        self.device_key = device_key

# Connect to the server
项目:geekcloud    作者:GeekCloud-Team    | 项目源码 | 文件源码
def is_latest():
    node = uuid.getnode()
    jsn = uuid.UUID(int=node).hex[-12:]
    with open(os.path.join(BASE_DIR, 'version')) as f:
        current_version = f.read()
    lastest_version = urllib.urlopen('http://www.jumpserver.org/lastest_version.html?jsn=%s' % jsn).read().strip()

    if current_version != lastest_version:
        pass
项目:geekcloud    作者:GeekCloud-Team    | 项目源码 | 文件源码
def get_mac_address():
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:]
    return mac
项目:onkyo_serial    作者:blaedd    | 项目源码 | 文件源码
def _getMac():
        """Get our machines mac address and format it for the packet."""
        return '{:0>12X}'.format(uuid.getnode())
项目:python-script    作者:austin98x    | 项目源码 | 文件源码
def getmac(self):
        import uuid
        node = uuid.getnode()
        mac = uuid.UUID(int = node).hex[-12:]
        return mac
项目:OctoPrint-PolarCloud    作者:markwal    | 项目源码 | 文件源码
def get_mac():
    return ':'.join(('%012X' % uuid.getnode())[i:i+2] for i in range(0, 12, 2))

# what's the likely ip address for the local UI?
项目:chat    作者:Decalogue    | 项目源码 | 文件源码
def __init__(self, audioplayer=None, tempdir="."):
        if audioplayer:
            self.audioplayer = audioplayer
        else:
            self.audioplayer = mixer
        self.audioplayer.init()
        self.app_key = "QrhsINLcc3Io6w048Ia8kcjS"
        self.secret_key = "e414b3ccb7d51fef12f297ffea9ec41d"
        self.url_tok_base = "https://openapi.baidu.com/oauth/2.0/token"
        self.url_get_base = "http://tsn.baidu.com/text2audio"
        self.url_post_base = "http://tsn.baidu.com/text2audio"
        self.access_token = self.get_token()
        self.mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:]
        self.language = 'zh'
        self.tempdir = tempdir if os.path.isdir(tempdir) else "."
项目:chat    作者:Decalogue    | 项目源码 | 文件源码
def get_mac_address():
    """Get mac address.
    """
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e+2] for e in range(0, 11, 2)])
项目:morango    作者:learningequality    | 项目源码 | 文件源码
def get_or_create_current_instance(cls):
        """Get the instance model corresponding to the current system, or create a new
        one if the system is new or its properties have changed (e.g. OS from upgrade)."""

        # on Android, platform.platform() barfs, so we handle that safely here
        try:
            plat = platform.platform()
        except:
            plat = "Unknown (Android?)"

        kwargs = {
            "platform": plat,
            "hostname": platform.node(),
            "sysversion": sys.version,
            "database": DatabaseIDModel.get_or_create_current_database_id(),
            "db_path": os.path.abspath(settings.DATABASES['default']['NAME']),
            "system_id": os.environ.get("MORANGO_SYSTEM_ID", ""),
        }

        # try to get the MAC address, but exclude it if it was a fake (random) address
        mac = uuid.getnode()
        if (mac >> 40) % 2 == 0:  # 8th bit (of 48 bits, from left) is 1 if MAC is fake
            hashable_identifier = "{}:{}".format(kwargs['database'].id, mac)
            kwargs["node_id"] = hashlib.sha1(hashable_identifier.encode('utf-8')).hexdigest()[:20]
        else:
            kwargs["node_id"] = ""

        # do within transaction so we only ever have 1 current instance ID
        with transaction.atomic():
            InstanceIDModel.objects.filter(current=True).update(current=False)
            obj, created = InstanceIDModel.objects.get_or_create(**kwargs)
            obj.current = True
            obj.save()

        return obj, created
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_getnode(self):
        import sys
        node1 = uuid.getnode()
        self.check_node(node1, "getnode1")

        # Test it again to ensure consistency.
        node2 = uuid.getnode()
        self.check_node(node2, "getnode2")

        self.assertEqual(node1, node2)
项目:Python-Penetration-Testing-for-Developers    作者:PacktPublishing    | 项目源码 | 文件源码
def get_localhost_details(interfaces_eth, interfaces_wlan):
    hostdata = "None"
    hostname = "None"
    windows_ip = "None"
    eth_ip = "None"
    wlan_ip = "None"
    host_fqdn = "None"
    eth_mac = "None"
    wlan_mac = "None"
    windows_mac = "None"
    hostname = socket.gethostbyname(socket.gethostname())
    if hostname.startswith("127.") and os.name != "nt":
        hostdata = socket.gethostbyaddr(socket.gethostname())
        hostname = str(hostdata[1]).strip('[]')
        host_fqdn = socket.getfqdn()
        for interface in interfaces_eth:
            try:
                eth_ip = get_ip(interface)
                if not "None" in eth_ip:
                    eth_mac = get_mac_address(interface)
                break
            except IOError:
                pass
        for interface in interfaces_wlan:
            try:
                wlan_ip = get_ip(interface)
                if not "None" in wlan_ip:
                    wlan_mac = get_mac_address(interface)
                break
            except IOError:
                pass
    else:
        windows_ip = socket.gethostbyname(socket.gethostname())
        windows_mac = uuid.getnode()
        windows_mac = ':'.join(("%012X" % windows_mac)[i:i+2] for i in range(0, 12, 2))
        hostdata = socket.gethostbyaddr(socket.gethostname())
        hostname = str(socket.gethostname())
        host_fqdn = socket.getfqdn()
    return hostdata, hostname, windows_ip, eth_ip, wlan_ip, host_fqdn, eth_mac, wlan_mac, windows_mac
项目:CIDDS    作者:markusring    | 项目源码 | 文件源码
def init(browsing, mailing, printing, copyfiles, copysea, ssh, meeting, offline, private, breaks, attacking, t):
    activities = createActivityList(browsing, mailing, printing, copyfiles, copysea, ssh, meeting, offline, private, breaks, attacking)

    time.sleep(2)

    parser = SafeConfigParser()
    parser.read("packages/system/config.ini")

    subnet, host, hostname = getSubnetHostAndHostname()
    global myID

    if platform.system() == "Linux":
        myID = str(getnode())
    else:
        # For Windows, something must be trickled, since getnode () returns an incorrect value
        hexMac = check_output(["getmac"])[162:180]
        hexMacNoDash = hexMac.replace("-", "")
        intMac = int(hexMacNoDash, 16)
        myID = str(intMac)

    global pathForLog
    if platform.system() == "Linux":
        pathForLog = "/home/debian/log/"
    else:
        pathForLog = "M:\\"

    # In endless loop perform different activities
    try:    
        while True:

            if isWorkday(parser) and isWorkingHours(parser):
                    doSomething(activities)

            else:
                # Should be just the end of his work, he must wait until he has to work again
                time.sleep(random.randint(1, 15)*60 - random.randint(1, 55))

    except KeyboardInterrupt:
        echoC(__name__, "SCRIPT STOPPED: KEYBOARDINTERRUPT")    
        sys.exit(0)
项目:CIDDS    作者:markusring    | 项目源码 | 文件源码
def copyRandomFile(fileNames, destination):

    # Select a random file 
    fileNameWithPath = fileNames[randint(0, len(fileNames)-1)]

    if platform.system() == "Linux":
        separator = "/"
    elif platform.system() == "Windows":
        separator = "\\"

    # If the file is copied to the VM, the MAC address (as an integer) is placed before the file names
    # -> Avoid deadlocks when copying to the server
    if "localstorage" in destination:
        localFileName = str(getnode()) + "-" + fileNameWithPath.split(separator)[-1]
    else:
        localFileName = fileNameWithPath.split(separator)[-1]

    # Path to the corresponding drive and filename
    dstWithFileName = destination + localFileName

    # Copy file 
    try:
        copyfile(fileNameWithPath, dstWithFileName)
        echoC(__name__, "Copied file " + localFileName + " to " + destination)
    except Exception as e:
        echoC(__name__, "copyfile() with destination " + destination + " error: " + str(e))
        return -1

    # copyfile() is not blocking 
    time.sleep(random.randint(15, 300))
    return 0

# Select a file and copy it to the VM or the file server
项目:CIDDS    作者:markusring    | 项目源码 | 文件源码
def copyRandomFile(fileNames, destination):

    # Pick a random file 
    fileNameWithPath = fileNames[randint(0, len(fileNames)-1)]

    if platform.system() == "Linux":
        separator = "/"
    elif platform.system() == "Windows":
        separator = "\\"

    # If the file is copied to the VM, the MAC address (as an integer) is placed before the file names
    # -> Avoid deadlocks when copying to the server
    if "localstorage" in destination:
        localFileName = str(getnode()) + "-" + fileNameWithPath.split(separator)[-1]
    else:
        localFileName = fileNameWithPath.split(separator)[-1]

    # Path to the appropriate drive and filename
    dstWithFileName = destination + localFileName

    # Copy file 
    try:
        copyfile(fileNameWithPath, dstWithFileName)
        echoC(__name__, "Copied file " + localFileName + " to " + destination)
    except Exception as e:
        echoC(__name__, "copyfile() with destination " + destination + " error: " + str(e))
        return -1

    # copyfile() is not blocking 
    time.sleep(random.randint(15,120))
    return 0
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_getnode(self):
        node1 = uuid.getnode()
        self.assertTrue(0 < node1 < (1 << 48), '%012x' % node1)

        # Test it again to ensure consistency.
        node2 = uuid.getnode()
        self.assertEqual(node1, node2, '%012x != %012x' % (node1, node2))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_getnode(self):
        node1 = uuid.getnode()
        self.assertTrue(0 < node1 < (1 << 48), '%012x' % node1)

        # Test it again to ensure consistency.
        node2 = uuid.getnode()
        self.assertEqual(node1, node2, '%012x != %012x' % (node1, node2))
项目:CeNet-Interconnect    作者:shikharsrivastava    | 项目源码 | 文件源码
def getmac():
    mac = get_mac()
    mac = ':'.join(("%012X" % mac)[i:i+2] for i in range(0, 12, 2))
    return mac
项目:ahenk    作者:Pardus-LiderAhenk    | 项目源码 | 文件源码
def mac_addresses():
                mac = get_mac()
                ':'.join(("%012X" % mac)[i:i + 2] for i in range(0, 12, 2))
                arr = []
                for iface in psutil.net_io_counters(pernic=True):
                    try:
                        addr_list = psutil.net_if_addrs()
                        mac = addr_list[str(iface)][2][1]
                        if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()) and str(
                                mac) != '00:00:00:00:00:00':
                            arr.append(mac.lower())
                    except Exception as e:
                        pass

                return arr
项目:ahenk    作者:Pardus-LiderAhenk    | 项目源码 | 文件源码
def generate_uuid(self, depend_mac=True):
        if depend_mac is False:
            self.logger.debug('uuid creating randomly')
            return uuid.uuid4()  # make a random UUID
        else:
            self.logger.debug('uuid creating according to mac address')
            return uuid.uuid3(uuid.NAMESPACE_DNS,
                              str(get_mac()))  # make a UUID using an MD5 hash of a namespace UUID and a mac address
项目:PySide_For_Amazon_Order    作者:cundi    | 项目源码 | 文件源码
def login(self):
        flag = True
        if self.loginUrl is not None:
            try:
                mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
                self.params.append(
                    ('KEY', self.md5(self.softKey.upper() + self.user.upper()) + mac))
                self.opener.addheaders = self.params
                url = "http://" + self.loginUrl
                url += "/Upload/Login.aspx?U=%s&p=%s" % (
                    self.user, self.md5(self.pwd))
                try:
                    response = self.opener.open(url, None, 60)
                    if response.code == 200:
                        body = response.read()
                        if body is not None:
                            if body.find("-") > 0:
                                us = body.split("_")
                                self.uid = us[0]
                                self.uKey = body.strip()
                                print '???????ID??', self.uid
                                flag = True
                            else:
                                print '????,??????', body
                                flag = False
                except Exception, e:
                    print "Error:Login Request"
                    print e
            except Exception, e:
                print "Error:Login Params "
                print e
        return flag
项目:gpvdm    作者:roderickmackenzie    | 项目源码 | 文件源码
def send_init(self):
        cpus=multiprocessing.cpu_count()
        mac=':'.join('%02X' % ((get_mac() >> 8*i) & 0xff) for i in reversed(xrange(6)))
        self.socket.sendto("init#"+str(cpus)+"#"+mac, (self.server_ip, self.tx_port))
项目:server    作者:sgr-smile2015    | 项目源码 | 文件源码
def is_latest():
    node = uuid.getnode()
    jsn = uuid.UUID(int=node).hex[-12:]
    with open(os.path.join(BASE_DIR, 'version')) as f:
        current_version = f.read()
    lastest_version = urllib.urlopen('http://www.jumpserver.org/lastest_version.html?jsn=%s' % jsn).read().strip()

    if current_version != lastest_version:
        pass
项目:server    作者:sgr-smile2015    | 项目源码 | 文件源码
def get_mac_address():
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:]
    return mac
项目:easytrader_py2.7    作者:easyquant    | 项目源码 | 文件源码
def get_mac():
    # ??mac?? link: http://stackoverflow.com/questions/28927958/python-get-mac-address
    return ("".join(c + "-" if i % 2 else c for i, c in enumerate(hex(
            uuid.getnode())[2:].zfill(12)))[:-1]).upper()
项目:mppt_config    作者:dilithiumpower    | 项目源码 | 文件源码
def Connect(self):
    self.socket_mode = UDP_MODE
    self.mac = uuid.getnode()

    # Set up UDP receiver.
    self.udp_rx_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.udp_rx_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Pack multicast group structure correctly.
    mreq = struct.pack('=4sl', socket.inet_aton(MCAST_GRP),socket.INADDR_ANY) 

    # Request access to multicast group.
    self.udp_rx_sock.setsockopt(socket.IPPROTO_IP,
                                socket.IP_ADD_MEMBERSHIP, mreq)  

    # Bind to all intfs.
    self.udp_rx_sock.bind(('', MCAST_PORT))
    self.udp_rx_sock.settimeout(TIMEOUT)

    # Set up UDP transmitter.
    self.udp_tx_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.udp_tx_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)

    # Get the MAC address of the local adapter.
    msg = bytearray(8)
    struct.pack_into('<Q', msg, 0, int(self.mac))
    self.local_mac = ''.join('{:02x}'.format(x) for x in msg[0:6])
    logging.debug('MAC Addr: %s', self.local_mac)
项目:Cayenne-Agent    作者:myDevicesIoT    | 项目源码 | 文件源码
def getMac(self, format=2):
        if format < 2:
            format = 2
        if format > 4:
            format = 4
        mac_num = hex(getnode()).replace('0x', '').upper()
        mac = '-'.join(mac_num[i : i + format] for i in range(0, 11, format))
        #debug("Mac:" + mac)
        return mac
项目:hardware-lab    作者:Buzzvil    | 项目源码 | 文件源码
def get_machine_id():
    machine_id = get_rpi_serial()
    if machine_id:
        return machine_id

    return str(uuid.getnode())
项目:Supplicant    作者:mayuko2012    | 项目源码 | 文件源码
def get_mac_address(): 
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:] 
    return ":".join([mac[e:e+2] for e in range(0,11,2)])
项目:Supplicant    作者:mayuko2012    | 项目源码 | 文件源码
def get_mac_address(): 
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:] 
    return ":".join([mac[e:e+2] for e in range(0,11,2)])
项目:JBOPS    作者:blacktwin    | 项目源码 | 文件源码
def fetch(path, t='GET'):
    url = 'http{}://{}:{}/'.format(PLEX_SSL, PLEX_HOST, PLEX_PORT)

    headers = {'X-Plex-Token': PLEX_TOKEN,
               'Accept': 'application/json',
               'X-Plex-Provides': 'controller',
               'X-Plex-Platform': platform.uname()[0],
               'X-Plex-Platform-Version': platform.uname()[2],
               'X-Plex-Product': 'Plexpy script',
               'X-Plex-Version': '0.9.5',
               'X-Plex-Device': platform.platform(),
               'X-Plex-Client-Identifier': str(hex(getnode()))
               }

    try:
        if t == 'GET':
            r = requests.get(url + path, headers=headers, verify=False)
        elif t == 'POST':
            r = requests.post(url + path, headers=headers, verify=False)
        elif t == 'DELETE':
            r = requests.delete(url + path, headers=headers, verify=False)

        if r and len(r.content):  # incase it dont return anything
            return r.json()
        else:
            return r.content

    except Exception as e:
        print e