コード例 #1
0
def load_login(_auth, _master):
    try:
        locale = 'en_US'
        android_id = gm_api_mob.FROM_MAC_ADDRESS
        is_mac = android_id is gm_api_mob.FROM_MAC_ADDRESS
        if is_mac:
            mac_int = getmac()
            if (mac_int >> 40) % 2:
                raise OSError("a valid MAC could not be determined."
                              " Provide an android_id (and be"
                              " sure to provide the same one on future runs).")

            device_id = utils.create_mac_string(mac_int)
            device_id = device_id.replace(':', '')
        else:
            device_id = android_id

        gm_api_mob.session._master_token = _master
        gm_api_mob.session._authtoken = _auth
        gm_api_mob.session.is_authenticated = True

        gm_api_mob.android_id = gm_api_mob._validate_device_id(device_id,
                                                               is_mac=is_mac)
        gm_api_mob.logger.info("authenticated")

        gm_api_mob.locale = locale

        if gm_api_mob.is_subscribed:
            gm_api_mob.logger.info("subscribed")

        return True
    except:
        traceback.print_exc(file=sys.stdout)
        return False
コード例 #2
0
    def __init__(self):

        #Mac and hostname are used to identify our client.
        self.mac = hex(getmac())[2:-1]
        self.mac = ':'.join([self.mac[x:x + 2] for x in range(0, 10, 2)])

        hostname = gethostname()

        #Pre-filled protobuff instances.
        #These are used to fill in new instances.
        #Named scheme is '[protocol name]_filled'

        self.upload_auth_filled = metadata_pb2.UploadAuth()
        self.upload_auth_filled.address = self.mac
        self.upload_auth_filled.hostname = hostname

        self.client_state_filled = metadata_pb2.ClientState()
        self.client_state_filled.address = self.mac

        self.upload_auth_response_filled = metadata_pb2.UploadAuthResponse()

        self.client_state_response_filled = metadata_pb2.ClientStateResponse()

        self.metadata_request_filled = metadata_pb2.MetadataRequest()
        self.metadata_request_filled.address = self.mac

        self.metadata_response_filled = metadata_pb2.MetadataResponse()

        #Service name mapped to url.
        self.pb_services = {
            "upload_auth": 'upauth',
            "client_state": 'clientstate',
            "metadata": 'metadata?version=1'
        }
コード例 #3
0
    def __init__(self):

        #Mac and hostname are used to identify our client.
        self.mac = hex(getmac())[2:-1]
        self.mac = ':'.join([self.mac[x:x+2] for x in range(0, 10, 2)])

        hostname = gethostname()

        #Pre-filled protobuff instances.
        #These are used to fill in new instances.
        #Named scheme is '[protocol name]_filled'

        self.upload_auth_filled = metadata_pb2.UploadAuth()
        self.upload_auth_filled.address = self.mac
        self.upload_auth_filled.hostname = hostname

        self.client_state_filled = metadata_pb2.ClientState()
        self.client_state_filled.address = self.mac

        self.upload_auth_response_filled = metadata_pb2.UploadAuthResponse()

        self.client_state_response_filled = metadata_pb2.ClientStateResponse()

        self.metadata_request_filled = metadata_pb2.MetadataRequest()
        self.metadata_request_filled.address = self.mac

        self.metadata_response_filled = metadata_pb2.MetadataResponse()
        
        #Service name mapped to url.
        self.pb_services = {
            "upload_auth" : 'upauth',
            "client_state": 'clientstate',
            "metadata": 'metadata?version=1'}
コード例 #4
0
ファイル: google.py プロジェクト: vefve/WhatsApp-GD-Extractor
def _get_android_id():
    mac_int = getmac()
    if (mac_int >> 40) % 2:
        raise OSError("a valid MAC could not be determined."
                      " Provide an android_id (and be"
                      " sure to provide the same one on future runs).")

    android_id = _create_mac_string(mac_int)
    android_id = android_id.replace(':', '')
    return android_id
コード例 #5
0
def pwaAutoIdentity():
    authbase = pwaScriptID() + "\\"
    try:
        authbase += os.environ['USERDOMAIN'] + "\\"
    except:
        pass
    authbase += socket.gethostname() + "\\"
    authbase += socket.gethostbyname(socket.gethostname()) + "\\"
    #authbase += getpass.getuser()+"\\"
    authbase += str(getmac())
    return authbase
