Is there a more DRY way to write the following commands (will be putting them in a bash shell script):
sudo sed -i 's/^#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sudo sed -i 's/^#PermitEmptyPasswords yes/PermitEmptyPasswords no/' /etc/ssh/sshd_config
sudo sed -i 's/PermitEmptyPasswords yes/PermitEmptyPasswords no/' /etc/ssh/sshd_config
sudo sed -i 's/^#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/^#X11Forwarding yes/X11Forwarding no/' /etc/ssh/sshd_config
sudo sed -i 's/X11Forwarding yes/X11Forwarding no/' /etc/ssh/sshd_config
Since the patterns to be matched are similar, you could make use of alternation for the 4 strings and capture it. Make the #
at the beginning of the string optional.
The following would combine those into one:
sed -i -r 's/^#?(PermitRootLogin|PermitEmptyPasswords|PasswordAuthentication|X11Forwarding) yes/\1 no/' /etc/ssh/sshd_config
If your version of sed
doesn't support extended regular expressions, you could say:
sed -i 's/^#\{0,1\}\(PermitRootLogin\|PermitEmptyPasswords\|PasswordAuthentication\|X11Forwarding\) yes/\1 no/' /etc/ssh/sshd_config
Either use multiple -e 'sed-command'
arguments in a single invocation of sed
:
sudo sed -i.bak \
-e 's/^#PermitRootLogin yes/PermitRootLogin no/' \
-e 's/PermitRootLogin yes/PermitRootLogin no/' \
-e 's/^#PermitEmptyPasswords yes/PermitEmptyPasswords no/' \
-e 's/PermitEmptyPasswords yes/PermitEmptyPasswords no/' \
-e 's/^#PasswordAuthentication yes/PasswordAuthentication no/' \
-e 's/PasswordAuthentication yes/PasswordAuthentication no/' \
-e 's/^#X11Forwarding yes/X11Forwarding no/' \
-e 's/X11Forwarding yes/X11Forwarding no/' \
/etc/ssh/sshd_config
Or create a script file, sed.script
, containing the commands:
s/^#PermitRootLogin yes/PermitRootLogin no/
s/PermitRootLogin yes/PermitRootLogin no/
s/^#PermitEmptyPasswords yes/PermitEmptyPasswords no/
s/PermitEmptyPasswords yes/PermitEmptyPasswords no/
s/^#PasswordAuthentication yes/PasswordAuthentication no/
s/PasswordAuthentication yes/PasswordAuthentication no/
s/^#X11Forwarding yes/X11Forwarding no/
s/X11Forwarding yes/X11Forwarding no/
and then run sed
with that file:
sudo sed -i.bak -f sed.script /etc/ssh/sshconfig
I've added a backup extension to the -i
option. You're a braver man than I am if you edit major configuration files without making a backup copy first! (It's also necessary if you work on Mac OS X or BSD; the sed
there requires an extension with -i
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With