File Server Upload Python - python

File Server Download Problem Python 2.5.1
So i am working on a File Server as a hobby project. I am having some problems though. I can use the client to successfully upload the file to the server but say the file to upload is 50,000 bytes (50 mbs) it will only upload like 49,945 bytes then if i try opening it, it says its corrupt. If i close the server it goes to 50,000 then works. Is there a way to fix this without the server needing to close and reopen?
(Downloading Doesnt Have this Problem)
Full Client Code:
Client
Full Server:
Server
Client Upload Function:
def Uploader(s):
IsReal = True
data = "UploaderReady"
if data == "UploaderReady":
List = []
FilePath = dir_path = os.path.dirname(os.path.realpath(__file__))
List.append(os.listdir(FilePath))
FileUpload = raw_input("Pick a file? -> ")
for Item in List:
if FileUpload == Item:
IsReal = True #checks if item exists
if IsReal == True:
File = open(FileUpload,'rb')
bytestosend = File.read(1024)
FileSize = os.path.getsize(FileUpload)
s.send(FileUpload)
s.send(str(FileSize))
s.send(bytestosend)
while bytestosend != "":
bytestosend = File.read(8192)
s.send(bytestosend)
print"Processing"
File.close()
time.sleep(1.5)
s.send("COMPLETE")
print"File Successfully Uploaded"
time.sleep(2)
print" \n " * 10
Main()
if IsReal == "False":
print"Item doesn't Exist"
time.sleep(2)
print" \n " * 10
s.close()
Main()
Server Upload Function:
Todo = sock.recv(1024)
if Todo == "U":
print str(addr)+" Uploading"
UploadingThread = threading.Thread(target=Uploader,args=(c,c,))
UploadingThread.start()
def Uploader(c,s):
filename = s.recv(1024)
filesize = s.recv(1024)
f = open(filename,'wb')
totalRecv = 0
while totalRecv < filesize:
FileContent = s.recv(8192)
totalRecv += len(FileContent)
f.write(FileContent)
print"Download Complete"
f.close()
s.close()

You close the client connection on the server side, but never close it on the client side as Cory Shay said.
Instead of closing it though, you need to shutdown the socket and signal it is done writing with s.shutdown(socket.SHUT_WR)
Here's how it should look for the client:
def Uploader(s):
IsReal = True
data = "UploaderReady"
if data == "UploaderReady":
List = []
FilePath = dir_path = os.path.dirname(os.path.realpath(__file__))
List.append(os.listdir(FilePath))
FileUpload = raw_input("Pick a file? -> ")
for Item in List:
if FileUpload == Item:
IsReal = True #checks if item exists
if IsReal == True:
File = open(FileUpload,'rb')
bytestosend = File.read(1024)
FileSize = os.path.getsize(FileUpload)
s.send(FileUpload)
s.send(str(FileSize))
s.send(bytestosend)
while bytestosend != "":
bytestosend = File.read(8192)
s.send(bytestosend)
print"Processing"
s.shutdown(socket.SHUT_WR) # End the writing stream
print(s.recv(1024)) # Expecting the server to say 'upload complete'
s.close() # close the socket
File.close()
time.sleep(1.5)
s.send("COMPLETE")
s.close() #To close connection after uploading
print"File Successfully Uploaded"
time.sleep(2)
print" \n " * 10
Main()
and the server:
def Uploader(c,s):
filename = s.recv(1024)
filesize = s.recv(1024)
f = open(filename,'wb')
totalRecv = 0
while totalRecv < filesize:
FileContent = s.recv(8192)
totalRecv += len(FileContent)
f.write(FileContent)
s.send("Upload Complete!") # Tell client the upload is complete
print"Download Complete"
f.close()
s.close() # Close the socket
Also, you are passing the server Uploader 2 identical arguments, and only using one, instead you should just pass one:
UploadingThread = threading.Thread(target=Uploader,args=(c,c,))
# should be
UploadingThread = threading.Thread(target=Uploader,args=(c,))
Similarly, your password thread only needs 2:
c, addr = s.accept()
print"Client Connection: <"+str(addr)+">"
PasswordThread = threading.Thread(target=Password,args=(c,addr))
def Password(c,addr):
c.send("WAITINGPASSWORD")
PASSWORD = "123"
password = c.recv(1024)
and your checking password function can be simpler:
def Password(c,addr):
password = "123"
c.send("WAITINGPASSWORD")
attempt = c.recv(1024)[::-1]
if attempt == password:
doStuff()

Related

How to transfer a file through a socket with Tkinter GUI(Python)

I have a client that let user to browse a file and upload to a server. Currently I'm just using command terminal to operate the program. When user type in fup in the terminal , the program will ask for filename and the file will be upload to the server if the filename input by user is valid.
So, what i want now is letting user to browse any file directory from a GUI without typing the filename to upload. I've tried to implement filedialog but it seem like not working, when i browse and upload a file, the server does not received any new file. I stucked with issues almost a week already but still couldn't find any solution, hope someone could help me. Thanks in advance
Client.py
import socket, sys, os
import time, shutil
# socket creating
def sock():
try:
s = socket.socket()
host = input('Enter Target IP :')
port = 9999
s.connect((host, port))
return (host, s)
except:
print("Error: In binding")
sock()
host, s = sock()
# upload file to client
def fup(conn):
try:
filename = input("\nMANO >>Filename? -> ")
if os.path.isfile(filename):
conn.send(str("fup~" + filename).encode("utf-8"))
conn.send(str.encode("EXISTS " + str(os.path.getsize(filename))))
filesize = int(os.path.getsize(filename))
userResponse = conn.recv(1024).decode("utf-8")
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
conn.send(bytesToSend)
totalSend = len(bytesToSend)
while int(totalSend) < int(filesize):
bytesToSend = f.read(1024)
totalSend += len(bytesToSend)
conn.send(bytesToSend)
sys.stdout.write("\r|" + "█" * int((totalSend / float(filesize)) * 50) + "|{0:.2f}".format(
(totalSend / float(filesize)) * 100) + "% ")
sys.stdout.flush()
print("\nUpload Completed!")
else:
print("File Does Not Exist!")
except:
print("Error")
# download file from client
def fdown(conn):
try:
print(os.getcwd())
filename = input("\nMANO >>Filename? -> ")
if filename != 'q':
conn.send(("fdown~" + filename).encode("utf-8"))
data = conn.recv(1024).decode("utf-8")
if data[:6] == 'EXISTS':
filesize = data[6:]
msg = input("File exists, " + str(filesize) + "Bytes, download? (Y/N)? -> ").upper()
if msg == 'Y':
conn.send("OK".encode("utf-8"))
f = open(filename, 'wb')
data = (conn.recv(1024))
totalRecv = len(data)
f.write(data)
while int(totalRecv) < int(filesize):
data = conn.recv(1024)
totalRecv += len(data)
f.write(data)
sys.stdout.write("\r|" + "█" * int((totalRecv / float(filesize)) * 50) + "|{0:.2f}".format(
(totalRecv / float(filesize)) * 100) + "% ")
sys.stdout.flush()
time.sleep(0.01)
print("\nDownload Complete!")
f.close()
else:
print("File Does Not Exist!")
except:
print("Error")
# commands that perform on client
def mano(cip, conn):
while True:
cli = input("MANO >>" + cip + ' >>')
if cli == 'fdown':
fdown(conn)
elif cli == 'fup':
fup(conn)
else:
print("Command not recognized")
mano(host, s)
Server.py
import socket, os, subprocess, shutil, pickle, struct, threading
## gettig the hostname by socket.gethostname() method
hostname = socket.gethostname()
## getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
# Create a Socket ( connect two computers)
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as msg:
create_socket()
# Binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
s.bind((host, port))
s.listen(5)
## printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
print(f"Running Port: {port}")
except socket.error as msg:
bind_socket()
print(bind_socket())
# send file list
def flist(conn):
try:
arr = pickle.dumps(os.listdir())
conn.send(arr)
print(arr)
except:
conn.send(('Error').encode("utf-8"))
# accept file from server
def fdown(filename, conn):
try:
data = conn.recv(1024).decode("utf-8")
if data[:6] == 'EXISTS':
filesize = data[6:]
conn.send("OK".encode("utf-8"))
f = open(filename, 'wb')
data = (conn.recv(1024))
totalRecv = len(data)
f.write(data)
while int(totalRecv) < int(filesize):
data = conn.recv(1024)
totalRecv += len(data)
f.write(data)
f.close()
except:
conn.send(('Error').encode("utf-8"))
# send file
def fup(filename, conn):
if os.path.isfile(filename):
conn.send(str.encode("EXISTS " + str(os.path.getsize(filename))))
filesize = int(os.path.getsize(filename))
userResponse = conn.recv(1024).decode("utf-8")
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
conn.send(bytesToSend)
totalSend = len(bytesToSend)
while int(totalSend) < int(filesize):
bytesToSend = f.read(1024)
totalSend += len(bytesToSend)
conn.send(bytesToSend)
else:
conn.send("ERROR".encode("utf-8"))
# main
def main(s):
while True:
data = (s.recv(1024)).decode("utf-8").split('~')
if data[0] == 'fdown':
fup(data[1], s)
elif data[0] == 'fup':
fdown(data[1], s)
elif data[0] == 'flist':
flist(s)
else:
s.send(".".encode('utf-8'))
def socket_accept():
while True:
conn, address = s.accept()
t = threading.Thread(target=main, args=(conn,))
t.start()
create_socket()
bind_socket()
socket_accept()
Expected output:
since you are using a gui I think you should receive the inputs through the use of an tkinter.Entry widget not through the terminal with input()

