def get_paths(self) -> Dict[str, str]: # We can't use sysconfig.get_paths() because # on some distributions it does not return the proper paths # (those used by pip for instance). We go through distutils # to get the proper ones. import site from distutils.command.install import SCHEME_KEYS # noqa from distutils.core import Distribution d = Distribution() d.parse_config_files() obj = d.get_command_obj("install", create=True) obj.finalize_options() paths = sysconfig.get_paths().copy() for key in SCHEME_KEYS: if key == "headers": # headers is not a path returned by sysconfig.get_paths() continue paths[key] = getattr(obj, "install_{}".format(key)) if site.check_enableusersite() and hasattr(obj, "install_usersite"): paths["usersite"] = getattr(obj, "install_usersite") paths["userbase"] = getattr(obj, "install_userbase") return paths
def inject_sleuth(syspath_sleuth_path: Optional[Path] = None): customize_path, is_user_path = get_customize_path() if customize_path and customize_path.exists(): name, _ = get_name_and_relative_path(customize_path, syspath_sleuth_path) sleuth_logger.warning("Reinstalling %s in %s site...", name, "user" if is_user_path else "system") reverse_patch_sleuth(customize_path) create_site_customize(customize_path) copy_site_customize(customize_path) append_sleuth_to_customize(customize_path, syspath_sleuth_path) create_reverse_sleuth_patch(customize_path) # Determine if the customize site was updated to wrap sys.path with a SysPathSleuth. if site.ENABLE_USER_SITE and site.check_enableusersite(): customize_module = importlib.import_module("usercustomize") else: customize_module = importlib.import_module("sitecustomize") reload(customize_module) class_names: Tuple[str] = tuple( x[0] for x in inspect.getmembers(customize_module, inspect.isclass)) if "SysPathSleuth" not in class_names or not isinstance( sys.path, customize_module.SysPathSleuth): # The file loaded doesn't wrap sys.path with a SysPathSleuth sleuth_logger.setLevel(logging.ERROR) reverse_patch_sleuth(customize_path) _, sleuth_path = get_name_and_relative_path(customize_path, syspath_sleuth_path) raise InstallError( f"{sleuth_path} does not wrap sys.path with a SysPathSleuth.")
def is_sleuth_active(): if site.ENABLE_USER_SITE and site.check_enableusersite(): customize_module = importlib.import_module("usercustomize") else: customize_module = importlib.import_module("sitecustomize") reload(customize_module) class_names: Tuple[str] = tuple( x[0] for x in inspect.getmembers(customize_module, inspect.isclass)) is_sleuth_active_now = "SysPathSleuth" in class_names and isinstance( sys.path, customize_module.SysPathSleuth) return is_sleuth_active_now
def get_customize_path() -> Tuple[Path, bool]: """ When using venv, site.ENABLE_USER_SITE is False. When using virtual environments, the effort is to isolate the activities within one virtual environment per Python system from other virtual environments. Were the user site enabled within a virtual environment, it would affect other Python virtual environments. :return: """ is_user_path = False if site.ENABLE_USER_SITE and site.check_enableusersite(): customize_path = get_user_customize_path() customize_path.parent.mkdir(parents=True, exist_ok=True) is_user_path = True else: customize_path = get_system_customize_path() return customize_path, is_user_path
def _is_active_in_user_site(cls, sleuth_module_file_name): # When using venv, site.ENABLE_USER_SITE is False. When using virtual environments, # the effort is to isolate the activities within one virtual environment per Python # system Python from other virtual environments. Were the user site enabled, it would # affect other Python virtual environments. if not site.ENABLE_USER_SITE or not site.check_enableusersite(): return False if sleuth_module_file_name != "usercustomize.py": # It is likely syspath_sleuth.py is being tested return False user_customize_path = cls._get_user_customize_path() if not user_customize_path.exists(): return False user_customize_path = cls.relative_path(user_customize_path) sleuth_message = f"SysPathSleuth is installed in user site: {user_customize_path}" cls._inform_user(sleuth_message) return True
def check_env_writable(): """ Checks if we can install packages to the current environment """ locations = [] try: locations.append(site.getsitepackages()[0]) except (AttributeError, IndexError): try: from distutils.sysconfig import get_python_lib locations.append(get_python_lib()) except (ImportError, ModuleNotFoundError): pass try: import pip locations.append(str(Path(pip.__path__[0]).parent.resolve())) except (ImportError, AttributeError, IndexError): pass try: if site.ENABLE_USER_SITE or site.check_enableusersite(): if site.USER_SITE: locations.append(site.USER_SITE) else: locations.append(site.getusersitepackages()) except AttributeError: pass for location in set(locations): logger.debug( f"Can write to {location}: {os.access(location, os.W_OK)}") return any([os.access(location, os.W_OK) for location in set(locations)])
if not new_path.endswith('python'): new_path = os.path.join(new_path, 'python') api_path = new_path if (len(sys.argv) > 1 and sys.argv[1].lower() == "root"): #write to root site install_path = getsitepackages()[0] if not os.access(install_path, os.W_OK): print("Root install specified but cannot write to {}".format( install_path)) sys.exit(1) elif INSTALL_VENV: install_path = getsitepackages()[0] else: if check_enableusersite(): install_path = getusersitepackages() if not os.path.exists(install_path): os.makedirs(install_path) else: print( "Warning, trying to write to user site packages, but check_enableusersite fails." ) sys.exit(1) binaryninja_pth_path = os.path.join(install_path, 'binaryninja.pth') with open(binaryninja_pth_path, 'wb') as pth_file: pth_file.write((api_path + "\n").encode('charmap')) if sys.version_info.major < 3 or (sys.version_info.major == 3 and sys.version_info.minor < 10): pth_file.write(
print("Please provide the path to Binary Ninja's install directory: \n [{}] : ".format(api_path)) new_path = sys.stdin.readline().strip() if len(new_path) == 0: print("\nInvalid path") continue if not new_path.endswith('python'): new_path = os.path.join(new_path, 'python') api_path = new_path if ( len(sys.argv) > 1 and sys.argv[1].lower() == "root" ): #write to root site install_path = getsitepackages()[0] if not os.access(install_path, os.W_OK): print("Root install specified but cannot write to {}".format(install_path)) sys.exit(1) else: if check_enableusersite(): install_path = getusersitepackages() if not os.path.exists(install_path): os.makedirs(install_path) else: print("Warning, trying to write to user site packages, but check_enableusersite fails.") sys.exit(1) binaryninja_pth_path = os.path.join(install_path, 'binaryninja.pth') open(binaryninja_pth_path, 'wb').write(api_path.encode('charmap')) print("Binary Ninja API installed using {}".format(binaryninja_pth_path))
def main(): import os import shutil import site import sys import time import traceback if os.geteuid() != 0: sys.exit("You need root permissions to do this!") args = sys.argv[1:] # Check proper usage if len(args) > 1: print "Invalid number of args. Usage: python aurorainstall.py [--uninstall]" sys.exit(1) if len(args) == 1: if args[0] != "--uninstall": print "Invalid argument. Usage: python aurorainstall.py [--uninstall]" sys.exit(1) auroraDirectory = os.getcwd() print "cwd: ", auroraDirectory # Remove aurora try: print "Removing /usr/local/bin/aurora..." os.remove("/usr/local/bin/aurora") except IOError as e: print >> sys.stderr, e print "Continuing..." except OSError as e: if (e[0] == 2): print "aurora does not already exist, contining..." # Remove aurora-manager try: print "Removing /usr/local/bin/aurora-manager..." os.remove("/usr/local/bin/aurora-manager") except IOError as e: print >> sys.stderr, e print "Continuing..." except OSError as e: if (e[0] == 2): print "aurora-manager does not already exist, contining..." if site.check_enableusersite(): site_package_dir = site.getusersitepackages() else: site_package_dir = site.getsitepackages()[0] try: os.unlink(os.path.join(site_package_dir, 'aurora.pth')) except OSError: # File didn't exist pass except Exception: traceback.print_exc(file=sys.stdout) sys.exit(1) try: os.unlink(os.path.join(site_package_dir, 'python-auroraclient.pth')) except OSError: # File didn't exist pass except Exception: traceback.print_exc(file=sys.stdout) sys.exit(1) # If not --uninstall if len(args) == 0: # Add module directory to python path try: os.makedirs(site_package_dir) except OSError: # File already exists pass try: with open(os.path.join(site_package_dir,'aurora.pth'), 'w') as F: F.write(auroraDirectory + '/aurora\n') with open(os.path.join(site_package_dir,'python-auroraclient.pth'), 'w') as F: F.write(auroraDirectory + '/python-auroraclient\n') except Exception: traceback.print_exc(file=sys.stdout) try: os.unlink(os.path.join(site_package_dir, 'aurora.pth')) except OSError: pass except Exception: traceback.print_exc(file=sys.stdout) try: os.unlink(os.path.join(site_package_dir, 'python-auroraclient.pth')) except OSError: pass except Exception: traceback.print_exc(file=sys.stdout) traceback.print_exc(file=sys.stdout) exit(1) # Create files auroramanager and aurora print "Creating auroramanager..." with open('aurora-manager', 'w') as f: f.write('''#!/usr/bin/python -tt """Script which launches aurora's manager""" import sys from aurora.shell import main if __name__ == "__main__": sys.exit(main()) ''') print "Creating aurora..." with open('aurora-client', 'w') as f: f.write('''#!/usr/bin/python -tt """Script which launches aurora's client.""" import sys from auroraclient.shell import main if __name__ == "__main__": sys.exit(main()) ''') os.chmod("aurora-manager", 0755) os.chmod("aurora-client", 0755) #copy files to /usr/local/bin print "Copying files to /usr/local/bin..." try: shutil.move('aurora-manager', '/usr/local/bin/aurora-manager') shutil.move('aurora-client', '/usr/local/bin/aurora') except IOError as e: traceback.print_exc(file=sys.stdout) sys.exit(1) print "\nTo run, first start aurora-manager:" print "\t$ aurora-manager" print "Then start aurora:" print "\t$ aurora --help"
def update_event(self, inp=-1): self.set_output_val(0, site.check_enableusersite())