Что делать если нужно поставить какую-то Python-библиотеку а root-прав нет? То есть в систему библиотеку никак и ничего не поставить.
Есть как минимум два способа это решить правильно!
🔸 Сделать виртуальное окружение и ставить там что угодно.
Это позволит создать полностью независимое исполняемое окружение для ваших приложений.
Все библиотеки будут храниться в домашней директории юзера а значит доступ на запись имеется.
Создать очень просто:
python3 -m venv ~/venvs/myenvname
Теперь активируем окружение
# Linux
source ~/venvs/myenvname/bin/activate
# Windows
%userprofile%\venvs\myenvname\Scripts\activate.bat
Можно ставить любые библиотеки и запускать приложение.
Это стандартный метод работы с любым проектом. Если еще не используете его, то пора начинать. Даже при наличии root доступа!
🔸 Бывает, что нет возможности запустить приложение из своего виртуального окружения. Например, его запускает какой-то сервис от вашего юзера и вставить активацию окружения вы не можете.
В этом случае можно установить библиотеки для Python не глобально в систему, а только для юзера.
Выполните этот код в консоли:
python3 -m site
Вы получите что-то такое:
sys.path = [
'/home/user',
'/usr/lib/python37.zip',
'/usr/lib/python3.7',
'/usr/lib/python3.7/lib-dynload',
'/home/user/.local/lib/python3.7/site-packages',
...
]
USER_BASE: '/home/user/.local'
USER_SITE: '/home/user/.local/lib/python3.7/site-packages'
ENABLE_USER_SITE: True
Нас интересует параметр USER_SITE. Это путь к пользовательским библиотекам, которые доступны по умолчанию, если они есть.
Именно сюда будут устанавливаться модули если добавить флаг --user при установке чего-либо через pip
pip install --user requests
Для этой команды не нужны root-права.
После неё можно запускать системный интерпретатор без виртуальных окружений и установленная библиотека будет доступна для текущего юзера.
Параметр USER_BASE показывает корневую директорию для хранения user-библиотек. Её можно изменить с помощью переменной окружения PYTHONUSERBASE
export PYTHONUSERBASE=~/pylibs
python3 -m site
...
USER_BASE: '/home/user/pylibs'
USER_SITE: '/home/user/pylibs/lib/python3.7/site-packages'
Получается некоторое подобие виртуального окружения для бедных 😁 которое можно менять через эту переменную (не делайте так!Лучше venv!)
🔸 Дописывание пути в PYTHONPATH
Этот способ не входит в список "двух правильных", но тоже рабочий. Здесь придётся сделать всё несколько сложней.
Сначала ставим библиотеку в любое место указывая путь установки
pip3 install -t ~/mylibs modulename
Библиотека установится без привязки к какому-либо интерпретатору. То есть по умолчанию не будет видна. Теперь в нужный момент добавляем этот путь в sys.path или в PYTHONPATH.
Не буду советовать так делать. Единственный раз когда этот способ мне пригодился и решил поставленную задачу, это при создании общей библиотеки для кластера компьютеров.
Модули лежат в сети и подгружаются для всех из одного и того же места. То есть обновлять файлы требуется только один раз а не на всех хосты отдельно.
Минусы такого подхода:
▫️Нужно всем хостам пробить нужный путь в .bashrc или ещё куда-то чтобы он сетапился на старте.
▫️Чем больше хостов тем больше нагрузка на сеть. Иногда такой способ не подходит именно по этой причине. Тогда Ansible вам в помощь.
▫️Не очень подходит если хосты с разными операционками. Некоторые библиотеки различаются для Linux и Windows (там, где есть бинарники) и приходится мудрить более сложные схемы.
#tricks#basic
#Hacking
🥷
Complete Ethical Hacking Bootcamp (2023)
Learn Ethical Hacking + Penetration Testing! Use real techniques by black hat hackers then learn to defend against them!
-----
Main channel: @repo_science
Coupons: @freecoupons_reposcience
-----
#hacking
🛠
Automobile Hacking and Security v2 0
Description
Have you ever thought the car you drive can also be hacked and it’s also vulnerable to hackers ?
Welcome to the second course on Automobile Hacking and Security version 2.0.
In this course we will look at some advanced and interesting concepts and see how deep the rabbit hole goes. We will start this course with the overview of the first course so all things revised and clear.
🌐En
🔗Link
-----
Main channel:@repo_science
Coupons:@freecoupons_reposcience
-----
#hacking
📊
Exclusive Hacker House Trainings
Description:
Hacker House Hands-On Hacking course is an intensive introductory course that teaches applied hacking methodologies in a hands-on practical orientated approach. Our course is engineered from decades of experienced cyber security practitioner’s knowledge to educate students on common cyber security tasks. Our course is delivered by expert hackers to prepare students on adversarial thinking and equip them for tasks conducted in a number of different cyber security roles.
🌐En
🔗Link
-----
Main channel:@repo_science
Coupons:@freecoupons_reposcience
-----
https://www.youtube.com/watch?v=3bZNhMcv4Y8
#Hacking Cars with Python
Modern cars are networks of computers, and a high end vehicle could have nearly 100 different computers inside. These devices control everything from the engine to the airbags. By understanding how these systems work, we can interface with vehicles to read data, perform diagnostics, and even modify operation.
#hacking#python
🐍
Python Hacking | Real Ethical Hacking with Python | PYCEH23+
Description:
This immersive and comprehensive course is designed to equip you with the knowledge and hands-on skills necessary to excel in the exciting world of ethical hacking.
With a focus on practical applications, this course covers everything you need to know about Python programming, making it accessible to both beginners and experienced programmers. You’ll embark on an exciting journey where you’ll learn how to harness the power of Python to manipulate MAC addresses, develop network scanners, execute Man-in-the-Middle attacks, intercept network traffic, create your own pentesting RAT (Remote Access Trojan) malware, and much more.
🌐En
🔗Link
-----
Main channel:@repo_science
Coupons:@freecoupons_reposcience
-----
#hacking#Cybersecurity
🛠
Certified in Cybersecurity 2023 – ISC2-CC Complete Training
Description
About this courseThe CC training course is designed to provide you with a detailed understanding of information security management, risk management, and incident management. The course is divided into four domains, each of which is covered in-depth:The course is designed to help you develop the necessary skills to become a successful information security manager by providing you with practical knowledge and hands-on experience.Additional NotesCourse Requirements:No requirements Certification:Upon completion of the course, you will be eligible to sit for the CC certification exam. The exam is administered by ISC2 Enroll in the CC training course today and take the first step towards becoming a certified in cybersecurity!
🌐En
⚖️1.01 GB
🔗Link
-----
Main channel:@repo_science
Coupons:@freecoupons_reposcience
-----
#hacking#Cybersecurity
📊
Cyber Security From Beginner to Expert
Description:
A beginner level comprehensive course that includes step-by-step explanations of core security concepts along with follow-up quizzes and hands on labs to ensure a solid learning for the course taker.
🌐En
🔗Link
-----
Main channel:@repo_science
Coupons:@freecoupons_reposcience
-----
#hacking#Cybersecurity
📊
Complete Cybersecurity Bootcamp
Description:
The Cybersecurity Bootcamp that will take you from ZERO to HIRED as a Cyber Security Engineer. You'll learn the latest best practices, techniques, and tools used for network security so that you can build a fortress for digital assets and prevent black hat hackers from penetrating your systems.
🌐En
🔗Link
-----
Main channel:@repo_science
Coupons:@freecoupons_reposcience
-----