Переход на Python 3 в Debian и Kali Linux
Python 2 в Debian и производных дистрибутивах
Kali Linux полностью перешла на Python 3. Это означает, что любой инструмент, присутствующий в репозиториях Kali, который использовал Python 2, был либо удалён, либо конвертирован для использования в Python 3. Во всех этих инструментах в качестве шебанга указан /usr/bin/python3.
Что касается пакетов, которые поступают прямо из Debian, они сделали то же самое для большинства пакетов, но есть несколько исключений, когда пакетам разрешено продолжать полагаться на Python 2. Однако эти пакеты были обновлены, поэтому все эти скрипты используют /usr/bin/python2 в качестве их шебанга, то есть в них использование python2 указано явно (вместо прежнего python).
Благодаря этим изменениям Debian больше не нужно предоставлять /usr/bin/python, а недавние обновления эффективно избавятся от этой символической ссылки.
К сожалению, когда вы загружаете скрипт Python в Интернет, он, скорее всего, будет иметь /usr/bin/python в качестве его шебанга. Если вы попытаетесь выполнить его, не исправляя строку shebang, вы получите ошибку, подобную этой:
То есть плохой интерпретатор /usr/bin/python, нет такого файла или каталога.
В Debian вы можете восстановить символическую ссылку /usr/bin/python, установив один из пакетов:
- python-is-python2, если вы хотите, чтобы он указывал на python2
- python-is-python3, если вы хотите, чтобы он указывал на python3
Сохранение обратной совместимости в Kali с Python 2
Учитывая большое количество пользователей, которые не знали, как избежать вышеуказанной ошибки, было решено, что Kali будет продолжать поставлять Python 2 по умолчанию (пока Debian всё ещё предоставляет его) и что /usr/bin/python будет указывать на него. Также сохранено несколько общих внешних модулей (например, requests), чтобы скрипты эксплойтов имели разумные шансы на успешное выполнение.
Однако pip для Python2 (он же python-pip) больше не используется, /usr/bin/pip совпадает с /usr/bin/pip3, и он установит модули для Python 3. Для получения дополнительной информации смотрите вопросы и ответы ниже.
Эта совместимость была реализована за счёт того, что kali-linux-headless рекомендовал python2, python-is-python2 и offsec-awae-python2, так что они устанавливаются по умолчанию и могут быть удалены пользователями, которые хотели бы избавиться от них.
Чтобы пользователи знали об этой ситуации, при входе в систему выводится сообщение:
В этом сообщении дана ссылка на страницу, перевод которой вы сейчас читаете. Ниже будет показано, что нужно сделать, чтобы это сообщение не выводилось.
Часто задаваемые вопросы по переходу на Python 3
В: Я загрузил скрипт Python, что мне делать?
О: Вам нужно осмотреть его шебанг. Строка shebang — это первая строка скрипта, которая начинается с символов #! за которыми следует путь к интерпретатору, который будет использоваться для выполнения скрипта.
Если интерпретатором является /usr/bin/python, вам следует прочитать документацию, чтобы узнать, может ли скрипт работать с Python 3. Если да, то вам следует обновить строку shebang, чтобы она указывала на /usr/bin/python3. В противном случае вам следует обновить его, чтобы она указывал на /usr/bin/python2.
Хорошие строки shebang, которые можно оставить как есть:
- #!/usr/bin/python3
- #!/usr/bin/python2
- #!/usr/bin/env python3
- #!/usr/bin/env python2
Плохие строки shebang, которые необходимо обновить:
- #!/usr/bin/python
- #!/usr/bin/env python
В: Как я могу избавиться от сообщения о Python 2 которое показывается при входе в систему?
О: Сообщение будет отображаться только до тех пор, пока /usr/bin/python указывает на устаревший Python 2. Теперь, когда вы знаете об этой ситуации и знаете, как исправить строку shebang в старых скриптах, вы можете безопасно избавиться от /usr/bin/python:
Или вы можете указать на Python 3:
Любое из этих действий избавит от приведённого выше сообщения.
В качестве альтернативы, если вы хотите, чтобы /usr/bin/python указывал на python2, и вы всё равно хотите отключить это сообщение, вы можете сделать это:
В: У меня есть скрипт Python 2, который не запускается, что мне делать?
О: Если ваш скрипт Python 2 использует модули, которых нет среди тех, которые поставляются в пакете совместимости offsec-awae-python2 (смотрите список здесь), то вы можете попробовать pyenv для установки полностью изолированной среды Python 2, где вы можете использовать pip для установки дополнительных модулей. Смотрите следующий раздел «Использование версий EoL Python в Kali».
How To Install python3 on Kali Linux
In this tutorial we learn how to install python3 on Kali Linux.
What is python3
Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics.
This package is a dependency package, which depends on Debian’s default Python 3 version (currently v3.9).
There are three ways to install python3 on Kali Linux . We can use apt-get , apt and aptitude . In the following sections we will describe each method. You can choose one of them.
Install python3 Using apt-get
Update apt database with apt-get using the following command.
After updating apt database, We can install python3 using apt-get by running the following command:
Install python3 Using apt
Update apt database with apt using the following command.
After updating apt database, We can install python3 using apt by running the following command:
Install python3 Using aptitude
If you want to follow this method, you might need to install aptitude first since aptitude is usually not installed by default on Kali Linux. Update apt database with aptitude using the following command.
After updating apt database, We can install python3 using aptitude by running the following command:
How To Uninstall python3 on Kali Linux
To uninstall only the python3 package we can use the following command:
Uninstall python3 And Its Dependencies
To uninstall python3 and its dependencies that are no longer needed by Kali Linux, we can use the command below:
Remove python3 Configurations and Data
To remove python3 configuration and data from Kali Linux we can use the following command:
Remove python3 configuration, data, and all of its dependencies
We can use the following command to remove python3 configurations, data and all of its dependencies, we can use the following command:
References
Summary
In this tutorial we learn how to install python3 using different package management tools like apt, apt-get and aptitude.
How to install Python 3.6+ version in Kali Linux?
I need help. I newone in Linux OS and in Python at all.
I need to install python interpreter v. 3.6 for my current project. The reason is — lib, that i would like to use doesn’t work on 3.7+ I use Pycharm and want to set new environment with interpreter 3.6. I know that i can set it in settings/project/python interpreter. But i can see only python v2,v2.7,v3,v3.9. How can i add 3.6 version? Please, help)
command apt install python3.6 doen’t help me.
Serge Ballesta helped me. Thanks a lot! Just for silly ubuntu users like me — "how to install some source distribution"
How To Install Python on Kali Linux (2023 Guide)
Follow this step-by-step guide to Install or Update Python on your favorite hacking distro, Kali Linux!