コード例 #6
0
    def __get_mac_address():
        """
        DOCSTRING: this function will return the mac address asa a string
        """
        mac_number = hex(getmac())[2:]

        mac_address = ''
        for index in range(int(len(mac_number) / 2)):
            mac_address += mac_number[index * 2:index * 2 + 2] + ':'

        mac_address = mac_address[:-1]

        return mac_address
コード例 #7
0
ファイル: musicmanager.py プロジェクト: ayuryshev/gmusicapi
    def _perform_upauth(self, uploader_id, uploader_name):
        """Auth or register ourselves as an upload client.

        Return True on success; see :py:func:`login` for params.
        """

        if uploader_id is None:
            mac_int = getmac()
            if (mac_int >> 40) % 2:
                self.session.logout()
                raise OSError('a valid MAC could not be determined.'
                              ' Provide uploader_id (and be'
                              ' sure to provide the same one on future runs).')

            else:
                # distinguish us from a Music Manager on this machine
                mac_int = (mac_int + 1) % (1 << 48)

            uploader_id = utils.create_mac_string(mac_int)

        if not utils.is_valid_mac(uploader_id):
            self.session.logout()
            raise ValueError('uploader_id is not in a valid form.'
                             '\nProvide 6 pairs of hex digits'
                             ' with capital letters',
                             ' (eg "00:11:22:33:AA:BB")')

        if uploader_name is None:
            uploader_name = gethostname() + u" (gmusicapi-%s)" % gmusicapi.__version__

        try:
            # this is a MM-specific step that might register a new device.
            self._make_call(musicmanager.AuthenticateUploader,
                            uploader_id,
                            uploader_name)
            self.logger.info("successful upauth")
            self.uploader_id = uploader_id
            self.uploader_name = uploader_name

        except CallFailure:
            self.logger.exception("upauth failure")
            self.session.logout()
            return False

        return True
コード例 #8
0
ファイル: musicmanager.py プロジェクト: zachreizner/gmusicapi
    def _perform_upauth(self, uploader_id, uploader_name):
        """Auth or register ourselves as an upload client.

        Return True on success; see :py:func:`login` for params.
        """

        if uploader_id is None:
            mac_int = getmac()
            if (mac_int >> 40) % 2:
                self.session.logout()
                raise OSError('a valid MAC could not be determined.'
                              ' Provide uploader_id (and be'
                              ' sure to provide the same one on future runs).')

            else:
                # distinguish us from a Music Manager on this machine
                mac_int = (mac_int + 1) % (1 << 48)

            uploader_id = utils.create_mac_string(mac_int)

        if not utils.is_valid_mac(uploader_id):
            self.session.logout()
            raise ValueError(
                'uploader_id is not in a valid form.'
                '\nProvide 6 pairs of hex digits'
                ' with capital letters', ' (eg "00:11:22:33:AA:BB")')

        if uploader_name is None:
            uploader_name = gethostname(
            ) + u" (gmusicapi-%s)" % gmusicapi.__version__

        try:
            # this is a MM-specific step that might register a new device.
            self._make_call(musicmanager.AuthenticateUploader, uploader_id,
                            uploader_name)
            self.logger.info("successful upauth")
            self.uploader_id = uploader_id
            self.uploader_name = uploader_name

        except CallFailure:
            self.logger.exception("upauth failure")
            self.session.logout()
            return False

        return True
コード例 #9
0
ファイル: gmusic.py プロジェクト: Kronos3/SimpleMusicManager
def load_login(_auth, _master):
    try:
        gm_api_mob.session.is_authenticated = True
        gm_api_mob.session._authtoken = _auth
        gm_api_mob.session._master_token = _master
        mac_int = getmac()
        if (mac_int >> 40) % 2:
            raise OSError("a valid MAC could not be determined."
                          " Provide an android_id (and be"
                          " sure to provide the same one on future runs).")

        android_id = utils.create_mac_string(mac_int)
        android_id = android_id.replace(':', '')
        gm_api_mob.android_id = android_id
    except:
        traceback.print_exc(file=sys.stdout)
        return False
    return True
