Python socket.SOCK_STREAM Examples

The following are 30 code examples of socket.SOCK_STREAM(). 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: server.py    From RF-Monitor with GNU General Public License v2.0 10 votes vote down vote up
def __init__(self, eventHandler):
        threading.Thread.__init__(self)
        self.name = 'Server'
        self.daemon = True
        self._eventHandler = eventHandler

        self._client = None
        self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        try:
            self._server.bind(('', PORT))
            self._server.listen(5)
        except socket.error:
            event = Event(Events.SCAN_ERROR, msg='Could not start server')
            post_event(eventHandler, event)
            return

        self._cancel = False
        self.start() 
Example #2
Source File: SockPuppet.py    From ALF with Apache License 2.0 8 votes vote down vote up
def connect(self):
        if self.is_server:
            log.debug("waiting for client to connect...")
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind(('', self.port))
            s.settimeout(0.1)
            start_time = time.time()
            s.listen(0)
            while True:
                try:
                    conn, _ = s.accept()
                    self.conn = conn
                    break
                except socket.timeout:
                    pass
                if self.timeout > 0 and time.time() - start_time >= self.timeout:
                    s.close()
                    raise RuntimeError("Timeout exceeded (%ds)" % self.timeout)
            self.conn.setblocking(True)
        else:
            log.debug("connecting to server (%s:%d)...", self.ip, self.port)
            self.conn = socket.create_connection((self.ip, self.port), self.timeout) 
Example #3
Source File: start.py    From Starx_Pixiv_Collector with MIT License 8 votes vote down vote up
def ip_latency_test(ip, port=443):
    tag = 'IP_Latency_TEST'
    print_with_tag(tag, ['Prepare IP latency test for ip', ip, 'Port', str(port)])
    s_test = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s_test.settimeout(10)
    s_start = time.time()
    try:
        s_test.connect((ip, port))
        s_test.shutdown(socket.SHUT_RD)
    except Exception as e:
        print_with_tag(tag, ['Error:', e])
        return None
    s_stop = time.time()
    s_runtime = '%.2f' % (1000 * (s_stop - s_start))
    print_with_tag(tag, [ip, 'Latency:', s_runtime])
    return float(s_runtime) 
Example #4
Source File: usbmux.py    From facebook-wda with MIT License 7 votes vote down vote up
def __init__(self, addr: Union[str, tuple, socket.socket]):
        """
        Args:
            addr: can be /var/run/usbmuxd or (localhost, 27015)
        """
        self._sock = None
        if isinstance(addr, socket.socket):
            self._sock = addr
            return
        if isinstance(addr, str):
            if not os.path.exists(addr):
                raise MuxError("socket unix:{} unable to connect".format(addr))
            family = socket.AF_UNIX
        else:
            family = socket.AF_INET

        self._sock = socket.socket(family, socket.SOCK_STREAM)
        self._sock.connect(addr) 
Example #5
Source File: script_runner.py    From InsightAgent with Apache License 2.0 7 votes vote down vote up
def acceptThread(parameters):
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    acceptor.bind(('', int(parameters['listenPort'])))
    acceptor.listen(5)
    cur_thread = threading.current_thread()
    logger.info("Listening to connections on port " + str(parameters['listenPort']) + '\n')

    while True:
        (clientSock, clientAddr) = acceptor.accept()
        print "==== Output Request ====="
        msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
        logger.info(msg)
        thread3 = threading.Thread(target=sendFile, args=(clientSock, parameters))
        thread3.daemon = True
        thread3.start()
    acceptor.close()
    return 
Example #6
Source File: sublist3r.py    From subtake with GNU General Public License v2.0 6 votes vote down vote up
def port_scan(self, host, ports):
        openports = []
        self.lock.acquire()
        for port in ports:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(2)
                result = s.connect_ex((host, int(port)))
                if result == 0:
                    openports.append(port)
                s.close()
            except Exception:
                pass
        self.lock.release()
        if len(openports) > 0:
            print("%s%s%s - %sFound open ports:%s %s%s%s" % (G, host, W, R, W, Y, ', '.join(openports), W)) 
Example #7
Source File: tmgr.py    From iSDX with Apache License 2.0 6 votes vote down vote up
def connect (host, why):    
    # should be either a listener host or a router host (edge-router)
    if host not in bgprouters and host not in hosts and host not in participants:
            log.error('MM:' + host + ' ERROR: ' + why + ': Unknown host: ' + host)
            return None    
    try:
        hostdata = hosts[host]
    except:
        try:
            hostdata = bgprouters[host]
        except:
            hostdata = participants[host]

    #print 'MM:' + host + ' INFO: ' + why + ': Connecting to ' + host + ' at ' + hostdata.host + ':' + str(hostdata.port)

    try:
        if hostdata.port is None:
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
            s.connect(hostdata.host)
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((hostdata.host, int(hostdata.port)))
    except Exception, e:
        log.error('MM:' + host + ' ERROR: ' + why + ': ' + repr(e))
        return None 
Example #8
Source File: tmgr.py    From iSDX with Apache License 2.0 6 votes vote down vote up
def genericObjNW (host, label, cmd):
    
    if host not in participants:
            log.error('MM:' + host + ' ERROR: ' + label + ': Can only send to a participant: ' + host)
            return None    
    try:
        hostdata = hosts[host]
    except:
        try:
            hostdata = bgprouters[host]
        except:
            hostdata = participants[host]

    #print 'MM:' + host + ' INFO: ' + why + ': Connecting to ' + host + ' at ' + hostdata.host + ':' + str(hostdata.port)

    try:
        if hostdata.port is None:
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
            s.connect(hostdata.host)
        else:
            s = Client((hostdata.host, int(hostdata.port)))
    except Exception, e:
        log.error('MM:' + host + ' ERROR: ' + label + ': ' + repr(e))
        return None 
Example #9
Source File: sdnip.py    From iSDX with Apache License 2.0 6 votes vote down vote up
def config(self, **kwargs):
        super(BgpRouter, self).config(**kwargs)

        self.cmd('%s/zebra -d -f %s -z %s -i %s'
                 % (BgpRouter.binDir, self.zebraConfFile, self.socket, self.zebraPidFile))
        while True:
            try:
                s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
                s.connect(self.socket)
                #print 'connected - breaking'
                s.close()
                break
            except Exception, e:
                #print' ERROR: ' + repr(e)
                time.sleep(.1)
        #print 'zebra ready' 
Example #10
Source File: rsync_unauthorized_access.py    From Vxscan with Apache License 2.0 6 votes vote down vote up
def check(url, ip, ports, apps):
    if verify(vuln, ports, apps):
        try:
            socket.setdefaulttimeout(1.5)
            payload = b"\x40\x52\x53\x59\x4e\x43\x44\x3a\x20\x33\x31\x2e\x30\x0a"
            socket.setdefaulttimeout(timeout)
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_address = (ip, 873)
            sock.connect(server_address)
            sock.sendall(payload)
            initinfo = sock.recv(400)
            if b"RSYNCD" in initinfo:
                sock.sendall(b"\x0a")
            modulelist = sock.recv(200)
            sock.close()
            if len(modulelist) > 0:
                return '873 Rsync Unauthorized Access'
        except Exception as e:
            pass 
Example #11
Source File: client-test2.py    From The-chat-room with MIT License 6 votes vote down vote up
def fileGet(name):
    PORT3 = 50009
    ss2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ss2.connect((IP, PORT3))
    message = 'get ' + name
    ss2.send(message.encode())
    fileName = '.\\Client_image_cache\\' + name
    print('Start downloading image!')
    print('Waiting.......')
    with open(fileName, 'wb') as f:
        while True:
            data = ss2.recv(1024)
            if data == 'EOF'.encode():
                print('Download completed!')
                break
            f.write(data)
    time.sleep(0.1)
    ss2.send('quit'.encode())


# 将图片上传到图片服务端的缓存文件夹中 
Example #12
Source File: tnode.py    From iSDX with Apache License 2.0 6 votes vote down vote up
def create_command_listener (baddr, port):
    try:
        if port is None:
            try:
                if os.path.exists(baddr):
                    os.unlink(baddr)
            except OSError:
                print 'could not remove old unix socket ' + baddr
                return
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
            s.bind(baddr)
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((baddr, int(port)))
    except socket.error , msg:
        print 'Bind failed on command interface ' + baddr + ' port ' + str(port) + ' Error Code : ' + str(msg[0]) + ' Message ' + msg[1] + '\n'
        return 
Example #13
Source File: handlers.py    From jawfish with MIT License 6 votes vote down vote up
def _connect_unixsocket(self, address):
        use_socktype = self.socktype
        if use_socktype is None:
            use_socktype = socket.SOCK_DGRAM
        self.socket = socket.socket(socket.AF_UNIX, use_socktype)
        try:
            self.socket.connect(address)
            # it worked, so set self.socktype to the used type
            self.socktype = use_socktype
        except socket.error:
            self.socket.close()
            if self.socktype is not None:
                # user didn't specify falling back, so fail
                raise
            use_socktype = socket.SOCK_STREAM
            self.socket = socket.socket(socket.AF_UNIX, use_socktype)
            try:
                self.socket.connect(address)
                # it worked, so set self.socktype to the used type
                self.socktype = use_socktype
            except socket.error:
                self.socket.close()
                raise 
Example #14
Source File: client-test.py    From The-chat-room with MIT License 6 votes vote down vote up
def fileGet(name):
    PORT3 = 50009
    ss2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ss2.connect((IP, PORT3))
    message = 'get ' + name
    ss2.send(message.encode())
    fileName = '.\\Client_image_cache\\' + name
    print('Start downloading image!')
    print('Waiting.......')
    with open(fileName, 'wb') as f:
        while True:
            data = ss2.recv(1024)
            if data == 'EOF'.encode():
                print('Download completed!')
                break
            f.write(data)
    time.sleep(0.1)
    ss2.send('quit'.encode())


# 将图片上传到图片服务端的缓存文件夹中 
Example #15
Source File: TCP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def stop(self):
		self._stop = True

		if self.threads:
			for t in self.threads:
				t.stop()
		
		# not so nice solution to get rid of the block of listen()
		# unfortunately close() does not help on the block
		try:
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			serverbind = self.config.get("Global", "serverbind")
			if serverbind == "0.0.0.0":
				# windows does not like to connect to 0.0.0.0
				serverbind = "127.0.0.1"

			server_socket.connect((serverbind, int(self.config.get(self.get_module_configname(), "serverport"))))
		except:
			pass

		return 
Example #16
Source File: TCP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = TCP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 
Example #17
Source File: Server.py    From EvilOSX with GNU General Public License v3.0 6 votes vote down vote up
def start_server(port):
    # Start the server
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('', port))
    server_socket.listen(128)  # Maximum connections Mac OSX can handle.

    status_messages.append(MESSAGE_INFO + "Successfully started the server on port {0}.".format(str(port)))
    status_messages.append(MESSAGE_INFO + "Waiting for clients...")

    while True:
        client_connection, client_address = ssl.wrap_socket(server_socket, cert_reqs=ssl.CERT_NONE, server_side=True, keyfile="server.key", certfile="server.crt").accept()

        status_messages.append(MESSAGE_INFO + "New client connected!")
        connections.append(client_connection) 
Example #18
Source File: XAsyncSockets.py    From MicroWebSrv2 with MIT License 6 votes vote down vote up
def Create(asyncSocketsPool, srvAddr, srvBacklog=256, bufSlots=None) :
        try :
            srvSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except :
            raise XAsyncTCPServerException('Create : Cannot open socket (no enought memory).')
        try :
            srvSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            srvSocket.bind(srvAddr)
            srvSocket.listen(srvBacklog)
        except :
            raise XAsyncTCPServerException('Create : Error to binding the TCP server on this address.')
        if not bufSlots :
            bufSlots = XBufferSlots(256, 4096, keepAlloc=True)
        xAsyncTCPServer = XAsyncTCPServer( asyncSocketsPool,
                                           srvSocket,
                                           srvAddr,
                                           bufSlots )
        asyncSocketsPool.NotifyNextReadyForReading(xAsyncTCPServer, True)
        return xAsyncTCPServer

    # ------------------------------------------------------------------------ 
Example #19
Source File: interface.py    From XFLTReaT with MIT License 6 votes vote down vote up
def mac_set_ip_address(self, dev, ip, serverip, netmask):
		ifr = struct.pack('<16sBBHIIIBBHIIIBBHIII',
			self.iface_name,
			16, socket.AF_INET, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, ip))[0], 0, 0,
			16, socket.AF_INET, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, serverip))[0], 0, 0,
			16, 0, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, "255.255.255.255"))[0], 0, 0)
		try:
			sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			fcntl.ioctl(sock, self.IOCTL_MACOSX_SIOCAIFADDR, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))
		ps = subprocess.Popen(["route", "add", "-net", rangeip+"/"+netmask, serverip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example #20
Source File: interface.py    From XFLTReaT with MIT License 6 votes vote down vote up
def freebsd_tun_alloc(self, dev, flags):
		try:
			sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			ifr = struct.pack('<16si', 'tun', 0)
			self.iface_name = fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCIFCREATE2, ifr)
			self.iface_name = self.iface_name.rstrip("\x00")

			buff = array.array('c', dev+"\x00")
			caddr_t, _ = buff.buffer_info()
			ifr = struct.pack('16sP', self.iface_name, caddr_t);

			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFNAME, ifr)
			tun = os.open("/dev/"+self.iface_name, os.O_RDWR | os.O_NONBLOCK)
			self.iface_name = dev

		except IOError as e:
			print e
			common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
			sys.exit(-1)

		return tun 
Example #21
Source File: interface.py    From XFLTReaT with MIT License 6 votes vote down vote up
def freebsd_set_ip_address(self, dev, ip, serverip, netmask):
		sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			#set ip, serverip and netmask
			ifaliasreq = struct.pack('<16sBBHI8sBBHI8sBBHI8sI', self.iface_name,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton(ip))[0], '\x00'*8,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton(serverip))[0], '\x00'*8,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton('255.255.255.255'))[0],
				'\x00'*8,
				0)
			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCAIFADDR, ifaliasreq)

			# get flags
			ifr = struct.pack('<16sh', self.iface_name, 0)
			flags = struct.unpack('<16sh', fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCGIFFLAGS, ifr))[1]

			# set new flags
			flags = flags | self.IOCTL_FREEBSD_IFF_UP
			ifr = struct.pack('<16sh', self.iface_name, flags)

			# iface up
			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFFLAGS, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))

		ps = subprocess.Popen(["route", "add", "-net", rangeip+"/"+netmask, serverip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example #22
Source File: reporting_send.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def acceptThread():       
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        
    acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    acceptor.bind(('', int(uploadPort)))
    acceptor.listen(5)
        
    cur_thread=threading.current_thread()
    while True:            
        (clientSock,clientAddr)=acceptor.accept()
        print "====Output Request:"
        msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
        print msg
        thread3=threading.Thread(target=sendFile(clientSock))
        thread3.daemon=True
        thread3.start()
        #thread3.join()            
    acceptor.close()
    return 
Example #23
Source File: pdinstall.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def sendCommand(command, data):
    """
    Send a command to the pdinstall service.

    Commands:
    install - Install snaps from a file path or http(s) URL.
        Required data fields:
        sources - List with at least one snap file path or URL.  The snaps
                  are installed in order until one succeeds or all fail.

    Returns True/False for success.  Currently, we cannot check whether the
    call succeeded, only whether it was delived.  A return value of False means
    we could not deliver the command to pdinstall.
    """
    data['command'] = command

    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        sock.connect(SOCKET_ADDRESS)
        sock.send(json.dumps(data))
        return True
    except:
        return False
    finally:
        sock.close() 
Example #24
Source File: _socket_proxy.py    From oscrypto with MIT License 6 votes vote down vote up
def make_socket_proxy(ip, port, send_callback=None, recv_callback=None):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(('', 8080))
    server.listen(1)
    t = threading.Thread(
        target=listen,
        args=(server, ip, port, send_callback, recv_callback)
    )
    t.start()
    sock = socket.create_connection(('localhost', 8080))
    sock.settimeout(1)
    t.join()
    with _socket_lock:
        data = _sockets[t.ident]
        return (sock, data['lsock'], data['rsock'], server) 
Example #25
Source File: zookeeper_unauthorized_access.py    From Vxscan with Apache License 2.0 5 votes vote down vote up
def check(url, ip, ports, apps):
    if verify(vuln, ports, apps):
        try:
            socket.setdefaulttimeout(2)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((ip, 2181))
            s.send(b'success')
            data = s.recv(1024)
            if b'Environment' in data:
                return '2181 Zookeeper Unauthorized access'
        except Exception as e:
            pass 
Example #26
Source File: rtp_cluster_client.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def cli_client(address, argv, tcp = False):
    if not tcp:
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    else:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(address)
    command = reduce(lambda x, y: x + ' ' + y, argv)
    s.send(command.encode('ascii') + b'\nquit\n')
    while True:
        data = s.recv(1024)
        if len(data) == 0:
            break
        sys.stdout.write(data.decode('ascii')) 
Example #27
Source File: redis_unauthorized_access.py    From Vxscan with Apache License 2.0 5 votes vote down vote up
def check(url, ip, ports, apps):
    if verify(vuln, ports, apps):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(5)
        try:
            s.connect((ip, 6379))
            payload = b'\x2a\x31\x0d\x0a\x24\x34\x0d\x0a\x69\x6e\x66\x6f\x0d\x0a'
            s.send(payload)
            data = s.recv(1024)
            s.close()
            if b"redis_version" in data:
                return '6379 Redis Unauthorized Access'
        except Exception as e:
            s.close() 
Example #28
Source File: piescan.py    From piescan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tcp_scan((target, port)):

    target, port = (target, port)

    try:
        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1,0))
        conn.settimeout(timeout)

        ret = conn.connect_ex((target, port))

	# DATA RECIEVED - SYN ACK
        if (ret==0):
            if VERBOSE:
                sys.stdout.write("[%s] %s - %d/tcp open (SYN-ACK packet)\n" % (date_time(), target, port))
            ports_ident["open"].append(port)
	
	# RST RECIEVED - PORT CLOSED
	elif (ret == 111):
            if VERBOSE:
                sys.stdout.write("[%s] %s - %d/tcp closed (RST packet)\n" % (date_time(), target, port))
            ports_ident["closed"].append(port)
	
	# ERR CODE 11 - TIMEOUT
	elif (ret == 11):
           ports_ident["filtered"].append(port)
 	            
	else:
            if VERBOSE:
		print port
    except socket.timeout:
	ports_ident["filtered"].append(port)
        
    conn.close() 
