《黑帽Python》第7章GitHub远控AttributeError: recurse错误修复
修复
AttributeError: recurse 错误方案 嘿,我来帮你搞定这个报错!先梳理下你的场景和问题:
你的开发环境
root@kali:~# python Python 2.7.3 (default, Mar 14 2014, 11:57:14) [GCC 4.7.2] on linux2
遇到的错误
运行你提供的git_trojan.py脚本时,抛出了这个错误:
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
问题根源
这个报错的核心原因是你使用的github3.py库版本和脚本依赖的版本不兼容:旧版github3.py里Tree对象的recurse()方法已经被移除了,脚本里调用了一个不存在的方法,自然就触发了属性错误。
具体修复方案
你需要修改get_file_contents函数,把调用recurse()的逻辑改成手动递归遍历仓库的文件树。替换后的函数代码如下:
def get_file_contents(filepath): gh, repo, branch = connect_to_github() # 获取分支对应commit的根tree root_tree = branch.commit.commit.tree # 定义递归遍历函数,查找目标文件 def traverse_tree(tree): for item in tree.tree: if item.type == 'tree': # 如果是子目录,继续递归遍历 sub_tree = repo.tree(item.sha) result = traverse_tree(sub_tree) if result: return result elif item.path == filepath: # 找到目标文件,返回其内容 print("[*] Found file %s" % filepath) blob = repo.blob(item.sha) return blob.content return traverse_tree(root_tree)
额外注意事项
- 因为你用的是Python2.7(已经停止维护),要确保安装的
github3.py是支持Python2.7的最后兼容版本,避免出现其他兼容性问题 - 检查
connect_to_github函数里的GitHub用户名、密码、仓库名是否正确配置,这也是脚本正常运行的前提
修改完后重新运行脚本,应该就能正常获取GitHub仓库里的文件内容,不会再出现AttributeError: recurse的错误了。
内容的提问来源于stack exchange,提问作者0000 00
相关产品推荐
相关产品推荐

