Как обновить python kali linux

Как обновить Python в Linux?

Руководство по обновлению Python в операционных системах семейства Linux.

Введение

Представь себе ситуацию, ты придумал какой-нибудь проект, решил реализовать его на Python, открываешь терминал и обнаруживаешь старую версию, например Python 3.4.

Правильно, обновить Python через пакетный менеджер.

Далее я расскажу как это сделать.

Все команды необходимо выполнять под пользователем root или же через sudo.

Обновление Python

Рассмотрим несколько примеров обновления Python в самых популярных дистрибутивах

Обновление Python в Debian Linux (Ubuntu, Raspbian, Mint и другие)

В моем случае я буду использовать raspberrypi 4 с дистрибутивом raspbian (основан на Debian buster). Открываем терминал (или подключаемся по ssh) и вводим команду apt update

Видим примерно такую же ситуацию, локальный репозиторий обновил информацию о доступным пакетах из сетевого репозитория и стали доступны обновления других пакетов. Но мы сейчас не об этом. Нас интересует только python.

Далее вводим команду

В моем дистрибутиве используется последняя доступная версия 3.7.3-1

Обновление Python в Red Hat Linux (CentOS и Fedora Linux)

В принципе обновление пакетов в linux имеет схожий алгоритм. Сперва вы получаете список доступных пакетов из удаленного репозитория и сравнивание с тем, что установлено у вас локально. После обновление локального репозитория нужно инициализировать установку python. Разнообразных дистрибутивов linux у меня под рукой нет, да и используя я в серверных вариантах только debian-based. Но информация о работе с другими пакетными менеджерами доступна онлайн:)

Обновление python выполняется одной командой

Заключение

В этом руководстве мы узнали как обновить Python в Linux.

Источник

Как обновить все пакеты Python в Kali Linux

В вашей системе Kali Linux полно устаревших пакетов Python. Вы можете убедиться в этом сами, для вывода пакетов Python 3, для которых выпущена новая версия:

Для вывода пакетов Python 2, для которых выпущена новая версия:

Чтобы обновить сразу все пакеты Python 3 в Kali Linux выполните команду:

Чтобы обновить сразу все пакеты Python 2 в Kali Linux выполните команду:

Ошибки pip при обновлении пакетов Python 3

Но если говорить точнее, то обновится большинство пакетов — некоторые не обновятся из-за разных ошибок и предупреждений.

Пример предупреждения, когда отсутствует необходимая зависимость:

python-debianbts 2.7.3 requires pysimplesoap!=1.16.2, which is not installed.

То есть пакету python-debianbts требуется pysimplesoap, который не установлен. Решение проблемы — просто устанавливаем отсутствующую зависимость командой вида:

Если проблема с пакетом для Python 2, то используем соответствующую версию pip:

Когда установите все зависимости, ещё раз запустите команду из первого сообщения для повторной установки пакетов, которые не смогли обновиться.

Пример другого предупреждения, в котором упоминается distutils:

Cannot uninstall ‘AdvancedHTTPServer’. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

В сообщении сказано, что не получается удалить AdvancedHTTPServer, поскольку он является частью установленного distutils и невозможно точно определить, какие файлы принадлежат ему.

Можно просто пропустить обновления этих пакетов — то есть ничего не делать.

При желании обновить и эти пакеты, то используйте опцию —ignore-installed в команде вида:

Например, для обновления AdvancedHTTPServer:

Если пакет предназначен для Python2, то используйте pip2:

Также у меня возникло несколько других ошибок, в основном при сборке пакетов из-за отсутствия необходимых файлов. Причина чаще всего в том, что не установлена необходимая зависимость (разные заголовки для компиляции). Такие ошибки нужно решать в индивидуальном порядке — смотреть, какого файла не хватает, искать какому пакету он принадлежит, устанавливать этот пакет и заново запускать обновление.

Например:

Говорит о том, что pkg-config не найден, устанавливаем его:

Источник

Как обновить python kali linux

