Piping Data When Not Running a Command with sudo

From a security standpoint, you should avoid running everything with sudo, as it increases the risk of you accidentally wiping your machine, or a malicious script compromising your machine.

But this can be a real pain, for instance if you need to write to protected file(s).

The solution here is to use the tee command, and make sure that only tee is run as root. A huge benefit of using tee, too, is that it'll render the output both to the file specified, and to stdout, so you have a chance to see if there's anything suspicious being output.

For instance, I used to run this setup to set up my Arch Linux package mirrors:

curl -s 'https://www.archlinux.org/mirrorlist/?country=GB&protocol=http&protocol=https&ip_version=4&use_mirror_status=on' \
       | sed 's/^#//' \
       | sudo tee /etc/pacman.d/mirrorlist

This means that only the very end of the command is run as root, so any other remote code executions are less likely to cause massive damage to the system.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

Tags

This post was filed under articles.

This post is part of the series nablopomo-2019.

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.