I have a configuration file located at /etc/ssh/sshd_config
that may or may not include a configuration line that sets PermitRootLogin
.
PermitRootLogin yes
My goal is to either change this value to something I know is correct (regardless of the current value), or to add the configuration line to the end of the file if the configuration value is not currently set in the file.
In other words, I would like a command line one-liner (or as few lines as possible) to do the following:
If a line that begins with PermitRootLogin
followed by a space or tab exists, replace the entire line with PermitRootLogin no
. Otherwise, add the line PermitRootLogin no
to the end of the file.
I want to this to work on the command line (Bash on Linux) so sed, awk, and grep can be used.
I know I can do half of my requirement (if it exists, replace it) with
sed -i 's/^PermitRootLogin[ \t].*$/PermitRootLogin no/' /etc/ssh/sshd_config
If this could be modified to add the line if there was no match, that would work for me.
sed,awk.grep - add a line to the end of a configuration section if the line doesn't already exist is close as well but does not fulfill my full requirement.
Edit: Maintaining the position of a set configuration variable in the file is important to me. The variables are defined in a certain logical order that is useful to human editors. Since this file may be edited by hand in the future, I want to maintain the order. A solution that simply deletes the configuration variable and adds it to the end does not fit my requirements. Thanks.
You can replace sed
bu this awk
:
awk '/^PermitRootLogin/ {
found=1;
sub(/^PermitRootLogin[[:blank:]]+.*$/, "PermitRootLogin no")
}
1;
END {
if (!found)
print "PermitRootLogin no"
}' file