Advertisement
TrashRat

Local GUI File transfer SERVER/CLIENT

Feb 23rd, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.96 KB | None | 0 0
  1. -----SERVER-----
  2. """
  3. Local Area Network FTP Server, hamfisted by none other than your humble and gracious overlord, REED. Some things are definitely redundant, but it runs god damnit.
  4. 2/08/18
  5. VERSION: 1
  6. """
  7.  
  8. import socket  # for networking
  9. import threading  # for synchronous execution of functions
  10. import os  # for gathering filenames/directories
  11. import base64  # for encoding/decoding data sent across the network
  12. import math  # for calculations in convertSie function
  13.  
  14. global allFiles
  15. global printThis
  16. allFiles = os.listdir()
  17. hasRan = False
  18.  
  19.  
  20. def infoFunc(sock):
  21.     if hasRan == False:
  22.         def convertSize(size_bytes):
  23.             if size_bytes == 0:
  24.                 return "0B"
  25.             size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  26.             i = int(math.floor(math.log(size_bytes, 1024)))
  27.             p = math.pow(1024, i)
  28.             x = round(size_bytes / p, 2)
  29.             return "%s %s" % (x, size_name[i])
  30.  
  31.         allFiles = os.listdir()  # gathers all files in root directory
  32.         finalList = []
  33.         for file in allFiles:
  34.             theSize = os.path.getsize(file)
  35.             theConvertedSize = convertSize(theSize)
  36.             final = file + "..." + theConvertedSize + "ZZ" + str(theSize)  # used to be theConvertedSize
  37.             finalList.append(final)
  38.  
  39.         printThis = "\n".join(finalList)
  40.         print("sending NAMES")
  41.         sock.send(str.encode("NAMES ") + str(printThis).encode())
  42.  
  43.  
  44. def RetrFile(name, sock):
  45.     print("Waiting for file request")
  46.     name = name
  47.     sock = sock
  48.     hasRan = True
  49.     filename = ""
  50.     filename = sock.recv(1024)
  51.     filename = filename.decode()
  52.     print("Request for " + filename)
  53.  
  54.     if os.path.isfile(filename):
  55.         sock.send(str.encode("EXISTS") + str(os.path.getsize(filename)).encode())
  56.         print("sent exists, waiting for response")
  57.         userResponse = sock.recv(1024)
  58.         userResponse = userResponse.decode()
  59.         print("recieved client response")
  60.         if userResponse[:2] == 'OK':
  61.             print("Sending " + filename)
  62.             with open(filename, 'rb') as f:
  63.                 print("first byte")
  64.                 bytesToSend = f.read(8192)
  65.                 sock.sendall(bytesToSend)
  66.                 byteCounter = 0
  67.                 while str(bytesToSend) != "b''":
  68.                     byteCounter += 1
  69.                     print("Sending byte No." + str(byteCounter))
  70.                     bytesToSend = f.read(8192)
  71.                     sock.sendall(bytesToSend)
  72.  
  73.                 print(filename + " successfully transfered to client")
  74.                 #
  75.         global allFiles
  76.         RetrFile(name, sock)  # NEW LINE
  77.         if userResponse in allFiles:
  78.             print("Client denied transfer of " + str(filename) + ", reconnecting...")
  79.  
  80.             RetrFile(name, sock)
  81.     else:
  82.         print("Client disconnected...")
  83.         sock.send(str.encode("ERR "))
  84.         sock.close()
  85.  
  86.  
  87. def Main():
  88.     host = '192.168.42.146'
  89.     port = 5000
  90.     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  91.     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  92.     s.bind((host, port))
  93.     s.listen(5)
  94.     print("Server IP: %s\nServer Port: %s" % (host, port))
  95.  
  96.     while True:
  97.         c, addr = s.accept()
  98.         print("client connected with IP and Port:<" + str(addr) + ">")
  99.         infoFunc(c)
  100.         t = threading.Thread(target=RetrFile, args=("RetrThread", c))
  101.         t.start()
  102.  
  103.     s.close()
  104.  
  105.  
  106. if __name__ == '__main__':
  107.     Main()
  108.  
  109. -----CLIENT-----
  110. """
  111. Local area network FTP client. Hamfisted by your humble and glorious overlord, REED. GUI generated by PAGE ver. 4.9
  112. 2/08/18
  113. VERSION: 2
  114. """
  115. import threading  # for use in download/progressbar function
  116. import socket  # for networking
  117. import base64  # for encoding/decoding data sent across the network
  118. import sys  # imported by PAGE for use in GUI
  119. import tkinter as tk  # shit man idk
  120. import math  # do i even use math?
  121.  
  122. try:
  123.     from Tkinter import *
  124. except ImportError:
  125.     from tkinter import *
  126.  
  127. try:
  128.     import ttk
  129.  
  130.     py3 = 0
  131. except ImportError:
  132.     import tkinter.ttk as ttk
  133.  
  134.     py3 = 1
  135.  
  136.  
  137. def vp_start_gui():
  138.     '''Starting point when module is the main routine.'''
  139.     global val, w, root
  140.     root = Tk()
  141.     top = New_Toplevel_1(root)
  142.     root.mainloop()
  143.  
  144.  
  145. w = None
  146.  
  147.  
  148. def create_New_Toplevel_1(root, *args, **kwargs):
  149.     '''Starting point when module is imported by another program.'''
  150.     global w, w_win, rt
  151.     rt = root
  152.     w = Toplevel(root)
  153.     top = New_Toplevel_1(w)
  154.     return (w, top)
  155.  
  156.  
  157. def destroy_New_Toplevel_1():
  158.     global w
  159.     w.destroy()
  160.     w = None
  161.  
  162.  
  163. class New_Toplevel_1:
  164.     downloadComp = True
  165.     global host
  166.     global port
  167.     global s
  168.     host = "192.168.42.146"
  169.     port = 5000
  170.     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  171.  
  172.     def __init__(self, top=None):
  173.  
  174.         s.connect((host, port))
  175.         info = s.recv(15360)
  176.         info = info.decode()
  177.         if info[:5] == "NAMES":
  178.             info = info[6:].split("\n")
  179.  
  180.         def onSelect(event):
  181.             try:
  182.                 s.connect(host, port)
  183.             except:
  184.                 listVal = int(event.widget.curselection()[0])
  185.                 filename = info[listVal]  # FILENAME
  186.                 self.head, self.sep, self.tail = filename.partition(
  187.                     "...")  # seperates filename from filesize, only head and tail are used
  188.                 self.finTail = self.tail.split("ZZ")[0]  # converted filesize
  189.                 self.rawTail = self.tail.split("ZZ")[1]  # raw filesize
  190.                 self.Label1.configure(font=("Terminal", 23), text=self.finTail)
  191.  
  192.         '''This class configures and populates the toplevel window.
  193.           top is the toplevel containing window.'''
  194.         _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
  195.         _fgcolor = '#000000'  # X11 color: 'black'
  196.         _compcolor = '#d9d9d9'  # X11 color: 'gray85'
  197.         _ana1color = '#d9d9d9'  # X11 color: 'gray85'
  198.         _ana2color = '#d9d9d9'  # X11 color: 'gray85'
  199.         self.style = ttk.Style()
  200.         if sys.platform == "win32":
  201.             self.style.theme_use('winnative')
  202.         self.style.configure('.', background=_bgcolor)
  203.         self.style.configure('.', foreground=_fgcolor)
  204.         self.style.configure('.', font="TkDefaultFont")
  205.         self.style.map('.', background=
  206.         [('selected', _compcolor), ('active', _ana2color)])
  207.  
  208.         top.geometry("466x286+650+150")
  209.         top.title("Just Send It!")
  210.         top.configure(background="#d9d9d9")
  211.         top.configure(height="354")
  212.         top.configure(highlightbackground="#d9d9d9")
  213.         top.configure(highlightcolor="black")
  214.         top.configure(width="493")
  215.  
  216.         self.Scrolledlistbox2 = ScrolledListBox(top)
  217.         self.Scrolledlistbox2.place(relx=0.0, rely=0.0, relheight=1.0
  218.                                     , relwidth=0.47)
  219.         self.Scrolledlistbox2.configure(background="white")
  220.         self.Scrolledlistbox2.configure(disabledforeground="#a3a3a3")
  221.         self.Scrolledlistbox2.configure(font="TkFixedFont")
  222.         self.Scrolledlistbox2.configure(foreground="black")
  223.         self.Scrolledlistbox2.configure(highlightbackground="#d9d9d9")
  224.         self.Scrolledlistbox2.configure(highlightcolor="#d9d9d9")
  225.         self.Scrolledlistbox2.configure(selectbackground="#c4c4c4")
  226.         self.Scrolledlistbox2.configure(selectforeground="black")
  227.         self.Scrolledlistbox2.configure(width=10)
  228.  
  229.         filenames = []
  230.         filesizes = []
  231.         for entry in info:
  232.             self.ehead, self.esep, self.etail = entry.partition("...")
  233.             self.Scrolledlistbox2.insert(tk.END, self.ehead)
  234.             filenames.append(self.ehead)
  235.             filesizes.append(self.etail)
  236.         self.Scrolledlistbox2.bind("<<ListboxSelect>>", onSelect)
  237.  
  238.         self.TProgressbar1 = ttk.Progressbar(top)
  239.         self.TProgressbar1.place(relx=0.49, rely=0.90, relwidth=0.49
  240.                                  , relheight=0.0, height=22)
  241.  
  242.         self.Label1 = Label(top)
  243.         self.Label1.place(relx=0.49, rely=0.1, height=100, width=224)
  244.         self.Label1.configure(activebackground="#f9f9f9")
  245.         self.Label1.configure(activeforeground="black")
  246.         self.Label1.configure(background="#d9d9d9")
  247.         self.Label1.configure(disabledforeground="#a3a3a3")
  248.         self.Label1.configure(foreground="#000000")
  249.         self.Label1.configure(highlightbackground="#d9d9d9")
  250.         self.Label1.configure(highlightcolor="black")
  251.         self.Label1.configure(font=("Terminal", 23), text='''send
  252. nudes''')
  253.  
  254.         self.TButton1 = ttk.Button(top, text='''Download''', command=self.threadStarter)
  255.         self.TButton1.place(relx=0.6, rely=0.52, height=55, width=126)
  256.         self.TButton1.configure(takefocus="")
  257.  
  258.     def downloadFile(self, event=None):
  259.         self.TProgressbar1['maximum'] = int(self.rawTail)
  260.         pval = 0
  261.         s.send(self.head.encode())
  262.         self.data = s.recv(1024)
  263.         self.data = self.data.decode()
  264.         if self.data[:6] == "EXISTS":
  265.             self.fileSize = int(self.data[6:])
  266.             s.send(str.encode("OK"))
  267.             self.f = open('new_' + self.head, 'wb')
  268.             self.TButton1.configure(state=DISABLED)
  269.             self.data = s.recv(8192)
  270.             pval = pval + len(self.data)
  271.             self.TProgressbar1['value'] = pval
  272.             self.TProgressbar1.update_idletasks()
  273.             self.totalRecv = len(self.data)
  274.             self.f.write(self.data)
  275.             while self.totalRecv < self.fileSize:
  276.                 self.data = s.recv(8192)
  277.                 pval = pval + len(self.data)
  278.                 self.TProgressbar1['value'] = pval
  279.                 self.TProgressbar1.update_idletasks()
  280.                 self.totalRecv += len(self.data)
  281.                 self.f.write(self.data)
  282.                 # print( format((self.totalRecv/float(self.fileSize))*100, '0.2f') + "%")
  283.             self.TProgressbar1['maximum'] = 0
  284.             self.TProgressbar1['value'] = 0
  285.             self.TProgressbar1.update_idletasks()
  286.             self.TButton1.configure(state=NORMAL)
  287.             self.f.close()
  288.  
  289.     def threadStarter(self):  # starts the downloadFile thread when download button is pressed.
  290.         t = threading.Thread(target=self.downloadFile)
  291.         t.start()
  292.  
  293.  
  294. # The following code is added to facilitate the Scrolled widgets you specified.
  295. class AutoScroll(object):
  296.     '''Configure the scrollbars for a widget.'''
  297.  
  298.     def __init__(self, master):
  299.         #  Rozen. Added the try-except clauses so that this class
  300.         #  could be used for scrolled entry widget for which vertical
  301.         #  scrolling is not supported. 5/7/14.
  302.         try:
  303.             vsb = ttk.Scrollbar(master, orient='vertical', command=self.yview)
  304.         except:
  305.             pass
  306.         hsb = ttk.Scrollbar(master, orient='horizontal', command=self.xview)
  307.  
  308.         # self.configure(yscrollcommand=_autoscroll(vsb),
  309.         #    xscrollcommand=_autoscroll(hsb))
  310.         try:
  311.             self.configure(yscrollcommand=self._autoscroll(vsb))
  312.         except:
  313.             pass
  314.         self.configure(xscrollcommand=self._autoscroll(hsb))
  315.  
  316.         self.grid(column=0, row=0, sticky='nsew')
  317.         try:
  318.             vsb.grid(column=1, row=0, sticky='ns')
  319.         except:
  320.             pass
  321.         hsb.grid(column=0, row=1, sticky='ew')
  322.  
  323.         master.grid_columnconfigure(0, weight=1)
  324.         master.grid_rowconfigure(0, weight=1)
  325.  
  326.         # Copy geometry methods of master  (taken from ScrolledText.py)
  327.         if py3:
  328.             methods = Pack.__dict__.keys() | Grid.__dict__.keys() \
  329.                       | Place.__dict__.keys()
  330.         else:
  331.             methods = Pack.__dict__.keys() + Grid.__dict__.keys() \
  332.                       + Place.__dict__.keys()
  333.  
  334.         for meth in methods:
  335.             if meth[0] != '_' and meth not in ('config', 'configure'):
  336.                 setattr(self, meth, getattr(master, meth))
  337.  
  338.     @staticmethod
  339.     def _autoscroll(sbar):
  340.         '''Hide and show scrollbar as needed.'''
  341.  
  342.         def wrapped(first, last):
  343.             first, last = float(first), float(last)
  344.             if first <= 0 and last >= 1:
  345.                 sbar.grid_remove()
  346.             else:
  347.                 sbar.grid()
  348.             sbar.set(first, last)
  349.  
  350.         return wrapped
  351.  
  352.     def __str__(self):
  353.         return str(self.master)
  354.  
  355.  
  356. def _create_container(func):
  357.     '''Creates a ttk Frame with a given master, and use this new frame to
  358.    place the scrollbars and the widget.'''
  359.  
  360.     def wrapped(cls, master, **kw):
  361.         container = ttk.Frame(master)
  362.         return func(cls, container, **kw)
  363.  
  364.     return wrapped
  365.  
  366.  
  367. class ScrolledListBox(AutoScroll, Listbox):
  368.     '''A standard Tkinter Text widget with scrollbars that will
  369.    automatically show/hide as needed.'''
  370.  
  371.     @_create_container
  372.     def __init__(self, master, **kw):
  373.         Listbox.__init__(self, master, **kw)
  374.         AutoScroll.__init__(self, master)
  375.  
  376.  
  377. if __name__ == '__main__':
  378.     vp_start_gui()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement