Exemplo n.º 1
0
async def execute(command, input=None, chdir=None, interactive=False,
                  stderr=None, stdout=None, **kw):
    """Execute a shell command
    :param command: command to execute
    :param input: optional input
    :param chdir: optional directory to execute the shell command from
    :param  interactive: display output as it becomes available
    :return: the output text
    """
    stdin = asyncio.subprocess.PIPE if input is not None else None
    if chdir:
        command = 'cd %s && %s' % (chdir, command)

    proc = await asyncio.create_subprocess_shell(
        command,
        stdin=stdin,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        limit=STREAM_LIMIT
    )
    if input is not None:
        proc._feed_stdin(to_bytes(input))

    msg, err = await asyncio.gather(
        _interact(proc, 1, interactive, stdout or sys.stdout),
        _interact(proc, 2, interactive, stderr or sys.stderr)
    )
    if proc.returncode:
        msg = '%s%s' % (msg.decode('utf-8'), err.decode('utf-8'))
        raise ShellError(msg.strip(), proc.returncode)
    return msg.decode('utf-8').strip()
Exemplo n.º 2
0
 def digest_auth_header(self,
                        realm=None,
                        nonce=None,
                        qop=None,
                        opaque=None,
                        algorithm=None,
                        stale=None):
     options = {}
     if nonce is None:
         nonce = hexmd5(to_bytes('%d' % time.time()) + os.urandom(10))
         if opaque is None:
             opaque = hexmd5(os.urandom(10))
     if stale:
         options['stale'] = 'TRUE'
     if opaque is not None:
         options['opaque'] = opaque
     if algorithm is not None:
         options['algorithm'] = algorithm
     if qop is None:
         qop = ('auth', )
     return self._auth_header('digest',
                              realm=realm,
                              nonce=nonce,
                              qop=', '.join(qop),
                              **options)
Exemplo n.º 3
0
    def _encode_body(self, data, files, json):
        body = None
        ct = None
        if isinstance(data, (str, bytes)):
            if files:
                raise ValueError('data cannot be a string or bytes when '
                                 'files are present')
            body = to_bytes(data, self.charset)
        elif data and is_streamed(data):
            if files:
                raise ValueError('data cannot be an iterator when '
                                 'files are present')
            if 'content-length' not in self.headers:
                self.headers['transfer-encoding'] = 'chunked'
            return data
        elif data or files:
            if files:
                body, ct = self._encode_files(data, files)
            else:
                body, ct = self._encode_params(data)
        elif json:
            body = _json.dumps(json).encode(self.charset)
            ct = 'application/json'

        if not self.headers.get('content-type') and ct:
            self.headers['Content-Type'] = ct

        if body:
            self.headers['content-length'] = str(len(body))

        return body
Exemplo n.º 4
0
    def _encode_body(self, data, files, json):
        body = None
        ct = None
        if isinstance(data, (str, bytes)):
            if files:
                raise ValueError('data cannot be a string or bytes when '
                                 'files are present')
            body = to_bytes(data, self.charset)
        elif data and is_streamed(data):
            if files:
                raise ValueError('data cannot be an iterator when '
                                 'files are present')
            if 'content-length' not in self.headers:
                self.headers['transfer-encoding'] = 'chunked'
            return data
        elif data or files:
            if files:
                body, ct = self._encode_files(data, files)
            else:
                body, ct = self._encode_params(data)
        elif json:
            body = _json.dumps(json).encode(self.charset)
            ct = 'application/json'

        if not self.headers.get('content-type') and ct:
            self.headers['Content-Type'] = ct

        if body:
            self.headers['content-length'] = str(len(body))

        return body
Exemplo n.º 5
0
async def execute(command,
                  input=None,
                  chdir=None,
                  interactive=False,
                  stderr=None,
                  stdout=None,
                  **kw):
    """Execute a shell command
    :param command: command to execute
    :param input: optional input
    :param chdir: optional directory to execute the shell command from
    :param  interactive: display output as it becomes available
    :return: the output text
    """
    stdin = asyncio.subprocess.PIPE if input is not None else None
    if chdir:
        command = 'cd %s && %s' % (chdir, command)

    proc = await asyncio.create_subprocess_shell(
        command,
        stdin=stdin,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        limit=STREAM_LIMIT)
    if input is not None:
        proc._feed_stdin(to_bytes(input))

    msg, err = await asyncio.gather(
        _interact(proc, 1, interactive, stdout or sys.stdout),
        _interact(proc, 2, interactive, stderr or sys.stderr))
    if proc.returncode:
        msg = '%s%s' % (msg.decode('utf-8'), err.decode('utf-8'))
        raise ShellError(msg.strip(), proc.returncode)
    return msg.decode('utf-8').strip()
