def sendFile(fileName): print("sending " + fileName + " file") dataToSend = "fileName=" + fileName framedSend(s, dataToSend.encode(), debug) f = open(fileName, "rb").read() framedSend(s, f, debug) print("received:", framedReceive(s, debug).decode())
def get(f): s.send(b'GETS') check = True while check: #f = input("Enter filename to get from server\n") if os.path.isfile(f): print("This file already exists in directory") else: check = False txtfile = f.encode('utf-8') framedSend(s, txtfile, debug) txtfile = f with open("copy " + txtfile, 'wb') as r: while True: input = s.recv(100) if input == b'LETSGO': continue #lets begin reading file elif input == b'TDBABY': print("Done writing") break elif input == b'WRONG': #wrong and tdbaby serve the similar purposes, but are different print("File does not exist exiting") break else: r.write(input) r.close() print("All done") s.close()
def send_message(): while True: user_input = input("Enter Message\n> ") if re.match("put\s[\w\W]+", user_input): trash, file = user_input.split(" ", 1) if os.path.exists("%s/%s" % (os.getcwd(), file)): msg = "put " + file.rsplit('/', 1)[-1] framedSend(s, msg.encode()) framedSend(s, open(file, "rb").read(), 1) else: print("File Doesn't Exist.") elif re.match("get\s[\w\W]+", user_input): framedSend(s, user_input.encode()) payload = framedReceive(s) if payload.decode() == "true": trash, file = user_input.split(" ", 1) writer = open("%s/%s" % (os.getcwd(), file), "wb+") payload = framedReceive(s) writer.write(payload) writer.close() print("Transfer Done.") else: print("File not Found.") elif user_input == "quit": print("Killing Server...") framedSend(s, "quit".encode()) print("Response:", framedReceive(s)) sys.exit(0) else: framedSend(s, user_input.encode()) print("Response:", framedReceive(s))
def sendFile(fileName,socket): framedSend(socket, b'OK:' + str(os.path.getsize(fileName)).encode(), debug) with open(fileName, 'rb') as file: data = file.read(100) while data != b"": framedSend(socket, data, debug) data = file.read(100)
def receive(): take = framedReceive(sock, debug) print(take) f = take.decode('utf-8') if os.path.isfile(f): print("This file already exists in directory") sock.send(b'wrrong') sys.exit(0) else: framedSend(sock, b'begin', debug) #txtfile = f.encode('utf-8') #framedSend(sock, txtfile, debug) txtfile = f with open("copy " + txtfile, 'wb') as r: while True: a = sock.recv(100) if a == b'LETSGO': continue #lets begin reading file elif a == b'TDBABY': print("Done writing") break elif a == b'WRONG': #wrong and tdbaby serve the similar purposes, but are different print("File does not exist exiting") break else: # print(a.decode('utf-8')) r.write(a) r.close() print("All done") sock.close()
def client(): switchesVarDefaults = ( # Default switches. (('1', '--server'), 'server', "127.0.0.1:50001"), (('?', '--usage'), 'usage', False), (('d', '--debug'), 'debug', False), ) parameterMap = params.parseParams(switchesVarDefaults) server, usage, debug = parameterMap['server'], parameterMap[ 'usage'], parameterMap['debug'] if usage: params.usage() # Calls method from given file params. try: serverHost, serverPort = re.split(":", server) serverPort = int(serverPort) except: print("Can't parse server:port from '%s'" % server) # Server could not be found. sys.exit(1) port = (serverHost, serverPort) # create socket listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listenSocket.connect(port) while True: fileName = input("> ") fileName.strip() if fileName == "exit": #Exit program if file name matches condition. sys.exit(0) else: if not fileName: continue elif os.path.exists(PATH + fileName): f = open(PATH + fileName, "rb") contents = f.read() if len(contents) <= 0: # Error if the file is empty. print("Error: File %s is empty" % fileName) continue framedSend(listenSocket, fileName, contents, debug) # Checks if server received the file. status = int(listenSocket.recv(1024).decode()) if status: print("File %s received by server." % fileName) sys.exit(0) else: # File not received and exit with error. print( "File Transfer Error: File %s was not received by server." % fileName) sys.exit(1) else: # File was not found. Repeat loop. print("File Not Found Error: File %s not found!" % fileName)
def puts(c): s.send(b'PUTS') #f = input("Enter file to put in server") txtfile = c[1].encode('utf-8') framedSend(s, txtfile, debug) message = framedReceive(s, debug) if message == b'begin': getruns = open(c[1], "rb") #open file for reading bytes s.send(b'LETSGO') #Lets drive this file to the end zone.. football references while True: run = getruns.read(100) s.send(run) print("sent ") #sent 100 bytes if not run: print("Done") #s.shutdown(socket.SHUT_WR) #s.send(b'TDBABY') break s.send(b'TDBABY') #Touchdown you're done getruns.close() s.close() else: print("File already exists in server") s.close()
def fileClient(): switchesVarDefaults = ( (('1', '--server'), 'server', "127.0.0.1:50001"), (('?', '--usage'), 'usage', False), (('d', '--debug'), 'debug', False), ) # based on demos parameterMap = params.parseParams(switchesVarDefaults) server, usage, debug = parameterMap['server'], parameterMap['usage'], parameterMap['debug'] if usage: params.usage() try: serverHost, serverPort = re.split(":", server) serverPort = int(serverPort) except: print("Can't parse server:port from '%s'" % server) sys.exit(1) port = (serverHost, serverPort) # create socket listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listenSocket.connect(port) while 1: fileName = input("Enter a filename > ") fileName.strip() if fileName == "exit": # terminate sys.exit(0) else: if not fileName: continue elif os.path.exists(PATH + fileName): f = open(PATH + fileName, "rb") # read and binary contents = f.read() if len(contents) < 1: print("Error: File %s is empty" % fileName) continue framedSend(listenSocket, fileName, contents, debug) # check if server was able to receive the file status = int(listenSocket.recv(1024).decode()) if status: print("File %s received by server." % fileName) sys.exit(0) else: print("File Transfer Error: File %s was not received by server." % fileName) sys.exit(1) else: print("File Not Found Error: File %s not found!" % fileName)
def run(self): print(threadNum) global sLock sLock.acquire() checkRecv = framedReceive(sock, debug) # Check the first thing the server sends! if checkRecv == b"ERROR": # Client sent an error message - stop! print("Something went wrong client-side. No files recieved.") sock.close() sys.exit(0) if checkRecv == b"exit": # Check for server terminate command. NON-FUNCTIONAL. print("Client terminated server. Shutting down...") sock.close() sys.exit(0) while checkRecv != b'': fileName = checkRecv.decode("utf-8") # Pull out the file name! checkRecv = framedReceive(sock, debug) filePath = os.getcwd() + "/server/" + fileName # Get path; server uploads fle to server folder. if os.path.isfile(filePath): # Don't let user overwrite files already on the server. print("ERROR: File already exists. %s not recieved." % fileName) framedSend(sock, b"exists", debug) sock.close() sys.exit(0) else: framedSend(sock,b"accept", debug) # Tell client that everything is fine! data = framedReceive(sock,debug) # Check out the data client sent. isZeroLen = False if (data == b"ERROR"): # Client sent an error - stop! print("ERROR: Something went wrong client-side. File not recieved.") sock.close() sys.exit(0) if data is None: # Check if file is zero length, and handle. print("WARNING: Zero-length file.") with open(filePath, 'w') as myFile: myFile.write("") isZeroLen = True if not isZeroLen: with open(filePath, 'wb') as myFile: # Otherwise, open a file to copy payload to. while True: myFile.write(data) # Read the data sent by the client and copy to the file. data = framedReceive(sock, debug) if not data: # When there's nothing more, stop taking payload. sys.exit(0) myFile.close() print("%s received. Exiting..." % fileName) sock.close() print("Closed connection", addr) sLock.release()
def send(name, size, info): sock = serverConnect(info) buff = int(size) framedSend(sock, name.encode(), False) with open(name, "rb") as f: payload = f.read(buff) framedSend(sock, payload, False) f.close() return framedReceive(sock, False)
def send_file(fname, s, folder, debug): ''' Read file in chunks and use framedSend to send to server. ''' with open(folder + '/' + fname, 'r') as f: chunk = f.read(100) while chunk: if debug: print("Next chunk:\n%s\n" % chunk) framedSend(s, chunk.encode(), debug) # print("waiting for ack of framed send") # print(framedReceive(s, debug)) # wait for ack? chunk = f.read(100)
def fileWrite(name, data, sock): name = "(Server)" + name if os.path.isfile(name): framedSend(sock, b"File already in server.", False) return try: with open(name, "wb") as f: f.write(data) f.close() framedSend(sock, b"File Transfered.", False) except Exception as e: print(f"[+] Error: {e}")
def sendFile(sock, source, destination, debug, proxy): # Sends file based on source, destination and proxy if not os.path.exists(source): print('File %s does not exist' % source) return f = open(source) for line in f: payload = "{}:{}".format(destination, line).encode() framedSend(sock, payload, debug) callback = framedReceive(sock, debug) f.close() framedSend(sock, b'', debug) # Letting server know file transfered completely print(framedReceive(sock, debug).decode())
def fileClient(): switchesVarDefaults = ( (('1', '--server'), 'server', "127.0.0.1:50001"), (('?', '--usage'), 'usage', False), (('d', '--debug'), 'debug', False), ) paramMap = params.parseParams(switchesVarDefaults) server, usage, debug = paramMap['server'], paramMap['usage'], paramMap['debug'] if usage: params.usage() try: serverHost, serverPort = re.split(":", server) serverPort = int(serverPort) except: print("Can't parse server:port from '%s'" % server) sys.exit(1) port = (serverHost, serverPort) listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # create socket listenSocket.connect(port) while 50001: fileName = input("> ") fileName.strip() if fileName == "exit": sys.exit(0) # exit loop else: if not fileName: continue elif os.path.exists(PATH + fileName): f = open(PATH + fileName, "rb") data = f.read() # read if len(data) < 1: print("File %s is blank" % fileName) continue framedSend(listenSocket, data, debug) statusNumber = int(listenSocket.recv(1024).decode()) # checks if server received the file if not statusNumber: print("File %s was not received by server." % fileName) sys.exit(1) else: print("File %s was received by server." % fileName) sys.exit(0) else: print("File %s not found" % fileName) # repeat loop if file does not exist
def client(): switchesVarDefaults = ( (('-s', '--server'), 'server', "127.0.0.1:50001"), (('-d', '--debug'), "debug", False), # boolean (set if present) (('-?', '--usage'), "usage", False), # boolean (set if present) ) paramMap = params.parseParams(switchesVarDefaults) server, usage, debug = paramMap["server"], paramMap["usage"], paramMap[ "debug"] if usage: params.usage() try: serverHost, serverPort = re.split(":", server) serverPort = int(serverPort) except: print("Can't parse server:port from '%s'" % server) sys.exit(1) # create socket object with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((serverHost, serverPort)) while True: fileName = input("Enter the file name: ") fileName.strip() if fileName == "exit": sys.exit(0) else: if not fileName: continue elif os.path.exists(FILE_PATH + fileName): file = open(FILE_PATH + fileName, "rb") fileContent = file.read() if len(fileContent) <= 0: print("File is empty") continue framedSend(s, fileName, fileContent, debug) if int(s.recv( 1024).decode()): # if the server received the file print("File %s has been received" % fileName) sys.exit(0) else: print("File %s was not received" % fileName) sys.exit(1) else: print("File %s not found" % fileName)
def recv_file_name(): ''' Get file name from client and check if exists.''' global folder payload = framedReceive(sock, debug) fname = folder + '/' + payload.decode() if os.path.exists(fname): framedSend(sock, b"file already exists") print("file already exists, terminating") exit() else: framedSend(sock, b"OK") return payload.decode() return None
def writeToFile(filename, data): # create te folder from received files mkdir('./Received/') currentdir = os.getcwd() + "/" dir = os.getcwd() + "/Received/" fileExists = os.path.isfile(dir + filename) #checks if the text file exists if fileExists: print("file exists") framedSend(sock, b'file already exist!', debug) else: # create a new file file = open(dir + filename, "wb+") # open for [w]riting as [b]inary # print(data,"data..........") file.write(data) file.close()
def cmd(): command=input(">>$ ") while(command !="q"): if ("put" in command): fileData= command.split(" ") fileName= fileData[1] data=readFile(fileName) size=getFileSize(fileName) print("encoding file...") name = bytearray(fileName+"/n", 'utf-8') framedSend(s, name, debug) framedSend(s, data, debug) print("message from server:", framedReceive(s, debug)) command=input(">>$ ")
def run(self): """ First get file name. Check if exists, if not get the rest of the file contents. """ if DEBUG: time.sleep(5) print("New thread handling connection from", self.addr) file_name = framedReceive(self.sock, debug=DEBUG) if not file_name: framedSend(self.sock, "File name not found".encode(), debug=DEBUG) return file_name = "results/" + file_name.decode() # lock thread, to begin writing file. thread_lock.acquire() if not os.path.exists(file_name) and file_name not in active_files: file = open(file_name, "w+b") active_files.add(file_name) else: framedSend(self.sock, "File already found!".encode(), debug=DEBUG) # Do nothing. return thread_lock.release() message = framedReceive(self.sock, debug=DEBUG) if not message: framedSend(self.sock, "Had trouble with contents of file".encode(), debug=DEBUG) return # Finish file operation. file.write(message) file.close() # Remove from active_files thread_lock.acquire() active_files.remove(file_name) thread_lock.release() print("File closed. Success!") framedSend(self.sock, "Success".encode(), debug=DEBUG)
def run(self): self.current_file_name = file_name(self.sock) if file_log.get(self.current_file_name) == True: print("\nSend back to client that file is in being accessed.\n") print("\n--------------------------------------------------------------\n") example = b'File in use.' framedSend(self.sock,example,debug) else: example = b'File not in use.' framedSend(self.sock,example,debug) lock_thread.acquire() file_log[self.current_file_name] = True lock_thread.release() write_to_file(self.current_file_name, self.sock) #print("\nupdating log") lock_thread.acquire() file_log[self.current_file_name] = False lock_thread.release()
def sendFile(socket, source, destination): try: fileSend = open(source, "r") except: print("Could not open source file") sys.exit(1) framedSend(socket, destination.encode()) for line in fileSend: framedSend(socket, line.encode()) framedSend(socket, b'DoneSending')
def send_file(s_conn): file_name_start = b'title_start' # start of file name flag file_name_end = b'title_end' # end of file name flag framedSend(s_conn, file_name_start, debug) # send the name of how the file will be save on the server framedSend(s_conn, server_file_name.encode(), debug) framedSend(s_conn, file_name_end, debug) with open(input_file, 'rb') as file: t_file_data = file.read(100) # only 100 bytes becasue of framedSock if not t_file_data: print("Finished sending bytes") else: while t_file_data: framedSend(s_conn, t_file_data, debug) t_file_data = file.read( 100) # only 100 bytes becasue of framedSock print("File has been sent") s_conn.close()
def sendFile(filename): # except file not found try: # open file f = open(filename, "r") except: print("Not an available file, try again.\n") return # first send filename <filepath> to let know user about file line = 'filename' + filename framedSend(s, line.encode('UTF-8'), debug) # read contents of file contents = f.read() # send contents to server framedSend(s, contents.encode('UTF-8'), debug) # let know server that file transfer is over framedSend(s, b"ending file transfer", debug)
print("listening on:", bindAddr) from framedSock import framedSend, framedReceive while True: sock, addr = lsock.accept() print("connection rc'd from", addr) if not os.fork(): while True: payload = framedReceive(sock, debug) if not payload: break payload = payload.decode() if exists(payload): framedSend(sock, b"True", debug) else: framedSend(sock, b"False", debug) try: payload2 = framedReceive(sock, debug) except: print("connection lost while receiving, exiting") sys.exit(0) if not payload2: break payload2 += b"!" try: framedSend(sock, payload2, debug) except: print("connection lost while sending, exiting") output = open(payload, 'wb')
addrPort = (serverHost, serverPort) s = socket.socket(addrFamily, socktype) if s is None: print('could not open socket') sys.exit(1) s.connect(addrPort) file_to_send = input("type file to send : ") def utf8len(s): return len(s.encode('utf-8')) if exists(file_to_send): print("hello") file_copy = open(file_to_send, 'r') #open file file_data = file_copy.read() #save contents of file #print(file_data) if utf8len(file_data) == 0: sys.exit(0) else: framedSend(s, file_data.encode(), debug) print("received:", framedReceive(s, debug)) else: sys.exit(0)
#check for zero length files if len(fileContents) == 0: print('error zero length file') sys.exit(0) else: #splitting the file name by the period and adding enumeration to the end splitFileName = transferFile.split('.') copiedFileEnumeration = '_copy.' fileNameForCopy = splitFileName[ 0] + copiedFileEnumeration + splitFileName[1] fileNameForCopy = fileNameForCopy.strip() #send file name to server to check if already on server framedSend(s, fileNameForCopy.encode(), debug) #response from server fileAlreadyOnServer = framedReceive(s, debug) #decode response fileAlreadyOnServer = fileAlreadyOnServer.decode() #if file is already on server exit if fileAlreadyOnServer == 'True': print('File is already on server!') sys.exit(0) #file is not on server, continue else: try: #send file
for res in socket.getaddrinfo(serverHost, serverPort, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: print("creating sock: af=%d, type=%d, proto=%d" % (af, socktype, proto)) s = socket.socket(af, socktype, proto) except socket.error as msg: print(" error: %s" % msg) s = None continue try: print("attempting to connect to %s" % repr(sa)) s.connect(sa) except socket.error as msg: print(" error: %s" % msg) s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) text = readFile() #Get information to send framedSend(s, text.encode(), debug) framedReceive( s, debug ) #Doesn't use the output,just want to make sure the file is completely sent before the filecloses
def client(): switchesVarDefaults = ( (('-s', '--server'), 'server', "127.0.0.1:50001"), (('-d', '--debug'), "debug", False), # boolean (set if present) (('-?', '--usage'), "usage", False), # boolean (set if present) ) paramMap = params.parseParams(switchesVarDefaults) server, usage, debug = paramMap["server"], paramMap["usage"], paramMap[ "debug"] if usage: params.usage() try: serverHost, serverPort = re.split(":", server) serverPort = int(serverPort) except: print("can't parse server:port from '%s'" % server) sys.exit(1) addr_port = (serverHost, serverPort) # create socket object listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.connect(addr_port) while True: filename = input("Enter the file to be sent: ") filename.strip() if filename == "exit": sys.exit(0) else: if not filename: continue elif os.path.exists(PATH_FILES + filename): # open file and read file = open(PATH_FILES + filename, "rb") file_content = file.read() # verify file is not empty if len(file_content) < 1: print("ERROR: file %s is empty" % filename) continue # send file contents to server framedSend(listen_socket, filename, file_content, debug) # check if server received file status = int(listen_socket.recv(1024).decode()) # successful transfer if status: print(CONFIRM_MSG % filename) sys.exit(0) # failed transfer else: print(REJECT_MSG % filename) sys.exit(1) # file not found else: print("ERROR: file %s not found" % filename)
except: print("Can't parse server:port from '%s'" % server) sys.exit(1) addrFamily = socket.AF_INET socktype = socket.SOCK_STREAM addrPort = (serverHost, serverPort) s = socket.socket(addrFamily, socktype) if s is None: print('could not open socket') sys.exit(1) s.connect(addrPort) while True: filename = input("File name: ") try: fileOpen = open(filename, "rb") break except FileNotFoundError: print("File not found") fileData = fileOpen.read() if len(fileData) == 0: print("File not sent, empty file") sys.exit(1) else: print("Sending file") framedSend(s, fileData, debug)
(('-?', '--usage'), "usage", False), # boolean (set if present) ) progname = "echoserver" paramMap = params.parseParams(switchesVarDefaults) debug, listenPort = paramMap['debug'], paramMap['listenPort'] if paramMap['usage']: params.usage() lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # listener socket bindAddr = ("127.0.0.1", listenPort) lsock.bind(bindAddr) lsock.listen(5) print("listening on:", bindAddr) sock, addr = lsock.accept() print("connection rec'd from", addr) from framedSock import framedSend, framedReceive while True: payload = framedReceive(sock, debug) if debug: print("rec'd: ", payload) if not payload: break payload += b"!" # make emphatic! framedSend(sock, payload, debug)