コード例 #10
0
ファイル: mobileclient.py プロジェクト: kbettadapur/gmusicapi
    def login(self, email, password, android_id):
        """Authenticates the Mobileclient.
        Returns ``True`` on success, ``False`` on failure.

        :param email: eg ``'*****@*****.**'`` or just ``'test'``.
        :param password: the account's password.
          This is not stored locally, and is sent securely over SSL.
          App-specific passwords are not supported.
        :param android_id: 16 hex digits, eg ``'1234567890abcdef'``.

          Pass Mobileclient.FROM_MAC_ADDRESS instead to attempt to use
          this machine's MAC address as an android id.
          **Use this at your own risk**:
          the id will be a non-standard 12 characters,
          but appears to work fine in testing.
          If a valid MAC address cannot be determined on this machine
          (which is often the case when running on a VPS), raise OSError.

        #TODO 2fa
        """

        if android_id is None:
            raise ValueError("android_id cannot be None.")

        if android_id is self.FROM_MAC_ADDRESS:
            mac_int = getmac()
            if (mac_int >> 40) % 2:
                raise OSError("a valid MAC could not be determined."
                              " Provide an android_id (and be"
                              " sure to provide the same one on future runs).")

            android_id = utils.create_mac_string(mac_int)
            android_id = android_id.replace(':', '')

        if not self.session.login(email, password, android_id):
            self.logger.info("failed to authenticate")
            return False

        self.android_id = android_id
        self.logger.info("authenticated")

        return True
コード例 #11
0
ファイル: mobileclient.py プロジェクト: zigdon/gmusicapi
    def login(self, email, password, android_id):
        """Authenticates the Mobileclient.
        Returns ``True`` on success, ``False`` on failure.

        :param email: eg ``'*****@*****.**'`` or just ``'test'``.
        :param password: the account's password.
          This is not stored locally, and is sent securely over SSL.
          App-specific passwords are not supported.
        :param android_id: 16 hex digits, eg ``'1234567890abcdef'``.

          Pass Mobileclient.FROM_MAC_ADDRESS instead to attempt to use
          this machine's MAC address as an android id.
          **Use this at your own risk**:
          the id will be a non-standard 12 characters,
          but appears to work fine in testing.
          If a valid MAC address cannot be determined on this machine
          (which is often the case when running on a VPS), raise OSError.

        #TODO 2fa
        """

        if android_id is None:
            raise ValueError("android_id cannot be None.")

        if android_id is self.FROM_MAC_ADDRESS:
            mac_int = getmac()
            if (mac_int >> 40) % 2:
                raise OSError("a valid MAC could not be determined."
                              " Provide an android_id (and be"
                              " sure to provide the same one on future runs).")

            android_id = utils.create_mac_string(mac_int)
            android_id = android_id.replace(':', '')

        if not self.session.login(email, password, android_id):
            self.logger.info("failed to authenticate")
            return False

        self.android_id = android_id
        self.logger.info("authenticated")

        return True
コード例 #12
0
ファイル: __init__.py プロジェクト: 2fast4you78/smarthome
    def push(self, key):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((self._host, int(self._port)))
            logger.debug("Connected to {0}:{1}".format(self._host, self._port))
        except Exception:
            logger.warning("Could not connect to %s:%s, to send key: %s." %
                           (self._host, self._port, key))
            return

        src = s.getsockname()[0]            # ip of remote
        mac = self._int_to_str(getmac())    # mac of remote
        remote = 'sh.py remote'             # remote name
        dst = self._host                    # ip of tv
        app = b'python'                      # iphone..iapp.samsung
        tv = b'UE32ES6300'                   # iphone.UE32ES6300.iapp.samsung

        logger.debug("src = {0}, mac = {1}, remote = {2}, dst = {3}, app = {4}, tv = {5}".format(
            src, mac, remote, dst, app, tv))

        src = base64.b64encode(src.encode())
        mac = base64.b64encode(mac.encode())
        cmd = base64.b64encode(key.encode())
        rem = base64.b64encode(remote.encode())

        msg = bytearray([0x64, 0])
        msg.extend([len(src), 0])
        msg.extend(src)
        msg.extend([len(mac), 0])
        msg.extend(mac)
        msg.extend([len(rem), 0])
        msg.extend(rem)

        pkt = bytearray([0])
        pkt.extend([len(app), 0])
        pkt.extend(app)
        pkt.extend([len(msg), 0])
        pkt.extend(msg)

        try:
            s.send(pkt)
        except:
            try:
                s.close()
            except:
                pass
            return

        msg = bytearray([0, 0, 0])
        msg.extend([len(cmd), 0])
        msg.extend(cmd)

        pkt = bytearray([0])
        pkt.extend([len(tv), 0])
        pkt.extend(tv)
        pkt.extend([len(msg), 0])
        pkt.extend(msg)

        try:
            s.send(pkt)
        except:
            return
        finally:
            try:
                s.close()
            except:
                pass
        logger.debug("Send {0} to Smart TV".format(key))
        time.sleep(0.1)
コード例 #13
0
    def login(self, oauth_credentials=OAUTH_FILEPATH,
              uploader_id=None, uploader_name=None):
        """Authenticates the Music Manager using OAuth.
        Returns ``True`` on success, ``False`` on failure.

        Unlike the :class:`Webclient`, OAuth allows authentication without
        providing plaintext credentials to the application.

        In most cases, the default parameters should be acceptable. Users on
        virtual machines will want to provide `uploader_id`.

        :param oauth_credentials: ``oauth2client.client.OAuth2Credentials`` or the path to a
          ``oauth2client.file.Storage`` file. By default, the same default path used by
          :func:`perform_oauth` is used.

          Endusers will likely call :func:`perform_oauth` once to write
          credentials to disk and then ignore this parameter.

          This param
          is mostly intended to allow flexibility for developers of a
          3rd party service who intend to perform their own OAuth flow
          (eg on their website).

        :param uploader_id: a unique id as a MAC address, eg ``'01:23:45:67:89:AB'``.
          This should only be provided in cases where the default
          (host MAC address incremented by 1) will not work.

          Upload behavior is undefined if a Music Manager uses the same id, especially when
          reporting bad matches.

          ``OSError`` will be raised if this is not provided and a stable MAC could not be
          determined (eg when running on a VPS).

          If provided, it's best to use the same id on all future runs for this machine,
          because of the upload device limit explained below.

        :param uploader_name: human-readable non-unique id; default is ``"<hostname> (gmusicapi)"``.

        There are strict limits on how many upload devices can be registered; refer to `Google's
        docs <http://support.google.com/googleplay/bin/answer.py?hl=en&answer=1230356>`__. There
        have been limits on deauthorizing devices in the past, so it's smart not to register
        more devices than necessary.
        """

        if isinstance(oauth_credentials, basestring):
            oauth_file = oauth_credentials
            storage = oauth2client.file.Storage(oauth_file)

            oauth_credentials = storage.get()
            if oauth_credentials is None:
                self.logger.warning("could not retrieve oauth credentials from '%s'", oauth_file)
                return False

        if not self.session.login(oauth_credentials):
            self.logger.warning("failed to authenticate")
            return False

        self.logger.info("oauth successful")

        if uploader_id is None:
            mac = getmac()
            if (mac >> 40) % 2:
                raise OSError('a valid MAC could not be determined.'
                              ' Provide uploader_id (and be'
                              ' sure to provide the same one on future runs).')

            else:
                #distinguish us from a Music Manager on this machine
                mac = (mac + 1) % (1 << 48)

            mac = hex(mac)[2:-1]
            mac = ':'.join([mac[x:x + 2] for x in range(0, 10, 2)])
            uploader_id = mac.upper()

        if uploader_name is None:
            uploader_name = gethostname() + u" (gmusicapi)"

        try:
            # this is a MM-specific step that might register a new device.
            self._make_call(musicmanager.AuthenticateUploader,
                            uploader_id,
                            uploader_name)
            self.logger.info("successful upauth")
            self.uploader_id = uploader_id
            self.uploader_name = uploader_name

        except CallFailure:
            self.logger.exception("upauth failure")
            self.session.logout()
            return False

        return True
コード例 #14
0
#POST a protobuf object to Google's skyjam servers and return the binary result
def protopost(path, proto):
    global SID, android
    android.request("POST", "/upsj/" + path, proto.SerializeToString(), {
        "Cookie": SID,
        "Content-Type": "application/x-google-protobuf"
    })
    r = android.getresponse()
    print "Response from", path, "Status", r.status, r.reason
    return r.read()


#The UploaderID is identical to the NIC's MAC address
from uuid import getnode as getmac
mac = hex(getmac())[2:-1]
mac = ':'.join([mac[x:x + 2] for x in range(0, 10, 2)])

#The Upload Authentication phase also looks up the hostname
from socket import gethostname
hostname = gethostname()

if options.verbose: print mac, hostname

import metadata_pb2

uauth = metadata_pb2.UploadAuth()
uauth.address = mac
uauth.hostname = hostname

uauthresp = metadata_pb2.UploadAuthResponse()
コード例 #15
0
ファイル: api.py プロジェクト: bruntonspall/xbmc-gmusicapi
    def login(self,
              email,
              password,
              perform_upload_auth=True,
              uploader_id=None,
              uploader_name=None):
        """Authenticates the api.
        Returns ``True`` on success, ``False`` on failure.

        :param email: eg ``'*****@*****.**'`` or just ``'test'``.
        :param password: password or app-specific password for 2-factor users.
          This is not stored locally, and is sent over SSL.

        :param perform_upload_auth: if ``True``, register/authenticate as an upload device.
          This is only required when this Api will be used with :func:`upload`.

        :param uploader_id: a unique id as a MAC address, eg ``'01:23:45:67:89:AB'``.
          This should only be provided in cases where the default
          (host MAC address incremented by 1) will not work.

          Upload behavior is undefined if a Music Manager uses the same id, especially when
          reporting bad matches.

          ``OSError`` will be raised if this is not provided and a stable MAC could not be
          determined (eg when running on a VPS).

          If provided, it's best to use the same id on all future runs for this machine,
          because of the upload device limit explained below.

        :param uploader_name: human-readable non-unique id; default is ``"<hostname> (gmusicapi)"``.

        Users of two-factor authentication will need to set an application-specific password
        to log in.

        There are strict limits on how many upload devices can be registered; refer to `Google's
        docs <http://support.google.com/googleplay/bin/answer.py?hl=en&answer=1230356>`__. There
        have been limits on deauthorizing devices in the past, so it's smart not to register
        more devices than necessary.
        """

        self.session.login(email, password)
        if not self.is_authenticated():
            log.info("failed to authenticate")
            return False

        log.info("authenticated")

        if perform_upload_auth:
            if uploader_id is None:
                mac = getmac()
                if (mac >> 40) % 2:
                    raise OSError(
                        'uploader_id not provided, and a valid MAC could not be found.'
                    )
                else:
                    #distinguish us from a Music Manager on this machine
                    mac = (mac + 1) % (1 << 48)

                mac = hex(mac)[2:-1]
                mac = ':'.join([mac[x:x + 2] for x in range(0, 10, 2)])
                uploader_id = mac.upper()

            if uploader_name is None:
                uploader_name = gethostname() + u" (gmusicapi)"

            try:
                #self._mm_pb_call("upload_auth")
                self._make_call(musicmanager.AuthenticateUploader, uploader_id,
                                uploader_name)
                log.info("successful upload auth")
                self.uploader_id = uploader_id
                self.uploader_name = uploader_name

            except CallFailure:
                log.exception("could not authenticate for uploading")
                self.session.logout()
                return False

        return True
