Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
File Transfer
#3
import socket
import sys
import os
import hashlib

HOST = 'localhost'
PORT = 8000

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('Server Created')
except OSError as e:
    print('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
    sys.exit()

try:
    s.bind((HOST, PORT))
except OSError as e:
    print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
    sys.exit()
print('Socket bind complete')

s.listen(1)
print('Server now listening')

while (1):
    conn, addr = s.accept()
    print('Connected with ' + addr[0] + ':' + str(addr[1]))
    reqCommand = conn.recv(1024)
    print('Client> %s' % (reqCommand))
    string = reqCommand
    if (reqCommand == 'quit'):
        break
    elif (reqCommand == 'lls'):
        toSend = ""
        path = os.getcwd()
        dirs = os.listdir(path)
        for f in dirs:
            toSend = toSend + f + ' '
        conn.send(toSend)
        # print path

    elif (string[1] == 'shortlist'):
        path = os.getcwd()
        command = 'find ' + path + ' -type f -newermt ' + string[2] + ' ' + string[3] + ' ! -newermt ' + string[
            4] + ' ' + string[5]
        var = commands.getstatusoutput(command)
        var1 = var[1]
        var = var1.split('\n')
        rslt = ""
        for i in var:
            comm = "ls -l " + i + " | awk '{print $9, $5, $6, $7, $8}'"
            tup = commands.getstatusoutput(comm)
            tup1 = tup[1]
            str = tup1.split(' ')
            str1 = str[0]
            str2 = str1.split('/')
            rslt = rslt + str2[-1] + ' ' + str[1] + ' ' + str[2] + ' ' + str[3] + ' ' + str[4] + '\n'
        conn.send(rslt)

    elif (string[1] == 'longlist'):
        path = os.getcwd()
        var = commands.getstatusoutput("ls -l " + path + " | awk '{print $9, $5, $6, $7, $8}'")
        var1 = ""
        var1 = var1 + '' + var[1]
        conn.send(var1)

    elif (string[0] == 'FileHash'):
        if (string[1] == 'verify'):
            BLOCKSIZE = 65536
            hasher = hashlib.sha1()
            with open(string[2], 'rb') as afile:
                buf = afile.read(BLOCKSIZE)
                while len(buf) > 0:
                    hasher.update(buf)
                    buf = afile.read(BLOCKSIZE)
            conn.send(hasher.hexdigest())
            print('Hash Successful')




        elif (string[1] == 'checkall'):
            BLOCKSIZE = 65536
            hasher = hashlib.sha1()

            path = os.getcwd()
            dirs = os.listdir(path)
            for f in dirs:
                conn.send(f)
                with open(f, 'rb') as afile:
                    buf = afile.read(BLOCKSIZE)
                    while len(buf) > 0:
                        hasher.update(buf)
                        buf = afile.read(BLOCKSIZE)
                conn.send(hasher.hexdigest())
                print('Hash Successful')



    else:
        string = reqCommand.split(' ')  # in case of 'put' and 'get' method
        if (len(string) > 1):
            reqFile = string[1]

            if (string[0] == 'FileUpload'):
                file_to_write = open(reqFile, 'wb')
                si = string[2:]
                for p in si:
                    p = p + " "
                    print("User" + p)
                    file_to_write.write(p)
                while True:
                    data = conn.recv(1024)
                    print("User" + data)
                    if not data:
                        break
                    file_to_write.write(data)
                file_to_write.close()
                print('Receive Successful')
            elif (string[0] == 'FileDownload'):
                with open(reqFile, 'rb') as file_to_send:
                    for data in file_to_send:
                        conn.sendall
                print('Send Successful')
    conn.close()

s.close()


import socket
import sys
import os
import hashlib

HOST = 'localhost'  # server name goes in here
PORT = 8000

def put(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    string = commandName.split(' ', 1).encode()
    inputFile = string.encode()
    socket1.send(commandName)
    
    with open(inputFile, 'rb') as file_to_send:
        for data in file_to_send:
            socket1.sendall(data)
            print("Client users " + data)
            socket1.send(data)
    print('Upload 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(' ')
    inputFile = string[1]
    with open(inputFile, 'wb') as file_to_write:
        while True:
            data = socket1.recv(1024)
            if not data:
                break
            # print data
            file_to_write.write(data)
    file_to_write.close()
    print('Download Successful')
    socket1.close()
    return


def FileHash(commandName):
    string = commandName.split(' ')
    if string[1] == 'verify':
        verify(commandName)
    elif string[1] == 'checkall':
        checkall(commandName)


def verify(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)
    hashValServer = socket1.recv(1024)

    string = commandName.split(' ')
    BLOCKSIZE = 65536
    hasher = hashlib.sha1()
    with open(string[2], 'rb') as afile:
        buf = afile.read(BLOCKSIZE)
        while len(buf) > 0:
            hasher.update(buf)
            buf = afile.read(BLOCKSIZE)
    hashValClient = hasher.hexdigest()
    print('hashValServer= %s', (hashValServer))
    print('hashValClient= %s', (hashValClient))
    if hashValClient == hashValServer:
        print('No updates')
    else:
        print('Update Available')

    socket1.close()
    return


def checkall(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)

    string = commandName.split(' ')
    BLOCKSIZE = 65536
    hasher = hashlib.sha1()
    # f=socket1.recv(1024)

    while True:
        f = socket1.recv(1024)

        with open(f, 'rb') as afile:
            buf = afile.read(BLOCKSIZE)
            while len(buf) > 0:
                hasher.update(buf)
                buf = afile.read(BLOCKSIZE)
        hashValClient = hasher.hexdigest()
        hashValServer = socket1.recv(1024)

        print('Filename =    %s', f)
        print('hashValServer= %s', (hashValServer))
        print('hashValClient= %s', (hashValClient))
        if hashValClient == hashValServer:
            print('No updates')
        else:
            print('Update Available')
        if not f:
            break

    socket1.close()
    return


def quit():
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)
    socket1.close()
    return


def IndexGet(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    string = commandName.encode('utf-8').split(' ')
    if string[1] == 'shortlist':
        socket1.send(commandName)
        strng = socket1.recv(1024)
        strng = strng.split('\n')
        for f in strng:
            print(f)

    elif (string[1] == 'longlist'):
        socket1.send(commandName)
        path = socket1.recv(1024)
        rslt = path.split('\n')
        for f in rslt[1:]:
            print(f)

    socket1.close()
    return


def serverList(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)
    fileStr = socket1.recv(1024)
    fileList = fileStr.split(' ', 1)
    for f in fileList[:-1]:
        print(f)

    socket1.close()
    return


msg = input('Enter your name: ')
while (1):
    print("\n")
    print("****************")
    print('Instruction')
    print('"FileUpload [filename]" to send the file the server ')
    print('"FileDownload [filename]" to download the file from the server ')
    print('"ls" to list all files in this directory')
    print('"lls" to list all files in the server')
    print('"IndexGet shortlist <starttimestamp> <endtimestamp>" to list the files modified in mentioned timestamp.')
    print('"IndexGet longlist" similar to shortlist but with complete file listing')
    print('"FileHash verify <filename>" checksum of the modification of the mentioned file.')
    print('"quit" to exit')
    print("\n")
    sys.stdout.write('%s> ' % msg)
    inputCommand = sys.stdin.readline().strip()
    if (inputCommand == 'quit'):
        quit()
        break
    elif (inputCommand == 'ls'):
        path = os.getcwd()
        dirs = os.listdir(path)
        for f in dirs:
            print(f)
    elif (inputCommand == 'lls'):
        serverList('lls')

    else:
        string = inputCommand.split(' ', 1)
        if string[0] == 'FileDownload':
            get(inputCommand)
        elif string[0] == 'FileUpload':
            put(inputCommand)
        elif string[0] == 'IndexGet':
            IndexGet(inputCommand)
        elif string[0] == 'FileHash':
            FileHash(inputCommand)
Reply


Messages In This Thread
File Transfer - by deezy - Nov-09-2017, 05:39 PM
RE: File Transfer - by heiner55 - Nov-10-2017, 06:15 AM
Can you walk me through how to encode it to byte to make it run - by Jaylord - Feb-24-2019, 03:10 PM
RE: File Transfer - by Jaylord - Feb-24-2019, 04:54 PM
RE: File Transfer - by Jaylord - Feb-25-2019, 09:44 AM
RE: File Transfer - by Jaylord - Feb-25-2019, 02:41 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  File transfer with xmodem CRC (1024) checksum Jhonbovi 3 8,337 Nov-08-2018, 09:01 AM
Last Post: Larz60+
  file transfer with sockets sinister88 1 6,476 Nov-11-2017, 03:29 PM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020