Example #29
Source File: mumble.py    From pymumble with GNU General Public License v3.0 5 votes vote down vote up
def connect(self):
        """Connect to the server"""
        
        # Connect the SSL tunnel
        self.Log.debug("connecting to %s on port %i.", self.host, self.port)
        std_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.control_socket = ssl.wrap_socket(std_sock, certfile=self.client_certif, ssl_version=ssl.PROTOCOL_TLSv1)

        self.control_socket.connect((self.host, self.port))
        
        self.control_socket.setblocking(0)
        
        # Perform the Mumble authentication
        version = mumble_pb2.Version()
        version.version = (PYMUMBLE_PROTOCOL_VERSION[0] << 16) + (PYMUMBLE_PROTOCOL_VERSION[1] << 8) + PYMUMBLE_PROTOCOL_VERSION[2]
        version.release = self.application
        version.os = PYMUMBLE_OS_STRING
        version.os_version = PYMUMBLE_OS_VERSION_STRING
        self.Log.debug("sending: version: %s", version)
        self.send_message(PYMUMBLE_MSG_TYPES_VERSION, version)
        
        authenticate = mumble_pb2.Authenticate()
        authenticate.username = self.user
        authenticate.password = self.password
        authenticate.celt_versions.extend(SUPPORTED_BITSTREAMS.keys())
#        authenticate.celt_versions.extend([-2147483637])  # for debugging - only celt 0.7
        authenticate.opus = True
        self.Log.debug("sending: authenticate: %s", authenticate)
        self.send_message(PYMUMBLE_MSG_TYPES_AUTHENTICATE, authenticate)
        
        self.connected = PYMUMBLE_CONN_STATE_AUTHENTICATING 
Example #30
Source File: server.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def run(self):
        """
        Enter the main loop.
        """
        try:
            os.remove(self.address)
        except OSError as err:
            pass

        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.bind(self.address)
        sock.listen(socket.SOMAXCONN)

        self.running = True
        while self.running:
            conn, address = sock.accept()
            try:
                data = conn.recv(MAX_MSG_SIZE)
                request = json.loads(data)
                cmd = request['command']
                if cmd in self.handlers:
                    for callback in self.handlers[cmd]:
                        callback(request)
            except Exception as e:
                print("Caught exception {}".format(e))
                pass
            finally:
                conn.close()

        sock.close()
        os.remove(self.address)