コード例 #16
0
    def login(self, email, password, perform_upload_auth=True,
              uploader_id=None, uploader_name=None):
        """Authenticates the api.
        Returns ``True`` on success, ``False`` on failure.

        :param email: eg ``'*****@*****.**'`` or just ``'test'``.
        :param password: password or app-specific password for 2-factor users.
          This is not stored locally, and is sent over SSL.

        :param perform_upload_auth: if ``True``, register/authenticate as an upload device.
          This is only required when this Api will be used with :func:`upload`.

        :param uploader_id: a unique id as a MAC address, eg ``'01:23:45:67:89:AB'``.
          This should only be provided in cases where the default
          (host MAC address incremented by 1) will not work.

          Upload behavior is undefined if a Music Manager uses the same id, especially when
          reporting bad matches.

          ``OSError`` will be raised if this is not provided and a stable MAC could not be
          determined (eg when running on a VPS).

          If provided, it's best to use the same id on all future runs for this machine,
          because of the upload device limit explained below.

        :param uploader_name: human-readable non-unique id; default is ``"<hostname> (gmusicapi)"``.

        Users of two-factor authentication will need to set an application-specific password
        to log in.

        There are strict limits on how many upload devices can be registered; refer to `Google's
        docs <http://support.google.com/googleplay/bin/answer.py?hl=en&answer=1230356>`__. There
        have been limits on deauthorizing devices in the past, so it's smart not to register
        more devices than necessary.
        """

        self.session.login(email, password)
        if not self.is_authenticated():
            self.log.info("failed to authenticate")
            return False

        self.log.info("authenticated")

        if perform_upload_auth:
            if uploader_id is None:
                mac = getmac()
                if (mac >> 40) % 2:
                    raise OSError('uploader_id not provided, and a valid MAC could not be found.')
                else:
                    #distinguish us from a Music Manager on this machine
                    mac = (mac + 1) % (1 << 48)

                mac = hex(mac)[2:-1]
                mac = ':'.join([mac[x:x + 2] for x in range(0, 10, 2)])
                uploader_id = mac.upper()

            if uploader_name is None:
                uploader_name = gethostname() + u" (gmusicapi)"

            try:
                #self._mm_pb_call("upload_auth")
                self._make_call(musicmanager.AuthenticateUploader,
                                uploader_id,
                                uploader_name)
                self.log.info("successful upload auth")
                self.uploader_id = uploader_id
                self.uploader_name = uploader_name

            except CallFailure:
                self.log.exception("could not authenticate for uploading")
                self.session.logout()
                return False

        return True
コード例 #17
0
ファイル: gnutella.py プロジェクト: Zethor456/ChordInPython
      os.makedirs(directory)
    logPath = os.path.join(directory, "output.log")
    open(logPath, "w").close()  # Create or empty current log file
#    logFile = open(os.path.join(directory, "output.log"), "w")
    directory = os.path.join(directory, 'files')
    if not os.path.exists(directory):
      os.makedirs(directory)
    print "Run \"tail -c +0 -f {0}\" in another terminal to see output".format(logPath)
    printLine("Using directory: {0}".format(directory))

    # Set up Twisted clients
    if(targetIP and targetPort):
      reactor.connectTCP(targetIP, targetPort, GnutellaFactory(initiating))#@UndefinedVariable
    listener = GnutellaFactory()
    usedPort = reactor.listenTCP(port, listener)#@UndefinedVariable
    host = usedPort.getHost()
    IP = host.host
    port = host.port
    nodeID = "{0}{1:05}".format(getmac(), port)
    printLine("IP address: {0}:{1}".format(host.host, host.port))
    resource = File(directory)
    fileServer = reactor.listenTCP(0, Site(resource))#@UndefinedVariable
    serverPort = fileServer.getHost().port
    printLine("File serving port: {0}".format(serverPort))
    printLine("Node ID: {0}".format(nodeID))
    reactor.callInThread(readInput)#@UndefinedVariable
    reactor.run()#@UndefinedVariable
    logFile.close()
  else:
    print "Must give a directory path"
コード例 #18
0
ファイル: __init__.py プロジェクト: kr2/plugins
    def push(self, key):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((self._host, int(self._port)))
            self.logger.debug("Connected to {0}:{1}".format(
                self._host, self._port))
        except Exception:
            self.logger.warning(
                "Could not connect to %s:%s, to send key: %s." %
                (self._host, self._port, key))
            return

        src = s.getsockname()[0]  # ip of remote
        mac = self._int_to_str(getmac())  # mac of remote
        remote = 'sh.py remote'  # remote name
        dst = self._host  # ip of tv
        app = b'python'  # iphone..iapp.samsung
        tv = b'UE32ES6300'  # iphone.UE32ES6300.iapp.samsung

        self.logger.debug(
            "src = {0}, mac = {1}, remote = {2}, dst = {3}, app = {4}, tv = {5}"
            .format(src, mac, remote, dst, app, tv))

        src = base64.b64encode(src.encode())
        mac = base64.b64encode(mac.encode())
        cmd = base64.b64encode(key.encode())
        rem = base64.b64encode(remote.encode())

        msg = bytearray([0x64, 0])
        msg.extend([len(src), 0])
        msg.extend(src)
        msg.extend([len(mac), 0])
        msg.extend(mac)
        msg.extend([len(rem), 0])
        msg.extend(rem)

        pkt = bytearray([0])
        pkt.extend([len(app), 0])
        pkt.extend(app)
        pkt.extend([len(msg), 0])
        pkt.extend(msg)

        try:
            s.send(pkt)
        except:
            try:
                s.close()
            except:
                pass
            return

        msg = bytearray([0, 0, 0])
        msg.extend([len(cmd), 0])
        msg.extend(cmd)

        pkt = bytearray([0])
        pkt.extend([len(tv), 0])
        pkt.extend(tv)
        pkt.extend([len(msg), 0])
        pkt.extend(msg)

        try:
            s.send(pkt)
        except:
            return
        finally:
            try:
                s.close()
            except:
                pass
        self.logger.debug("Send {0} to Smart TV".format(key))
        time.sleep(0.1)
コード例 #19
0
    def _get_android_id() -> str:
        mac_int = getmac()
        android_id = TokenDispenser._create_mac_string(mac_int)
        android_id = android_id.replace(':', '')

        return android_id
コード例 #20
0
android = httplib.HTTPSConnection("android.clients.google.com")

#POST a protobuf object to Google's skyjam servers and return the binary result
def protopost(path, proto):
	global SID, android
	android.request("POST", "/upsj/"+path, proto.SerializeToString(), {
		"Cookie": SID,
		"Content-Type": "application/x-google-protobuf"
	})
	r = android.getresponse()
	print "Response from", path, "Status", r.status, r.reason
	return r.read()

#The UploaderID is identical to the NIC's MAC address
from uuid import getnode as getmac
mac = hex(getmac())[2:-1]
mac = ':'.join([mac[x:x+2] for x in range(0, 10, 2)])

#The Upload Authentication phase also looks up the hostname
from socket import gethostname
hostname = gethostname()

if options.verbose: print mac, hostname

import metadata_pb2

uauth = metadata_pb2.UploadAuth()
uauth.address = mac
uauth.hostname = hostname

uauthresp = metadata_pb2.UploadAuthResponse()
コード例 #21
0
ファイル: gnutella.py プロジェクト: rslu2000/Gnutella
        open(logPath, "w").close()  #Create or empty current log file
        #    logFile = open(os.path.join(directory, "output.log"), "w")
        directory = os.path.join(directory, 'files')
        if not os.path.exists(directory):
            os.makedirs(directory)
        print "Run \"tail -c +0 -f {0}\" in another terminal to see output".format(
            logPath)
        printLine("Using directory: {0}".format(directory))

        #Set up Twisted clients
        if (targetIP and targetPort):
            reactor.connectTCP(targetIP, targetPort,
                               GnutellaFactory(initiating))
        listener = GnutellaFactory()
        usedPort = reactor.listenTCP(port, listener)
        host = usedPort.getHost()
        IP = host.host
        port = host.port
        nodeID = "{0}{1:05}".format(getmac(), port)
        printLine("IP address: {0}:{1}".format(host.host, host.port))
        resource = File(directory)
        fileServer = reactor.listenTCP(0, Site(resource))
        serverPort = fileServer.getHost().port
        printLine("File serving port: {0}".format(serverPort))
        printLine("Node ID: {0}".format(nodeID))
        reactor.callInThread(readInput)
        reactor.run()
        logFile.close()
    else:
        print "Must give a directory path"
コード例 #22
0
def get_device_mac():
    return str(hex(getmac())[2:])