Kali Linux is a secure distribution of Linux which has been derived from Debian and designed especially for system forensics, hacking and advanced penetration testing. It was developed through the rewriting of BackTrack which is now discontinued. It carries different tools which are designed for different information security tasks like testing, penetration, security research, reverse engineering and computer forensics. This article covers all the steps on how to Install Python on Kali Linux.
If you have Python 3.9, 3.8 or 3.7 already installed, we also show you how to upgrade Python on Kali Linux if you want to go to Python 3.10.
Why Install and use Python on Kali Linux
Kali Linux is an operating system specifically developed for ethical hackers. It is used by thousands of hackers and companies around the world to penetration test and breaks into their networks. It is popular among such audiences due to the various hacking tools it comes packaged with such as Wireshark and Nmap.
This is a bold distribution that has to be disproven. It has more than 580 pre-installed penetration-testing apps in order to discover. Every program comes with its unique flexibility and uses case.
Python is used a lot of scripting and automation and it has various libraries that work with Linux, hence why many security professionals use Python to create scripts used for hacking purposes that they may create based on a vulnerability.
Below are four different categories of the security professional where Python is used:
- Black hat hackers use Python to discover and exploit vulnerabilities, it comes with many network, malware analysis and security libraries that can be utilized by them to compromise an individual or organization. They can also download such applications off the shelf to use to get into a server or device.
- Forensic engineers, propose a forensic mode through which they can perform data discovery and recovery in some instances. Python has a famous imaging library called “PIL” which stands for “Python Imaging Library” which is used in AI/ML imaging applications.
- Security administrators or IT admins are responsible to safeguard both the information and data of their institution so doing this involves running security tests. What they do is use ready-made and custom Python scripts to review the environment and make sure that there are no vulnerabilities that are discovered easily. Many have automated scripts that they run for example to check for missing patches, open ports and out-of-date software.
- Penetration testers working independently or for bug bounty programs use Kali to perform monitoring and social engineering on businesses. They can check for vulnerabilities, default admin accounts, backups that are not encrypted and passwords, and pages open to the public that shouldn’t be!
How to Install or Upgrade Python on Kali Linux (Python 3.9, 3.8, 3.7)
One of the widely used high-level and object-oriented languages has become famous for beginners and experienced programmers for being simple and open-source for a big community. With this, you can build all kinds of apps, from small, simple scripts to complex machine learning-based issues.
Version 3.7 which is old can be installed using the apt package manager directly. Python 3.9 which is stable has been launched with improvements and security updates. The company has added different new modules and extended the existing modules with extra features.
A gentle reminder, Python 3.9 can’t be installed from standard Kali Linux repositories but can be installed from the original source once you add it.
Let’s see how to install Python 3.9 on Kali Linux from the terminal. All the commands shall be implemented in the Kali terminal so it is the same for you. So, you need to open the terminal app by clicking Ctrl + Alt + t from the keyboard in Kali.
Step 1: Install necessary packages in Kali core:
You first need to install all the packages and dependencies which are needed to build the source of python, so, to install the required packages follow the command below:

Now you need to upgrade Python on Kali Linux:

Step 2: Download the latest Python release for Kali Linux:
You need to have the latest python release from the python download page, for this you need to use the “curl” command to download the python release or alternatively the way shown in the image:

Step 3: Extract the installer file
Once the process of download has been completed, the file shall be saved into the tar extension. Extract the file by using the command below with Tar or you can use alternatives such as p7zip.
You need to navigate to the following directory of Python
By executing this, run the following configuration script in order to prepare your system for Python source code compilation
If you have issues running it, please run the below command to fix the permissions:
This shall perform many checks to ensure that all the dependencies are installed on the system. The -enable-optimization is used here to optimize the Python binary by executing many different tests. This sets various variables according to best practices identified by the Python community over the years.
Step 4: Finally, now install Python on Kali Linux
At this point you need to start with the build process by running the command mentioned below:
You shall modify –j in accordance with the cores of the processor. My own laptop has a quad-core so it will be -j4 for me.

As the build process is completed, you need to run altinstall in order to Install python binaries on Kali Linux:
Keep in mind to never use “make install” to install binaries as it will automatically overwrite the binary files.
Finished! Python has now been installed on Kali Linux. You can now check the version by running the command below if you want to verify it:
Similar Python installation articles:
Conclusion
This article covered extensively all the major instructions required to Install Python on Kali Linux. Python is without a doubt a very powerful scripting language but it still isn’t available or installed by default with operating systems, hence you have to manually install it.
Do let me know in the comments area below how easy you find the above and why you choose Python over any other language.