How to convert this code from Python version 2 to 3.4?

Asked

Viewed 567 times

4

I’m having a hard time convert the code below for the version 3.4 of Python, the purpose of this code is to encode and decode hexadecimal, in order to create shellcodes.

import binascii, sys, time

RED = '\033[31m'
WHITE = '\033[37m'
RESET = '\033[0;0m'

def main():
    print("shellcode hex encode decoder")
    print("programmer : gunslinger_ <yudha.gunslinger[at]gmail.com>")
    print "what do you want to do ? %sencode%s / %sdecode%s" % (RED, RESET, WHITE, RESET)  
    q = raw_input("=> ")

    if q == "encode":
        inputtype = raw_input("Please input data : ")
        print "shellcode => ",
        for encoded in inputtype:
            print "\b\\x"+encoded.encode("hex"),
            sys.stdout.flush()
            time.sleep(0.5)
            print RESET

    elif q == "decode":
        inputtype = raw_input("Please input data : ")
        cleaninput = inputtype.replace("\\x","")
        print "hex       => ",cleaninput
        print "plaintext => ",
        print "\b"+cleaninput.decode("hex")

    else:
        print "wrong answer ! your choice is %sencode%s or %sdecode%s" % (RED, RESET, WHITE, RESET)
        sys.exit(1)

if __name__ == '__main__':
    main()

That part I didn’t understand:

print "what do you want to do ? %sencode%s / %sdecode%s" % (RED, RESET, WHITE, RESET)  

All right he set the colors on top, and the %sencode%s / %sdecode%s how does it work? I understand he made a %s, at the beginning and at the end of the words encounter and Decode and call with the colors.

q = raw_input("=> ")

He defined the variable and this => something specific in Python 2?

In this part below I understood some parts but not all if someone explain me better I am grateful.

inputtype = raw_input("Please input data : ")
print "shellcode => ",
for encoded in inputtype:
    print "\b\\x"+encoded.encode("hex"),
    sys.stdout.flush()
    time.sleep(0.5)

Personal thank you.

  • 1

    Have you tried the 2to3? If that doesn’t work out, say what are these "little problems", what you’ve tried to do to solve them, and what you want us to help. At first glance, a few parentheses after the printwould solve most of the problems...

  • 1

    @mgibsonbr Why don’t you create an answer? I think it should be interesting to show this translation process.

  • 2

    @qmechanik I was just giving a quick tip that maybe solve problems without having to think long. But in reality, an answer like yours that explains the differences between the versions is much more useful. The 2to3, from what I read (never actually used it), it would only be an aid to convert large codes, but it does not guarantee that the result is a correct and functional code (i.e. it does not dispense with careful revision of the converted code).

1 answer

6


Some changes should be made to the code to work as expected in Python 3.

  • In versions prior to Python 3 print was an instruction (statement), from Python 3, it is considered a function, and so some details of the syntax have changed, such as the mandatory use of parentheses, ().

    inserir a descrição da imagem aqui

  • From Python 3, the function built-in raw_input() was renamed for input().

    inserir a descrição da imagem aqui

  • In Python 3 it is not necessary to use the comma at the end to delete a new line.

    inserir a descrição da imagem aqui

  • From the Python 3.4 the methods that dealt with coding and decoding were replaced by the functions of the module codecs.

    Python 3.4, wrong mode:

    b"hello".decode("hex")
    Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
    

    Python 3.4, correct mode:

    >>> from codecs import encode, decode
    >>> encode(b"hello", "hex")
    b'68656c6c6f'
    >>> decode(b"68656c6c6f", "hex")
    b'hello'
    
  • That part I didn’t understand:

    print "what do you want to do ? %sencode%s / %sdecode%s" % (RED, RESET, WHITE, RESET)
    

    The four occurrences of the format %s shall be replaced by the values of RED, RESET, WHITE and RESET. The print will print:

    print "what do you want to do ? \033[31mencode\033[0;0m / \033[37mdecode\033[0;0m"
    

    This will print on the screen words with a different color, other color combinations can be seen here.

  • q = raw_input("=> ") -> he defined the variable and this => serial something specific in python 2

    The => is the text that will be displayed and will receive the user input.

  • In this part below I understood some parts but not all if someone explain me better I am grateful.

    inputtype = raw_input("Please input data : ") # Recebe a entrada do usuário
    print "shellcode => ",                        # Imprime "shellcode =>" e elimina a nova linha
    for encoded in inputtype:                     # Percorre cada letra da variável "inputtype"
        print "\b\\x"+encoded.encode("hex"),
        sys.stdout.flush()                        # Imprime diretamente na saída padrão "stdout"
        time.sleep(0.5)                           # Espera 30s
    