Exemplo n.º 6
0
 def digest_auth_header(self, realm=None, nonce=None, qop=None, opaque=None,
                        algorithm=None, stale=None):
     options = {}
     if nonce is None:
         nonce = hexmd5(to_bytes('%d' % time.time()) + os.urandom(10))
         if opaque is None:
             opaque = hexmd5(os.urandom(10))
     if stale:
         options['stale'] = 'TRUE'
     if opaque is not None:
         options['opaque'] = opaque
     if algorithm is not None:
         options['algorithm'] = algorithm
     if qop is None:
         qop = ('auth',)
     return self._auth_header('digest', realm=realm, nonce=nonce,
                              qop=', '.join(qop), **options)
Exemplo n.º 7
0
    def _encode_params(self, params):
        content_type = self.headers.get('content-type')
        # No content type given, chose one
        if not content_type:
            content_type = FORM_URL_ENCODED

        if hasattr(params, 'read'):
            params = params.read()

        if content_type in JSON_CONTENT_TYPES:
            body = _json.dumps(params)
        elif content_type == FORM_URL_ENCODED:
            body = urlencode(tuple(split_url_params(params)))
        elif content_type == MULTIPART_FORM_DATA:
            body, content_type = encode_multipart_formdata(
                params, charset=self.charset)
        else:
            body = params
        return to_bytes(body, self.charset), content_type
Exemplo n.º 8
0
    def _encode_params(self, params):
        content_type = self.headers.get('content-type')
        # No content type given, chose one
        if not content_type:
            content_type = FORM_URL_ENCODED

        if hasattr(params, 'read'):
            params = params.read()

        if content_type in JSON_CONTENT_TYPES:
            body = _json.dumps(params)
        elif content_type == FORM_URL_ENCODED:
            body = urlencode(tuple(split_url_params(params)))
        elif content_type == MULTIPART_FORM_DATA:
            body, content_type = encode_multipart_formdata(
                params, charset=self.charset)
        else:
            body = params
        return to_bytes(body, self.charset), content_type
Exemplo n.º 9
0
    def validate(self, request):
        secret = to_bytes(self.secret)
        hub_signature = request.get('HTTP_X_HUB_SIGNATURE')

        if not hub_signature:
            raise PermissionDenied('No signature')

        if '=' in hub_signature:
            sha_name, signature = hub_signature.split('=')
            if sha_name != 'sha1':
                raise PermissionDenied('Bad signature')
        else:
            raise BadRequest('bad signature')

        payload = request.get('wsgi.input').read()
        sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha1)

        if sig.hexdigest() != signature:
            raise PermissionDenied('Bad signature')
Exemplo n.º 10
0
    async def shell(
        self,
        command,
        input=None,
        chdir=None,
        interactive=False,
        interactive_stderr=None,
        stderr=None,
        stdout=None,
        **kw
    ):
        """Execute a shell command
        :param command: command to execute
        :param input: optional input
        :param chdir: optional directory to execute the shell command from
        :param  interactive: display output as it becomes available
        :return: the output text
        """
        stdin = asyncio.subprocess.PIPE if input is not None else None
        if chdir:
            command = "cd %s && %s" % (chdir, command)

        if interactive_stderr is None:
            interactive_stderr = interactive

        proc = await asyncio.create_subprocess_shell(
            command, stdin=stdin, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
        )
        if input is not None:
            proc._feed_stdin(to_bytes(input))

        msg, err = await asyncio.gather(
            _interact(proc, 1, interactive, stdout or sys.stdout),
            _interact(proc, 2, interactive_stderr, stderr or sys.stderr),
        )
        if proc.returncode:
            msg = err.decode("utf-8") or msg.decode("utf-8")
            raise ShellError(msg, proc.returncode)
        return msg.decode("utf-8")
Exemplo n.º 11
0
def github_signature(secret, payload):
    secret = to_bytes(secret)
    if isinstance(payload, dict):
        payload = json.dumps(payload)
    payload = to_bytes(payload)
    return hmac.new(secret, msg=payload, digestmod=hashlib.sha1)
Exemplo n.º 12
0
def github_signature(secret, payload):
    secret = to_bytes(secret)
    if isinstance(payload, dict):
        payload = json.dumps(payload)
    payload = to_bytes(payload)
    return hmac.new(secret, msg=payload, digestmod=hashlib.sha1)
Exemplo n.º 13
0
 def challenge_response(self, key):
     sha1 = hashlib.sha1(to_bytes(key + WEBSOCKET_GUID))
     return native_str(base64.b64encode(sha1.digest()))