Python – Is `sudo pip install` Still a Broken Practice?

package-managementpermissionspippython

I'm new to Ubuntu, so please bear with me. I installed pip using this command: sudo apt-get -y install python-pip. Then I installed NLTK using the command on their website, which was: sudo pip install -U nltk. But then I stumbled on this question that says that everything I did was a "broken practice". The line that struck me the most was that using sudo pip is inherently wrong and that giving pip too much force could damage operating system files. Can anyone validate this claim?

Note – I only used sudo because when I tried the command apt-get -y install python-pip it gave me 2 errors:

E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?

Best Answer

Both sudo pip install and its other common variant sudo -H pip install should not be encouraged because it is a security risk to use root privileges to use pip to install Python packages from PyPI (Python Package Index).

From https://stackoverflow.com/a/21056000/486919 (emphasis mine):

When you run pip with sudo, you run setup.py with sudo. In other words, you run arbitrary Python code from the Internet as root. If someone puts up a malicious project on PyPI and you install it, you give an attacker root access to your machine. Prior to some recent fixes to pip and PyPI, an attacker could also run a man in the middle attack to inject their code when you download a trustworthy project.

As mentioned at https://security.stackexchange.com/a/79327/8761, it is important to note that anyone can upload Python packages, including malicious ones, to PyPI.

In short, in accordance with the principle of least privilege, don't use sudo with pip to install Python packages from PyPI unless you absolutely need to. Instead, consider using pip install --user (note that pip install with no sudo nor additional flags/options defaults to pip install --user on Ubuntu currently) or virtual environments (such as virtualenv). If you see people recommending sudo pip or sudo -H pip, please tell them not to.

Related Question