5

I'd like to have a file on my computer that stores a particular token (rather than having them just exported to the shell env). As such, I'd like that the token can only be read by sudo, so access to it requires authorisation. How can I write a file that can only be read by sudo?

20

Note that sudo is not synonymous with root/superuser. In fact, sudo command let you execute commands as virtually any user, as specified by the security policy:

$ sudo whoami
root
$ sudo -u bob whoami
bob

I assume you meant to create a file that only root user can read:

# Create the file
touch file

# Change permissions of the file
# '600' means only owner has read and write permissions
chmod 600 file

# Change owner of the file
sudo chown root:root file

When you need to edit the content of the file:

# Replace 'nano' with your prefered editor
sudo nano file

See how only root can read the file:

$ cat file
cat: file: Permission denied
$ sudo cat file
foo bar baz
2

Figured it out:

echo 'hello world' > test
sudo chown root test
sudo chmod 600 test
sudo cat test

In another terminal, if you do it without sudo:

> cat test
cat: test: Permission denied
  • 2
    Why do you want the file to be executable by root? – Toby Speight Jul 13 '18 at 9:34
  • 1
    Consider instead applying chmod 600, if nothing else, it's more obvious what the purpose of your file is, when it's non-executable. – Adonalsium Jul 13 '18 at 13:01
  • Good point, updated – balupton Jul 17 '18 at 12:49
1

With tee

$ echo "some text" | sudo tee tmpfile
some text
$ sudo chmod 700 tmpfile 
$ cat tmpfile
cat: tmpfile: Permission non accordée
$ sudo cat tmpfile
some text

For append :

$ echo "text appened" | sudo tee -a tmpfile
$ sudo cat tmpfile
somme text
text appened
$ sudo rm tmpfile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.