Modify the config variable or add it if it doesn't exist using sed / awk / grep

I have a config file located at /etc/ssh/sshd_config

which may or may not include a config line that sets PermitRootLogin

.

PermitRootLogin yes

      

My goal is to either change this value to what I know is correct (regardless of the current value), or add a config line to the end of the file if no config value is currently set in the file.

In other words, I would like a one-line (one-shot) command line line (or as few lines as possible) to do the following:

If there is a line that begins with a PermitRootLogin

space or tab, replace the entire line with PermitRootLogin no

. Otherwise, add a line PermitRootLogin no

to the end of the file.

I want this to work on the command line (Bash on Linux) so sed, awk and grep can be used.

I know I can fulfill 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 changed to add a line if there was no match, that would work for me.

sed, awk.grep - add a line to the end of the config section if the line doesn't already exist , also close, but doesn't fulfill my full requirement.


Edit: It is important for me to keep the position of the given config variable. Variables are defined in a certain logical order, which is useful for editors. Since this file may be manually edited in the future, I want to save the order. A solution that just removes the config variable and adds it all the way down doesn't fit my requirements. Thank.

+3


source to share


2 answers


You can replace sed

bu with awk

:



awk '/^PermitRootLogin/ {
   found=1;
   sub(/^PermitRootLogin[[:blank:]]+.*$/, "PermitRootLogin no")
}
1; 
END {
   if (!found)
      print "PermitRootLogin no"
}' file

      

+1


source


This can be done with sed

:

Typically, these conf files do not have strict parameter sequence requirements. At least it sshd_config

doesn't have such a requirement.

So this one sed

should work fine:

sed '/PermitRootLogin/d; ${p;s/.*/PermitRootLogin yes/}' /etc/ssh/sshd_config

      



If you want to keep the line position in the file, use the command below.

sed '1{p;s/.*/PermitRootLogin yes/;h;d;};/^PermitRootLogin/{g;p;s/.*//;h;d;};$G' /etc/ssh/sshd_config

      

Once you are satisfied with the result, add a flag -i

to the sed command to perform the in-place replacement.

+1


source







All Articles