sshwot/src/main-export-known-hosts.py

83 lines
2.4 KiB
Python

import argparse
import os
import sys
import process_known_hosts
import write_file
def main():
# TODO: Provide a way to add comments
parser = argparse.ArgumentParser(
description = """Export .ssh/known_hosts as a sshwot file.
By default the output is written to stdout.""",
# We want to provide help on --help, but the default thing
# also adds -h, which we don't want
add_help = False
)
# --help to get help
parser.add_argument('--help',
action = 'help',
help = 'show this help message and exit'
)
# -i and --include-ips can be used to not ignore the IPs in the file
parser.add_argument('-i', '--include-ips',
# We store a constant into a property depending on whether
# this argument is used or not
action = 'store_const',
# The property is ignore_ips (to match the argument of
# process_known_hosts.process_file()). Store False if this
# switch is used and True otherwise
dest = 'ignore_ips', const = False, default = True,
help = 'includes IPs in addition to domain names'
)
# -o can be used to write the .sshwot thing to a file instead of stdout
parser.add_argument('-o',
# Given one argument, we open a file of that name and store it
# to outfile, which will be sys.stdout.buffer otherwise.
# We use .buffer since we're going to write binary data
action = 'store',
dest = 'outfile',
type = argparse.FileType('wb'),
default = sys.stdout.buffer,
# This is what will be displayed in the help after -o
metavar = 'outfile',
help = 'write the sshwot file to a given file instead of the stdout'
)
try:
homedir = os.environ['HOME']
except KeyError as err:
raise KeyError('$HOME is not set') from err
# The input file
# Default to ~/.ssh/known_hosts
parser.add_argument('infile',
nargs = '?',
default = os.path.join(homedir, '.ssh/known_hosts'),
help = 'a file in .ssh/known_hosts format'
)
# This automatically parses the command line args for us. If it
# returns, we have correct arguments
args = parser.parse_args()
with open(args.infile, 'r') as f:
known_host_entries = process_known_hosts.process_file(f, args.ignore_ips)
# Convert to the entry format for .sshwot files
entries = []
for known_hosts_entry in known_host_entries:
entries.append(process_known_hosts.known_hosts_to_entry(known_hosts_entry))
write_file.write(args.outfile, entries)
if __name__ == '__main__':
try:
main()
except Exception as err:
print('Error: %s' % err, file=sys.stderr)
sys.exit(1)