Advertisement
Guest User

לרני הגזר

a guest
Apr 26th, 2018
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.32 KB | None | 0 0
  1. #   Heights sockets Ex. 2.7 template - server side
  2. #   Author: Barak Gonen, 2017
  3.  
  4. import socket
  5. from PIL import ImageGrab
  6. import glob
  7. import os
  8. import shutil
  9. import subprocess
  10.  
  11. IP = '0.0.0.0'
  12. PORT = 8820
  13. COMMANDS = ['TAKE_SCREENSHOT',"SEND_FILE", 'DIR', "DELETE", "COPY", "EXECUTE", 'EXIT']
  14.  
  15. def receive_client_request(client_socket):
  16.     """Receives the full message sent by the client
  17.  
  18.    Works with the protocol defined in the client's "send_request_to_server" function
  19.  
  20.    Returns:
  21.        command: such as DIR, EXIT, SCREENSHOT etc
  22.        params: the parameters of the command
  23.  
  24.    Example: 12DIR c:\cyber as input will result in command = 'DIR', params = 'c:\cyber'
  25.    """
  26.     client_kelet = client_socket.recv(1024)
  27.     com_par = client_kelet.split(' ')
  28.     print com_par
  29.     if len(com_par) > 2:
  30.         com_par[2] = "'" + com_par[2] + "'"
  31.         return com_par[1], com_par[2]
  32.     else:
  33.         return com_par[1], None
  34.  
  35.  
  36. def check_client_request(command, params):
  37.     """Check if the params are good.
  38.  
  39.    For example, the filename to be copied actually exists
  40.  
  41.    Returns:
  42.        valid: True/False
  43.        error_msg: None if all is OK, otherwise some error message
  44.    """
  45.     print "command = " + command
  46.     print "params = " + str(params)
  47.     try:
  48.         if command in COMMANDS:
  49.             print "got in"
  50.             print os.path.exists(params)
  51.             if command == "TAKE_SCREENSHOT":
  52.                 print "checked"
  53.                 return True, None
  54.             elif not os.path.exists(params):
  55.                 print "checked"
  56.                 return True, None
  57.         else:
  58.             err_msg = "wrong commnad"
  59.             return False, err_msg
  60.     except Exception, ex:
  61.         err_msg = "The execution didn't succeed. \n" + str(ex)
  62.         print err_msg
  63.         return False, err_msg
  64.  
  65.  
  66.  
  67.  
  68. def handle_client_request(command, params):
  69.     """Create the response to the client, given the command is legal and params are OK
  70.  
  71.    For example, return the list of filenames in a directory
  72.  
  73.    Returns:
  74.        response: the requested data
  75.    """
  76.     if command == 'TAKE_SCREENSHOT':
  77.         try:
  78.             im = ImageGrab.grab()
  79.             im.save(r'C:\Heights\Documents\Pictures\screen.jpg')
  80.             return "screenshot was saved succesfully"
  81.         except Exception, e:
  82.             print "screenshot was not saved. \n"
  83.             return e
  84.  
  85.     elif command == "SEND_FILE":
  86.         return "SEND_FILE " + params
  87.  
  88.     elif command == 'DIR':
  89.         params = params[0:len(params)-1] + "\*.*'"
  90.         print params
  91.         files_list = glob.glob(params)
  92.         print files_list
  93.         return str(files_list)
  94.  
  95.     elif command == "DELETE":
  96.         try:
  97.             os.remove(params)
  98.             return "file was removed succesfully"
  99.         except Exception, e:
  100.             print "The file was not removed. \n"
  101.             return e
  102.  
  103.     elif command == "COPY":
  104.         try:
  105.             shutil.copy(params[0], params[1])
  106.             return "file was copied succesfully"
  107.         except Exception, e:
  108.             print "The file was not copied. \n"
  109.             return e
  110.  
  111.     elif command == "EXECUTE":
  112.         try:
  113.             subprocess.call(params)
  114.             return "the execution succeeded"
  115.         except Exception, e:
  116.             print "The execution didn't succeed. \n"
  117.             return e
  118.  
  119.  
  120. def send_response_to_client(response, client_socket):
  121.     """Create a protocol which sends the response to the client
  122.  
  123.    The protocol should be able to handle short responses as well as files
  124.    (for example when needed to send the screenshot to the client)
  125.    """
  126.     if response.find("SEND_FILE") == 0:
  127.         directory = response[10:]
  128.         size = os.path.getsize(directory)
  129.         with open(directory, 'r') as file:
  130.             if size > 1024:
  131.                 content = file.readline()
  132.                 while content != '':
  133.                     msg_len = len(content)
  134.                     client_socket.send(str(msg_len))
  135.                     client_socket.send(content)
  136.                     content = file.readline()
  137.                 client_socket.send("END")
  138.             else:
  139.                 content = file.read()
  140.                 msg_len = len(content)
  141.                 client_socket.send(str(msg_len))
  142.                 client_socket.send(content)
  143.                 client_socket.send("END")
  144.     else:
  145.         client_socket.send(response)
  146.  
  147.  
  148. def main():
  149.     # open socket with client
  150.     server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  151.     server_socket.bind((IP, PORT))
  152.     server_socket.listen(1)
  153.     client_socket, address = server_socket.accept()
  154.     print client_socket
  155.     print address
  156.     # handle requests until user asks to exit
  157.     while True:
  158.         command, params = receive_client_request(client_socket)
  159.         if command == 'EXIT':
  160.             break
  161.         print command
  162.         print params
  163.         print type(params)
  164.         valid, error_msg = check_client_request(command, str(params))
  165.         if valid:
  166.             response = handle_client_request(command, params)
  167.             send_response_to_client(response, client_socket)
  168.         else:
  169.             send_response_to_client(error_msg, client_socket)
  170.  
  171.  
  172.  
  173.     client_socket.close()
  174.     server_socket.close()
  175.  
  176. if __name__ == '__main__':
  177.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement