1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
#
# Copyright 2009 Martin Owens
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
"""
Lists local ssh public keys
"""
import os
import logging
import commands
import glob
SSH_DIR = os.path.expanduser('~/.ssh/')
KNOWN_HOSTS = os.path.join(SSH_DIR, 'known_hosts')
def list_pubkeys():
"""Lists all available public keys"""
result = []
for pub_file in glob.glob(os.path.join(SSH_DIR, '*.pub')):
fhl = open(pub_file, "r")
result.append(fhl.readline().replace("\n",'').replace("\r",''))
fhl.close()
return result
def compare_pubkeys(find_key):
"""Compares a public key to the local stored keys"""
find_key = find_key.replace("\n",'').replace("\r",'')
# Select the middle part of the ssh key
if ' ' not in find_key:
return False
find_key = find_key.split(' ')[1]
for key in list_pubkeys():
if find_key in key:
return True
return False
def generate_key_file(tag):
"""Generates a filename in the .ssh directory"""
filename = os.path.join(SSH_DIR, "%s_id_rsa" % tag)
logging.debug("Making new SSH filename: %s" % filename)
return filename
def generate_key(filename, password, comment=None):
"""Generate a new ssh key (rsa by default)"""
logging.debug("Creating keygen SSH command")
com = "ssh-keygen -t rsa -N '%s' -f '%s' -C '%s' -q" % (
password, filename, comment)
logging.debug(com)
commands.getoutput(com)
logging.debug("Keys hopefully generated!")
return os.path.exists(filename)
def add_server_key(server):
"""Adds a fingerprint of a server to known_hosts"""
com = "ssh-keyscan -H %s" % server
fap = commands.getoutput(com).split('\n')[-1]
if os.path.exists(KNOWN_HOSTS):
fhl = open(KNOWN_HOSTS, 'r')
cont = fhl.read()
fhl.close()
part = fap.split(' ')[-1]
if part in cont:
logging.debug("Server '%s' already known." % server)
return
elif not os.path.exists(SSH_DIR):
os.mkdir(SSH_DIR)
logging.debug("Server '%s' is unknown - adding to known_hosts." % server)
fhl = open(KNOWN_HOSTS, 'a')
fhl.write(fap+'\n')
fhl.close()
|