How to copy folder from server to client in python

I'm trying to copy the folder from my server to the client the file is at the x directory.want to know how to set the file path in the server.
server side
filename = '/home/Desktop/features'
f = open(filename, 'rb')
while True:
l = f.read(buff_size)
while (l):
self.sock.sendall(l)
# print('Sent ',repr(l))
l = f.read(buff_size)
if not l:
f.close()
self.sock.close()
break
client side
with open('red_fi', 'rb') as f:
print('file opened client ')
time.sleep(3)
a = True
while a:
print('receiving data...')
data = s.recv(buff_size)
# print('data=%s', (data))
if not data:
f.close()
# time.sleep(3)
print('file closed client')
a = False
break
# write data to a file
f.write(data)
# time.sleep(2)
print('Successfully received the file')
print(id_list)
s.close()
I want the features folder to be copied from server to client.

Python File Server, login function not working

I made a python file server a while back and just recently came back to it. It is a very simple program but i wanted to add some more features to it, one of those being to add some security. For this reason i made a hashed login password and put that in a .txt file stored on the server computer. The way the program is supposed to work is every time the client connects to the server they must enter a password. Then the raw_entry is sent through a socket and checked on the server side if it is correct, if is is not then the user has two more tries to enter the password. For some reason this is not working.
The server:
from passlib.hash import pbkdf2_sha256
import socket
import threading
import os
def login():
loop = 1
while loop <= 3:
passwd = sock.recv(1024)
with open('passtor.txt', 'r') as f:
hash = f.read()
if pbkdf2_sha256.verify(passwd, hash):
s.send("Access Granted")
loop = 4
else:
s.send("Verification Failure")
loop += 1
if loop == 3:
sock.close()
def RetrFile(name, sock):
filename = sock.recv(1024)
if os.path.isfile(filename):
sock.send("EXISTS " + str(os.path.getsize(filename)))
userResponse = sock.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
sock.send("ERR ")
sock.close()
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#s.connect(('google.com', 0))
host = s.getsockname()[0]
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print "File Server Initiated"
print("Server Address-> " + host + " <-")
while True:
c, addr = s.accept()
print "Client Connected ip-> " + str(addr) + " <-"
t1 = threading.Thread(target=login, args=("RetrThread", c))
t2 = threading.Thread(target=RetrFile, args=("RetrThread", c))
t1.start()
t2.start()
s.close()
except:
print("Program Error, \nTermination Complete")
The client:
import socket
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host, port))
loop = True
while loop == True:
passwd = raw_input("Admin Password-> ")
s.send(passwd)
answer = s.recv(1024)
if answer == 'Verification Failure':
loop = True
print(answer)
elif answer == 'Access Granted':
loop = False
print(answer)
filename = raw_input("Filename? -> ")
if filename != 'q':
s.send(filename)
data = s.recv(1024)
if data[:6] == 'EXISTS':
filesize = long(data[6:])
message = raw_input("File exists, " + str(filesize) +"Bytes, download? (Y/N)? -> ")
if message == 'Y':
s.send("OK")
f = open('new_'+filename, 'wb')
data = s.recv(1024)
totalRecv = len(data)
f.write(data)
while totalRecv < filesize:
data = s.recv(1024)
totalRecv += len(data)
f.write(data)
print "{0:.2f}".format((totalRecv/float(filesize))*100)+ "% Done"
print "Download Complete!"
f.close()
else:
print "File Does Not Exist!"
s.close()
You are passing two arguments to the login function here:
t1 = threading.Thread(target=login, args=("RetrThread", c))
They are not declared in the function declaration:
def login():
Either remove the args parameter from the call to threading.Thread or add the arguments to the function declaration.

File transferring, File can't be opend after transfer

I am currently working on a file transfer server and ran into
a problem. I am able to transfer the file completly and it works perefect,
But when the client that received the file cannot open it through python.
What I mean is that if I transferr a file, I can see it in the dic of the client the received it, but it cannot open it and I get an:IOError that the file doesn't exist.
The server:
def download_manager(self, sock, ADDR, name):
sock.send('Starting file download: '+name)
# Getting the socket that has the file
# Getting the user ip address
BUFSIZ = 1024
fileSock = socket(AF_INET, SOCK_STREAM)
fileSock.connect(ADDR)
print 'connected;'
# Starting the file request protocol.
tries = "2"
# sending number of retries.
fileSock.send(tries + "," + name)
sock.send(tries)
for i in range(int(tries)):
# Accepting the start message.
data, size = fileSock.recv(BUFSIZ).split(',')
sock.send(size)
size = int(size)
if data == 'Start':
fileSock.send('ok')
# Getting first data from the supplier.
data = fileSock.recv(BUFSIZ)
# Sending the data to the request client.
sock.send(data)
current_size = BUFSIZ
while current_size <= size:
# Getting data from the supplier.
data = fileSock.recv(BUFSIZ)
# The server "sleeps" in order to keep a synchronization between the client and the server.
# The client works slower than the server(It needs to save the file as well.
time.sleep(0.0001)
# Sending the data to the request client.
sock.send(data)
current_size += BUFSIZ
print current_size
# Receive for the request client the end message.
#sock.send(data)
data = sock.recv(1024)
if data == 'ok':
fileSock.send(data)
break
else:
fileSock.send(data)
else:
sock.send("wrong")
fileSock.close()
The sender client, Just the relevant part:
print "connection from:", addr
# From here on, the server works by the File-Transfer RFC.
# Accepting number of retries from the server and the name of the file.
data = clientsock.recv(self.BUFSIZ)
tries, name = data.split(',')
# Opening File.
f = file(name, mode='rb')
if not tries:
clientsock.close()
continue
try:
for i in range(int(tries)):
# Sending the file size.
clientsock.send('Start,'+str(self.file_size(name)))
# Accepting an ok.
ok = clientsock.recv(self.BUFSIZ)
if not ok:
continue
if ok == "ok":
# Sending the file.
clientsock.send(f.read(-1))
# Waiting for confirmation.
ok = clientsock.recv(self.BUFSIZ)
if ok == "ok":
break
else:
continue
f.close()
except IOError as e:
f.close()
print e
# An error has occurred, closing the socket.
#clientsock.send('End,None')
clientsock.close()
The recieve Client:
def get_file(self, name):
"""
This function receives and saves the requested file from the server.
:param name: The name of the file( How it is saved )
:return: None.
"""
name = name.split('.')
tries = int(self.sock.recv(self.BUFSIZ))
progress = 0
for i in range(tries):
f = file(name[0] + '.' + name[1], mode='wb')
final_size = int(self.sock.recv(self.BUFSIZ))
data = self.sock.recv(self.BUFSIZ)
f.write(data)
current_size = self.BUFSIZ
while current_size <= final_size:
progress = (float(current_size)/final_size)
if progress > 0.01:
self.app.progress = progress
data = self.sock.recv(self.BUFSIZ)
f.write(data)
current_size += self.BUFSIZ
f.close()
print "Current: " + str(current_size)
print "real: " + str(self.file_size(name[0] + '.' + name[1]))
print "Wanted: " + str(final_size)
self.app.progress = None
if self.file_size(name[0] + '.' + name[1]) == final_size:
print 'ok'
self.sock.send('ok')
break
else:
print 'Bad'
os.remove(name[0] + '.' + name[1])
self.sock.send('Bad')
continue
Any Help is welcomed!

python socket send files

trying out a new way to send files. The client will be run every 10 mins to ask server to send what's new in last 10 mins. What I have so far work 40% of the time. I can't figure out so far why that is the case.
server main loop:
while 1:
conn, addr = s.accept()
last_ai = get_last_sent_ai()
new_ai = get_new_ai(last_ai)
ai_notes = ''
''' send # of file '''
print "sending length ---------"
conn.sendall('{0}'.format(len(new_ai)))
for ai_file in new_ai:
ai_file = ai_file.rstrip()
if not os.path.isfile(ai_file): continue
f = open(ai_file, 'rb')
ai_notes = f.read()
f.close()
print "sending file infor " + '{0:<10d}:{1:>40s}'.format(len(ai_notes), ai_file)
ready_flag = conn.recv(5)
if ready_flag == "Ready":
conn.sendall(ai_notes)
if len(new_ai) > 0:
update_last_sent(new_ai[-1])
else:
print 'nothing to send'
conn.sendall(' ')
conn.close()
s.close()
Client main loop:
if num_f == 0: sys.exit(0)
while num_f > 0:
f_info = ''
f_info = s.recv(50)
f_len,f_name_tmp = f_info.split(':')
f_len = int(f_len)
s.sendall("Ready")
f_name = f_name_tmp
f = open(f_name, 'wb')
recvd = 0
while recvd < f_len:
chunk = s.recv(min(f_len - recvd, 1024))
if chunk == '':
raise RuntimeError("socket connection broken")
f.write(chunk)
recvd = recvd + len(chunk)
f.close()
num_f -= 1
s.close()
update:
the issue seems to be gone after I went back and changed how the send and receive are done. There gotta be some kind of blocking going on when it hangs, so I followed the python doc and modified the code and all the tests so far are working.

Categories