#!/usr/bin/env python import os import sys import re usage = """ sshd_config.py old new Transfers defaults and custom rules from sshd_config file `old` to `new` `new` is based on a commented man page for sshd_config """ header = """ ## sshd_config, based on a commented sshd_config man page ## To output sshd_config man page as commented, detabbed plain text, ## man sshd_config | col -b | expand -t 4 | sed 's/^/# /' > sshd_config ## To display this file with comments and blank lines removed, ## egrep -v "^(#|$)" sshd_config ## If attempts at ssh fail with the error ## Permission denied (publickey,keyboard-interactive). ## then study the log on the host machine: ## sudo grep sshd /var/log/secure.log """ def get_args(count, usage): argv = sys.argv if len(argv) == count + 1: return argv[1:] else: print 'usage: %s %s' % (argv[0], usage) exit(0) fin, fon = get_args(2, usage) # read in old sshd_config file fi = open(fin) old = fi.readlines() fi.close() # read in man page for sshd_config fum = os.popen("man sshd_config | col -b | expand -t 4 | sed 's/^/# /'") man = fum.readlines() fum.close() # clean up mangled man page entries pat = r'^(# [A-Z]+[a-z][a-zA-Z]*)s{2,}(S.*)$' pat = re.compile(pat) new = list() for line in man: match = pat.search(line) if match: option, text = match.groups() new.append("%sn" % option) new.append("# %sn" % text) else: new.append(line) # make dictionary of option entries in man page pat = r'^# ([A-Z]+[a-z][a-zA-Z]*)$' pat = re.compile(pat) options = dict() for (index, line) in enumerate(new): match = pat.search(line) if match: option, = match.groups() options[option] = index # edit man page to insert option values pat = r'^(#)?([A-Z][a-z][a-zA-Z]+)s+(.*)$' pat = re.compile(pat) for line in old: match = pat.search(line) if match: hash, option, value = match.groups() if options.has_key(option): index = options[option] if hash: new[index] = '# %s %sn' % (option, value) else: new[index] += 'n%s %snn' % (option, value) else: print line # write out new sshd_config file fo = open(fon, mode='w') fo.writelines(header[1:]) fo.writelines(new) fo.close()