IndexError: Список исключений вне диапазона, созданный в Python 3, но не в Python 2 - PullRequest
1 голос
/ 07 марта 2019

Это исходный код, который я написал, и когда я набираю lls, он перечисляет только 1 элемент из 10, а также, когда я набираю indexLindGet longlist, он возвращает список индексов диапазона со стороны сервера.

client.py

#! /usr/bin/python3.7


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)
    inputFile = string
    socket1.send(commandName.encode('utf-8'))
    with open(inputFile, 'r') as file_to_send:
        for data in file_to_send:
            socket1.sendall(data.encode("utf-8"))
            print("Client users " + "data")
            socket1.send.encode('utf-8')(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.encode("utf-8"))
    string = commandName.split(' ')
    inputFile = string[1]
    with open(inputFile, 'w') as file_to_write:
        while True:
            data = socket1.recv(1024).decode("utf-8")
            if not data:
                break
            # print data
            file_to_write.write(data.decode("utf-8"))
    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.encode('utf-8'))
    hashValServer = socket1.recv(1024).decode('utf-8')

    string = commandName.split(' ', 1)
    BLOCKSIZE = 65536
    hasher = hashlib.sha1()
    with open(string[2], 'r') 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.encode('utf-8'))

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

    while True:
        f = socket1.recv(1024)

        with open(f, 'r') 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.encode('utf-8'))
    socket1.close()
    return


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

    elif string[1] == 'longlist':
        socket1.send(commandName.encode('utf-8'))
        path = socket1.recv(1024)
        rslt = path.decode('utf-8').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.encode('utf-8'))
    fileStr = socket1.recv(1024)
    fileList = fileStr.decode('utf-8').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)

server.py

#! /usr/bin/python3.7

import subprocess
import socket
import sys
import os
import hashlib

HOST = '0.0.0.0'
PORT = 8000

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    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).decode('utf-8')
    print('Client> %s' % reqCommand)
    string = reqCommand.split(' ', 1)
    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.encode('utf-8'))
        # print path

    elif not 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.encode("utf-8")(var1)

    elif string[0] == 'FileHash':
        if string[1] == 'verify':
            BLOCKSIZE = 65536
            hasher = hashlib.sha1()
            with open(string[2], 'r') 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.encode('utf-8'))
                with open(f, 'r') 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(' ', 1)  # in case of 'put' and 'get' method
        if len(string) > 1:
            reqFile = string[1]

            if string[0] == 'FileUpload':
                file_to_write = open(reqFile, 'w')
                si = string[2:]
                for p in si:
                    p = p + " "
                    print("User" + 'p')
                    file_to_write.write('p')
                while True:
                    data = conn.recv(1024).decode()
                    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(data)
                print('Send Successful')
    conn.close()

s.close()

Это ошибка, которую я получил со стороны сервера

Сервер создан Завершение гнезда завершено Сервер сейчас слушает Traceback (последний вызов был последним): Файл "server.py", строка 47, в elif not string [1] == 'короткий список': IndexError: список индексов вне диапазона Связано с 127.0.0.1:48954

...