The code converted for Python 3 should look like this:

import sys, time, binascii
# -*- coding: utf-8 -*-

RED = '\033[31m'
WHITE = '\033[37m'
RESET = '\033[0;0m'

def main():
    print("shellcode hex encode decoder")
    print("programmer : gunslinger_ <yudha.gunslinger[at]gmail.com>")
    print("what do you want to do ? {0}encode{1} / {2}decode{3}".format(RED, RESET, WHITE, RESET))
    q = input("=> ")

    if q == "encode":
        inputtype = input("Please input data : ")
        print ("shellcode => ")
        for encoded in inputtype:
            print ("\\x{0}".format(binascii.hexlify(bytes(encoded, 'utf-8')).decode()))
            sys.stdout.flush()
            time.sleep(0.5)
            print (RESET)

    elif q == "decode":
        inputtype = input("Please input data : ")
        cleaninput = inputtype.replace("\\x","")
        print ("hex       => {0}".format(inputtype))
        print ("plaintext => {0}".format(binascii.unhexlify(cleaninput).decode('utf-8')))
    else:
        print ("wrong answer ! your choice is %sencode%s or %sdecode%s" % (RED, RESET, WHITE, RESET))
        sys.exit(1)

if __name__ == '__main__':
    main()

One more version clean and with some modifications:

# -*- coding: utf-8 -*-
import sys, binascii

cor = {'vermelho': '\033[1;31m', 'branco': '\033[1;34m', 'sem_cor': '\033[0;0m'}

def shellcode(opcao, texto):
    resultado = ""
    if opcao == 'e':
        resultado += ''.join("\\x{0}".format(binascii.hexlify(bytes(s, 'utf-8')).decode()) for s in texto)
    elif opcao == 'd':
        texto = texto.replace('\\x', '')
        resultado = binascii.unhexlify(texto).decode()
    return resultado

def main():
    opcoes = "{0}encode{1} / {2}decode{3} ou sair".format(cor['vermelho'], cor['sem_cor'], cor['branco'], cor['sem_cor'])
    print("O que quer fazer? {0}".format(opcoes))
    while True:
        try:
            questao = input("Opcao: ").lower()
            dados = input("Dados: ")
            codigo = ""

            if questao in ['encode', 'enc', 'e']:
                codigo = shellcode('e', dados)
            elif questao in ['decode', 'dec', 'd']:
                codigo = shellcode('d', dados)
            elif questao in ['sair', 's']:
                sys.exit()
            else:
                sys.exit("Opcao inválida! Opcoes: {0}".format(opcoes))

            print("{0}: {1}".format(questao, codigo))
        except KeyboardInterrupt:
            sys.exit()

if __name__ == '__main__':
    main()
  • Dust friend I help many in my doubts, I saw you put the code in the new formatted ones, but I wish you had not put yourself. And that I like to put my head to work, if I had any doubt I would ask here again. Since I’m a beginner in python and good at getting my head straight, I’m going to do the code here my way and then put it here as it was. Thank you very much.

  • 1

    @Glauciofonseca I understood, in any case I posted a cleaner version and corrected an error in the part of Decode, If there’s anything else I can do to help, let me know. =)

  • Thanks a bro thanks.

  • 1

    @Glauciofonseca If possible mark the answer as accepted. =)

  • I already marked the answer accept @qmechanik

  • 1

    @Glauciofonseca To mark how you accept click on the after it turns green. Another thing, if you want to use codecs.encode/decode instead of binascii.hexlify/unhexlify also right.

  • 1

    Done bro thanks.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.