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?
3 Answers
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
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
-
1Consider instead applying chmod 600, if nothing else, it's more obvious what the purpose of your file is, when it's non-executable. Jul 13, 2018 at 13:01
-
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
chmod
, andchown
)