User Tools

Site Tools


ssh_key_management

SSH Key Management

Trying to automate key Management between Machines.
It is controlled from Database. <note warning> Strictly ALPHA should not work or might kill your file </note>

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 13 10:08:10 2012
 
This script used to manage and manipulate .ssh/authorized_keys
User home directory defined based on /etc/passwd and /etc/shadow
 
@author: k2patel
"""
 
import pwd
import fileinput
import subprocess
## Customization Start
 
pg_user = 'sshd'
pg_pass = 'testing'
pg_host = 'localhost'
username = 'k2patel'
 
 
## Customization End
 
def getdir( username ):
    user_info = pwd.getpwnam(username).pw_dir
    return user_info
 
#strmatch = open(getdir('k2patel') + "/.ssh/match")
for k in open(getdir('k2patel') + "/.ssh/match"):
    jusths = k.split()
    if jusths[0] == 'ssh-rsa':
        print jusths[1]
    else:
        print "Key Type MisMatch"
 
#allkeys = open(getdir('k2patel') + "/.ssh/authorized_keys.BK")
#fl = getdir('k2patel') + "/.ssh/authorized_keys.BK"
#print fl
 
try:
    for ukeys in fileinput.input(getdir('k2patel') + "/.ssh/authorized_keys.BK", inplace=0):
        nice = ukeys.split()
#        if jusths[1] is nice[1]:
#            print fileinput.lineno()
        if nice[0] == 'ssh-rsa':
#            print "Hash : " + nice[1]
            if jusths[1] == nice[1]:
                print "it is matching at " + str(fileinput.filelineno())
                Player = file(getdir('k2patel') + "/.ssh/authorized_keys.BK", "r").readlines()
                del Player[fileinput.filelineno()-1]
                Player.append(jusths[0] + " " + jusths[1] + " " + username + "\n" )
                file(getdir('k2patel') + "/.ssh/authorized_keys.BK", "w").writelines(Player)
        else:
            print "Key Type failed to match"
 
    fileinput.close()
except subprocess.CalledProcessError as prit:
    print str(prit)
 
ssh_key_management.txt · Last modified: 2012/04/13 16:31 by k2patel