Kali Linux fully switched to Python 3. This means that any tool packaged by Kali that was using Python 2 has been either dropped or converted to use Python 3. Any tool converted to Python 3 contains only scripts with /usr/bin/python3 as their shebang.

Concerning the packages that come straight from Debian, they did the same on most packages, but there are a few exceptions where packages are allowed to continue to rely on Python 2. However those packages have been updated so that all their scripts use /usr/bin/python2 as their shebang and so that they depend on the python2 binary package (instead of the former python ).

Thanks to those changes, Debian no longer need to provide /usr/bin/python and recent upgrades will effectively get rid of that symlink.

Unfortunately, when you download a Python script on the web, it will likely have /usr/bin/python as its shebang. If you try to execute it without fixing the shebang line, you will end up with an error like this one:

Читайте также:  Buffers in linux kernel

In Debian, you can reinstate the /usr/bin/python symlink by installing:

  • python-is-python2 if you want to have it point to python2
  • python-is-python3 if you want to have it point to python3

Keeping backwards compatibility in Kali

Given the large number of users that would not know how to avoid the above error, we decided that Kali would continue to ship Python 2 by default (as long as Debian still provides it) and that /usr/bin/python would point to it. We are also keeping a few common external modules (like requests ) so that random exploit scripts have a reasonable chance to run successfully.

Howewer, pip for Python2 (aka python-pip) is gone, /usr/bin/pip is the same as /usr/bin/pip3 and it will install modules for Python 3. See the FAQ below for more information.

This compatibility has been implemented by having kali-linux-headless recommend python2 , python-is-python2 and offsec-awae-python2 so that they are installed by default while being removable by users that would like to get rid of them.

To make users aware of this situation, we are displaying a promiment message on login:

The hope is that they will read this article and know how do deal with the various issues that they will encounter.

Frequently Asked Questions

I have downloaded a Python script, what should I do?

You need to inspect its shebang line. The shebang line is the first line of a script and it starts with #! followed by the path of the interpreter that will be used to execute the script.

If the interpreter is /usr/bin/python , you should read the documentation to see whether the script can run with Python 3. If yes, then you should update the shebang line to point to /usr/bin/python3 . Otherwise you should update it to point to /usr/bin/python2 .

Good shebang lines that can be kept:

  • #!/usr/bin/python3
  • #!/usr/bin/python2
  • #!/usr/bin/env python3
  • #!/usr/bin/env python2

Bad shebang lines that need to be updated:

How can I get rid of the login message?

The message will only be displayed as long as /usr/bin/python points to the deprecated Python 2. Now that you know about this situation and that you know how to fix the shebang line of old scripts, you can safely get rid of /usr/bin/python :

Or you can decide to make it point to Python 3:

Either of those actions will get rid of the login message.

Alternatively, if you want to keep /usr/bin/python pointing to python2 and you still want to disable the message, you can do this:

I have a Python 2 script that doesn’t run, what should I do?

If your Python 2 script uses modules that are not among those that we ship in the offsec-awae-python2 compatibility package (see list here), then you can try pyenv to setup a fully isolated Python 2 environment where you can use pip to install supplementary modules. See our Using EoL Python versions on Kali article.

I want pip for Python 2, how can I get it back?

I wrote a Python script, what should I do?

Be nice with end users:

  • document clearly whether your code runs with Python 3 or Python 2
  • use /usr/bin/python3 or /usr/bin/python2 as the shebang line, it’s more expressive than /usr/bin/python and is more likely to have the desired result
  • update it for Python 3 compatibility if that’s not the case yet

Updated on: 2021-Sep-27
Author: rhertzog

Источник

linux-notes.org

В данной теме я расскажу как можно обновить Python до последней версии или как скомпилировать python из исходников. Все покажу и расскажу на примере, недавно столкнулся с такой проблемкой.

Перейдем в папку в которую мы скачаем сами исходники программы.

ВНИМАНИЕ! Очень важно, чтобы вы использовали «make altinstall», собираете свою собственную версию Python. Если вы используете обычную «make install» установку, вы получите две разные версии Python в файловой системе с именем python. Это может привести к проблемам, которые очень трудно диагностировать!

