@cyrus:
My current script looks like this:
#!/bin/bash
touch /tmp/sshd_config
while read -r line || [[ -n "$line" ]]; do
if [ "$line" = "PermitRootLogin yes" ]; then
match=1
echo "PermitRootLogin no" >> /tmp/sshd_config
else
echo "$line" >> /tmp/sshd_config
fi
done < /etc/ssh/sshd_config
if [ "$match" != "1" ]; then
echo "PermitRootLogin no" >> /tmp/sshd_config
fi
It works, but it looks poor. I'd prefer a more \s+ 'ish style to catch "PermitRootLogin(manySpaces)yes" and "PermitRootLogin(tabTabTab)yes" lines. An approach using 'grep' would definitely be nicer.
To anybody else who has answered so far and mentioned sed and awk: There are three caveats in your proposals.
1: I, as I am not the maintainer of the distro, cannot guarantee that one or both will be installed.
2: I don't know if people who want to modify my scripts are sed and/or awk cracks.
3: I can guarantee that, except of the fact that sed and awk are magnificent, awesome, elegant tools to deal with such stuff, I have absolutely no knowledge when it comes to sed and awk. And yes, this is a humiliating gap.
=========
Post scriptum...
After playing around a bit and finding one ugly caveat in the original script, here is my current version:
#!/bin/bash
INFILE=/etc/ssh/sshd_config
TMPFILE=/var/tmp/sshd_config
touch $TMPFILE
while read -r line || [[ -n "$line" ]]; do
if [ `echo "$line" | grep -c -P "^\s*PermitRootLogin\s+"` = "1" ]; then
match=1
echo "PermitRootLogin no" >> $TMPFILE
else
echo "$line" >> $TMPFILE
fi
done < $INFILE
if [ "$match" != "1" ]; then
echo "" >> $TMPFILE
echo "# Do not permit root to log in directly" >> $TMPFILE
echo "PermitRootLogin no" >> $TMPFILE
fi
cp -f $TMPFILE $INFILE
sync
The difference to the old version is, at first sight, the change from the simple comparison to grep, but the pcre is indeed neccessary. If a future distro comes with "PermitRootLogin no", the former version will add an at least unneccessary entry to the config. Another nifty thing is that the config file, at another line, contains "PermitRootLogin yes" within a comment. A simple grep -c -P "PermitRootLogin\s+yes" would match there (again).
The new version still looks clumsy and ugly, but it works :)