コード例 #23
0
    def login(self, oauth_credentials=OAUTH_FILEPATH,
              uploader_id=None, uploader_name=None):
        """Authenticates the Music Manager using OAuth.
        Returns ``True`` on success, ``False`` on failure.

        Unlike the :class:`Webclient`, OAuth allows authentication without
        providing plaintext credentials to the application.

        In most cases, the default parameters should be acceptable. Users on
        virtual machines will want to provide `uploader_id`.

        :param oauth_credentials: ``oauth2client.client.OAuth2Credentials`` or the path to a
          ``oauth2client.file.Storage`` file. By default, the same default path used by
          :func:`perform_oauth` is used.

          Endusers will likely call :func:`perform_oauth` once to write
          credentials to disk and then ignore this parameter.

          This param
          is mostly intended to allow flexibility for developers of a
          3rd party service who intend to perform their own OAuth flow
          (eg on their website).

        :param uploader_id: a unique id as a MAC address, eg ``'01:23:45:67:89:AB'``.
          This should only be provided in cases where the default
          (host MAC address incremented by 1) will not work.

          Upload behavior is undefined if a Music Manager uses the same id, especially when
          reporting bad matches.

          ``OSError`` will be raised if this is not provided and a stable MAC could not be
          determined (eg when running on a VPS).

          If provided, it's best to use the same id on all future runs for this machine,
          because of the upload device limit explained below.

        :param uploader_name: human-readable non-unique id; default is ``"<hostname> (gmusicapi)"``.

        There are strict limits on how many upload devices can be registered; refer to `Google's
        docs <http://support.google.com/googleplay/bin/answer.py?hl=en&answer=1230356>`__. There
        have been limits on deauthorizing devices in the past, so it's smart not to register
        more devices than necessary.
        """

        if isinstance(oauth_credentials, basestring):
            oauth_file = oauth_credentials
            storage = oauth2client.file.Storage(oauth_file)

            oauth_credentials = storage.get()
            if oauth_credentials is None:
                self.logger.warning("could not retrieve oauth credentials from '%s'", oauth_file)
                return False

        if not self.session.login(oauth_credentials):
            self.logger.warning("failed to authenticate")
            return False

        self.logger.info("oauth successful")

        if uploader_id is None:
            mac = getmac()
            if (mac >> 40) % 2:
                raise OSError('a valid MAC could not be determined.'
                              ' Provide uploader_id (and be'
                              ' sure to provide the same one on future runs).')

            else:
                #distinguish us from a Music Manager on this machine
                mac = (mac + 1) % (1 << 48)

            mac = hex(mac)[2:-1]
            mac = ':'.join([mac[x:x + 2] for x in range(0, 10, 2)])
            uploader_id = mac.upper()

        if uploader_name is None:
            uploader_name = gethostname() + u" (gmusicapi)"

        try:
            # this is a MM-specific step that might register a new device.
            self._make_call(musicmanager.AuthenticateUploader,
                            uploader_id,
                            uploader_name)
            self.logger.info("successful upauth")
            self.uploader_id = uploader_id
            self.uploader_name = uploader_name

        except CallFailure:
            self.logger.exception("upauth failure")
            self.session.logout()
            return False

        return True
コード例 #24
0
ファイル: client.py プロジェクト: cl3t0/cookiethiefxss
import urllib.request
from time import sleep
from uuid import uuid4
from uuid import getnode as getmac

print('Esse programa foi criado com fins educacionais!')
print('Os criadores não se responsabilizam por qualquer tipo de irregularidade feita usando nosso sistema.')

at = 0
target = ''
server = 'http://seuservidor/'
id = str(uuid4())
mac = ''
mac += ':'.join(['{:02x}'.format((getmac() >> ele) & 0xff)
for ele in range(0,8*6,8)][::-1])
print('id: ' + id)
print('mac: ' + mac)

def testconnection():
    print('''
                     __   .__           __  .__    .__        _____  ____  ___ _________ _________
  ____  ____   ____ |  | _|__| ____   _/  |_|  |__ |__| _____/ ____\ \   \/  //   _____//   _____/
_/ ___\/  _ \ /  _ \|  |/ |  _/ __ \  \   __|  |  \|  _/ __ \   __\   \     / \_____  \ \_____  \ 
\  \__(  <_> (  <_> |    <|  \  ___/   |  | |   Y  |  \  ___/|  |     /     \ /        \/        /
 \___  \____/ \____/|__|_ |__|\___  >  |__| |___|  |__|\___  |__|    /___/\  /_______  /_______  /
     \/                  \/       \/             \/        \/              \_/       \/        \/    
    ''')
    print('Testando se vocẽ está conectado na internet...')
    try:
        urllib.request.urlopen('http://google.com')