Home > Blockchain >  Modify protected file with bash alias [duplicate]
Modify protected file with bash alias [duplicate]

Time:09-21

I have the following alias in my .bashrc file,

alias genpass="tr -dc A-Za-z0-9 </dev/urandom | head -c 13 ; echo ''"
alias savepass='echo "$1: $(genpass)" >> .secret'
alias getlastpass='tail .secret -n 1

the intention of this alias is to generate a password and later being able to retrieve the last one. I'm storing the passwords in a file called .secret with the following permissions,

-rw------- 1 root root 92 Sep 17 12:48 .secret

so in a way that only root user can read and write the file.

So the problem that I'm facing here is the following one, when I try to run

sudo savepass

is returning me

bash: .secret: Permission denied

Which I assume is because when this alias is not been executed as root, which is the owner of this file.

I don't know how to solve this, so any help is welcome, and any criticism related to this form of storing password is also welcome. My final goal is to be able to store password from the terminal and be able to retrieve it later, in a save way. If you know a better way to do this, just let me know, it will also be a valid answer. Just keep in mind that I want to do this from the terminal without installing any fancy program, just bash script.

CodePudding user response:

If your unprivileged user can alter the file, why do you store it with root permissions? This does not give you any benefit. Store the file with the user id of the user who needs to read and write it and stop using sudo.

The problem in your solution is, that echo is run with root permissions. But the redirection is still done by the shell running the sudo. And that shell does not have root permissions.

If you still want to keep your approach, you have to run tee -a by sudo. For this you have to put the sudo in the alias. But now it might be better to write a function instead of an alias.

savepass () {
  echo "$1: $(genpass)" | sudo tee -a .secret
}

Btw: if you want to store your passwords in clear text files, use the netrc syntax, used by other tools, too.

  • Related