Changeset - 377168866077
[Not reviewed]
0 1 0
Lance Edgar - 5 years ago 2019-08-10 02:41:26
ledgar@techsupport.coop
Add `ssh.set_config()` convenience function
1 file changed with 21 insertions and 18 deletions:
0 comments (0 inline, 0 general) First comment
rattail_fabric2/ssh.py
Show inline comments
 
@@ -47,24 +47,27 @@ def configure(c, allow_root=False):
 
    """
 
    Configure the OpenSSH service
 
    """
 
    path = '/etc/ssh/sshd_config'
 
    set_config(c, 'PermitRootLogin', 'without-password' if allow_root else 'no')
 
    set_config(c, 'PasswordAuthentication', 'no')
 
    restart(c)
 

	
 
    # PermitRootLogin no (or without-password)
 
    # TODO: this probably needs the same treatment as PasswordAuthentication got
 
    if c.run("grep '^PermitRootLogin ' {}".format(path), warn=True).failed:
 
        c.sudo('sed -i.bak -e "s/^#PermitRootLogin .*/PermitRootLogin {}/" {}'.format(
 
            'without-password' if allow_root else 'no', path))
 
    else:
 
        c.sudo('sed -i.bak -e "s/^PermitRootLogin .*/PermitRootLogin {}/" {}'.format(
 
            'without-password' if allow_root else 'no', path))
 

	
 
    # PasswordAuthentication no
 
    if c.run("grep '^PasswordAuthentication ' {}".format(path), warn=True).failed:
 
        if c.run("grep '^#PasswordAuthentication ' {}".format(path), warn=True).failed:
 
            c.sudo("""bash -c 'echo "PasswordAuthentication no" >> /etc/ssh/sshd_config'""")
 
        else:
 
            c.sudo("sed -i.bak -e 's/^#PasswordAuthentication .*/PasswordAuthentication no/' {}".format(path))
 
    else:
 
        c.sudo("sed -i.bak -e 's/^PasswordAuthentication .*/PasswordAuthentication no/' {}".format(path))
 
def set_config(c, setting, value, path='/etc/ssh/sshd_config'):
 
    """
 
    Configure the given SSH setting with the given value.
 
    """
 
    # first check if the setting is already defined
 
    if c.run("grep '^{} ' {}".format(setting, path), warn=True).failed:
 

	
 
    restart(c)
 
        # nope, not yet defined.  maybe we can uncomment a definition?
 
        # (note, this looks only for '#Foo' and not '# Foo' for instance)
 
        if c.run("grep '^#{} ' {}".format(setting, path), warn=True).failed:
 

	
 
            # nope, must tack on a new definition at end of file
 
            c.sudo("""bash -c 'echo "{} {}" >> {}'""".format(setting, value, path))
 

	
 
        else: # yep, uncomment existing definition, but also overwrite
 
            c.sudo("sed -i .bak -e 's/^#{0} .*/{0} {1}/' {2}".format(setting, value, path))
 

	
 
    else: # setting is defined, so overwrite it
 
        c.sudo("sed -i.bak -e 's/^{0} .*/{0} {1}/' {2}".format(setting, value, path))
0 comments (0 inline, 0 general) First comment
You need to be logged in to comment. Login now