Установить PYTHON 2.6

Качаем и собираем питон:

Распаковываем архив с исходниками для нашего питона:

Установим дополнительные утилиты:

Собственно, сконфигурируем наш питон, я сделал вот так ( кому не понравилось, читаем help, man):

Собираем уже сконфигурированный питон:

Сделаем линковку для удобного использования:

Чтобы проверить версию питона выполните:

Сейчас версия питона 2.6 запускается из python2.6

Установим питон с использованием easy_install, который упрощает установку.
Переходим в директорию и качаем этот скрипт для установки:

Запускаем его на выполнение:

Делаем символическую ссылку как и делали мы раньше

Для помощи вызовите:

PS: если у вас в системе имеется python2.6 и вы хотите его обновить, то можно использовать следующий метод.

После чего, будите иметь питон 2.7.

Установить PYTHON 2.7

Сейчас покажу как установить еще питон с версией 2.7, но для начала установим для них дополнительное ПО:

С самого начала скачаем сами исходники с питоном, для версии питона с 2.7 качаем:
только перейдем в нужный каталог:

И для распаковки данного архива выполните:

Переходим в директорию и сконфигурируем питон и выполним установку (компиляцию):

Очень удобным является использования файлового менеджера для пакетов такого как pip и менеджера среды, такого как virtualenv:

Установить PYTHON 3.4

Ставим необходимое ПО:

Делаем все тоже самое и для другой версии питона- 3.4.1:

Так как сам архив сжат с помощью утилиты и у него расширение стоит xz, то необходимо загрузить и после чего установить дополнительный софт для этого:

Расшифровуем архив и потом распаковываем:

Переходим в директорию и сконфигурируем наш конфиг:

Читайте также:  Как установить ultraiso для windows 10

Собираем все это добро.

На этом компиляция завершена.

Установить PYTHON 3.5

Ставим необходимое ПО.

И для распаковки данного архива выполните:

Переходим в директорию и сконфигурируем питон и выполним установку (компиляцию):

Установить PYTHON 3.6

Ставим необходимое ПО.

И для распаковки данного архива выполните:

Переходим в директорию и сконфигурируем питон и выполним установку (компиляцию):

Можно немного поднастроить наш питон.

Например чтобы иметь доступ к питону который мы только что установили и не указывать каждый раз ему путь в папку где он лежит, то можно воспользоваться переменной PATH и указать путь ( прописать его):
Например команда выглядит так: export PATH=»[/path/to/installation]:$PATH»

Для себя я делал вот так:

После установки самого питон, можно установить еще некоторые утилиты:

Вот собственно и все, завершил я свою данную тему «Обновить Python до последней версии или как скомпилировать python из исходников».

Источник

Ethical hacking and penetration testing

InfoSec, IT, Kali Linux, BlackArch

How to upgrade all Python packages in Kali Linux

Your Kali Linux system is full of obsolete Python packages. You can verify this, in order to display Python 3 packages for which a new version has been released:

To display Python 2 packages for which a new version has been released:

To upgrade all Python 3 packages at once in Kali Linux, run the following command:

To upgrade all Python 2 packages at once in Kali Linux, run the following command:

pip errors when upgrading Python 3 packages

But more precisely, most packages will be updated – some will not be updated due to various errors and warnings.

An example of a warning when the necessary dependency is missing:

That is, the python-debianbts package requires pysimplesoap, which is not installed. Solving the problem – just install the missing dependency with a command like this:

If the problem is with the package for Python 2, then use the appropriate version of pip:

When install all dependencies, run the command to update all packages again to reinstall packages that could not be updated.

An example of another warning in which distutils is mentioned:

The message says that you cannot delete the AdvancedHTTPServer, because it is part of the installed distutils and it is impossible to determine exactly which files belong to it.

You can simply skip the updates of these packages – that is, do nothing.

If you wish to upgrade these packages, use the —ignore-installed option in the command:

For example, to update AdvancedHTTPServer:

If the package is for Python2, then use pip2:

I also had several other errors, mainly when building packages due to the lack of necessary files. The reason most often is that the necessary dependency is not installed (different headers for compilation). Such errors need to be solved individually – look at which file is missing, look for which package it belongs to, install this package and re-launch the update.

says that pkg-config is not found, install it:

says that the cups/cups.h file is missing, this file is in the libcups2-dev package, install it:

Error ‘fatal error: libsmbclient.h: no such file or folder‘:

You need to install the libsmbclient-dev package that contains the required libsmbclient.h file.

Error Message ‘No package ‘cairo’ found’:

To solve the problem, install the packages:

Error ‘OSError: mysql_config not found’:

pip errors when upgrading Python 2 packages

Error ‘EnvironmentError: mysql_config not found’:

To solve it, install default-libmysqlclient-dev:

Error ‘fatal error: pcap.h: no such file’:

Its reason is that the pcap.h file was not found, this file is contained in the libpcap-dev package. And to solve this problem you need to install this package.

Error ‘Could not run curl-config: [Errno 2] No such file or directory’:

To solve it, install the packages:

Error ‘possibly undefined macro: AC_PROG_LIBTOOL’:

Error ‘fatal error: sqlite3.h: no such file or folder’:

To fix it, install the package:

Error ‘No package ‘gtk+-3.0’ found’:

To fix it, install the following packages:

The message ‘You are using pip version …, however version … is available.’

If using pip3 and pip2, messages like this occur:

That means you need to update the version of pip itself.

To update pip3:

To update pip2

  • Kali Linux post-installation tips and settings (100%)
  • How to install Python and PIP on Windows 10. How to set up Python as a web server module (59.2%)
  • How to update Kali Linux (50.9%)
  • How to replace Default Desktop Environment with Cinnamon in Kali Linux (50.9%)
  • How to configure Kali Linux to use a static IP address (50.9%)
  • How to use PsExec tools to run commands and manage remote Windows systems (RANDOM — 10%)

13 Comments to How to upgrade all Python packages in Kali Linux

guy this aint useful to a newbie in kali linux my advise is that you make a revised edition on this post

If ones do not know for what to upgrade Python packages, just skip this note. This tutorial is just not intended for newbie.

dirhunt
Traceback (most recent call last):
File «/usr/local/bin/dirhunt», line 6, in
from pkg_resources import load_entry_point
File «/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py», line 3250, in
@_call_aside
File «/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py», line 3234, in _call_aside
f(*args, **kwargs)
File «/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py», line 3263, in _initialize_master_working_set
working_set = WorkingSet._build_master()
File «/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py», line 583, in _build_master
ws.require(__requires__)
File «/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py», line 900, in require
needed = self.resolve(parse_requirements(requirements))
File «/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py», line 786, in resolve
raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The ‘maxminddb>=1.5.2’ distribution was not found and is required by geoip2

Читайте также:  Не гаснет клавиатура после выключения компьютера windows 10

TypeError: coercing to Unicode: need string or buffer, int found

Any clue about this error? I am trying to update python in Kali linux installed on windows 10

What commands do you run to get these errors?

Your question is not relevant to this article, you have problems caused by an interrupted installation/update or another reason that did not allow the package installation to complete correctly.

Pay attention to the line:

To fix, try the command:

You can ask other questions related to installing and updating packages in the comments to this article.

─# apt install -f -y
Reading package lists… Done
Building dependency tree
Reading state information… Done
The following packages were automatically installed and are no longer required:
libllvm10 libperl5.30 libpython3.8 libpython3.8-dev libre2-8 libxcb-util0 perl-modules-5.30 python3.8-dev
Use ‘apt autoremove’ to remove them.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
602 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Setting up python3 (3.9.0-4) …
running python rtupdate hooks for python3.9…
/usr/share/legion/ui/models/cvemodels.py:55: SyntaxWarning: «is not» with a literal. Did you mean «!=»?
if not len(self.__cves) is 0:
/usr/share/legion/ui/models/hostmodels.py:43: SyntaxWarning: «is not» with a literal. Did you mean «!=»?
if not len(self.__hosts) is 0:
/usr/share/legion/ui/models/processmodels.py:43: SyntaxWarning: «is not» with a literal. Did you mean «!=»?
if not len(self.__processes) is 0:
/usr/share/legion/ui/models/scriptmodels.py:44: SyntaxWarning: «is not» with a literal. Did you mean «!=»?
if not len(self.__scripts) is 0:
/usr/share/legion/ui/models/servicemodels.py:40: SyntaxWarning: «is not» with a literal. Did you mean «!=»?
if not len(self.__services) is 0:
/usr/share/legion/ui/models/servicemodels.py:184: SyntaxWarning: «is not» with a literal. Did you mean «!=»?
if not len(self.__serviceNames) is 0:
/usr/share/responder/settings.py:209: SyntaxWarning: «is not» with a literal. Did you mean «!=»?
if len(self.NumChal) is not 16 and not «random»:
/usr/share/responder/tools/MultiRelay.py:418: SyntaxWarning: «is not» with a literal. Did you mean «!=»?
if data.find(«NTLM») is not -1:
/usr/share/responder/tools/MultiRelay.py:423: SyntaxWarning: «is not» with a literal. Did you mean «!=»?
if data.find(«NTLM») is not -1:
/usr/share/responder/tools/RunFingerPackets.py:14: SyntaxWarning: «is» with a literal. Did you mean «==»?
if PY2OR3 is «PY2»:
[Errno 2] No such file or directory: ‘/usr/share/set/src/payloads/set_payloads/multi_pyinjector.py’
[Errno 2] No such file or directory: ‘/usr/share/set/src/payloads/set_payloads/pyinjector_args.py’
[Errno 2] No such file or directory: ‘/usr/share/set/src/payloads/set_payloads/shell.py’
error running python rtupdate hook set
[Errno 2] No such file or directory: ‘/usr/share/unicorn-magic/unicorn.py’
error running python rtupdate hook unicorn-magic
dpkg: error processing package python3 (—configure):
installed python3 package post-installation script subprocess returned error exit status 4
dpkg: dependency problems prevent configuration of python3-adblockparser:
python3-adblockparser depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-adblockparser (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of python3-pyppeteer:
python3-pyppeteer depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-pyppeteer (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of king-phisher:
king-phisher depends on python3; however:
Package python3 is not configured yet.

dpkg: error processing package king-phisher (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of python3-nbformat:
python3-nbformat depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-nbformat (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of python3-sortedcontainers:
python3-sortedcontainers depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-sortedcontainers (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of python3-tables:
python3-tables depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-tables (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of python3-gitdb:
python3-gitdb depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-gitdb (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of dnschef:
dnschef depends on python3; however:
Package python3 is not configured yet.

dpkg: error processing package dnschef (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of python3-zipp:
python3-zipp depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-zipp (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of python3-opengl:
python3-opengl depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-opengl (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of python3-click:
python3-click depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-click (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of weevely:
weevely depends on python3; however:
Package python3 is not configured yet.

dpkg: error processing package weevely (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of python3-asysocks:
python3-asysocks depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-asysocks (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of python3-aioconsole:
python3-aioconsole depends on python3:any; however:
Package python3 is not configured yet.

dpkg: error processing package python3-aioconsole (—configure):
dependency problems — leaving unconfigured
dpkg: dependency problems prevent configuration of sparta-scripts:
E: Sub-process /usr/bin/dpkg returned an error code (1)
┌──(root💀DESKTOP-NF4O0MG)-[

Do you have any idea about below files like which package it belongs to

[Errno 2] No such file or directory: ‘/usr/share/set/src/payloads/set_payloads/multi_pyinjector.py’
[Errno 2] No such file or directory: ‘/usr/share/set/src/payloads/set_payloads/pyinjector_args.py’
[Errno 2] No such file or directory: ‘/usr/share/set/src/payloads/set_payloads/shell.py’

They belong to the ‘set’ package.

What did you do with your system to get this state?

Источник

Оцените статью