From 3b86aa2dbaac08d555118babf80197ae8da6daa8 Mon Sep 17 00:00:00 2001 From: Shekhar Date: Tue, 26 Mar 2013 21:03:40 +0530 Subject: [PATCH] - new ssh_unauthorize function - added test for ssh_unauthorize - improved ssh_authorize test (was a TODO) XX Wanted to use file_update but it failed for one of the ssh keys we use so used simpler get/put instead --- src/cuisine.py | 24 +++++++++++++++++++++++- tests/all.py | 17 ++++++++++++++--- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/src/cuisine.py b/src/cuisine.py index 3af8564..de42bd8 100644 --- a/src/cuisine.py +++ b/src/cuisine.py @@ -40,7 +40,8 @@ """ from __future__ import with_statement -import base64, hashlib, os, re, string, tempfile, subprocess, types, functools, StringIO +import base64, hashlib, os, re, string, tempfile, subprocess, types +import tempfile, functools, StringIO import fabric, fabric.api, fabric.operations, fabric.context_managers VERSION = "0.5.6" @@ -1174,6 +1175,27 @@ def ssh_authorize(user, key): file_write(keyf, key, owner=user, group=group, mode="600") return False +def ssh_unauthorize(user, key): + """Removes the given key to the '.ssh/authorized_keys' for the given + user.""" + d = user_check(user, need_passwd=False) + group = d["gid"] + keyf = d["home"] + "/.ssh/authorized_keys" + if file_exists(keyf): + tmpfile = tempfile.NamedTemporaryFile() + fabric.operations.get(keyf, tmpfile.name) + keys = [line.strip() for line in tmpfile] + tmpfile.close() + if key in keys: + tmpfile = tempfile.NamedTemporaryFile() + keys.remove(key) + content = '\n'.join(keys) + '\n' + tmpfile.write(content) + tmpfile.flush() + fabric.operations.put(tmpfile.name, keyf, mode=0600) + tmpfile.close() + return True + # ============================================================================= # # UPSTART diff --git a/tests/all.py b/tests/all.py index b53c272..d3c30d4 100644 --- a/tests/all.py +++ b/tests/all.py @@ -221,6 +221,8 @@ def testInstall( self ): class SSHKeys(unittest.TestCase): + key = "ssh-dss XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX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XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX= user@cuisine""" - cuisine.ssh_authorize(USER, key) - # FIXME: Should check that the key is present, and only one + cuisine.ssh_authorize(USER, self.key) + d = cuisine.user_check(USER, need_passwd=False) + keyf = d["home"] + "/.ssh/authorized_keys" + keys = [line.strip() for line in open(keyf)] + assert keys.count(self.key) == 1 + + def testUnauthorize( self ): + cuisine.ssh_unauthorize(USER, self.key) + d = cuisine.user_check(USER, need_passwd=False) + keyf = d["home"] + "/.ssh/authorized_keys" + keys = [line.strip() for line in open(keyf)] + assert keys.count(self.key) == 0 if __name__ == "__main__": # We bypass fabric as we want the tests to be run locally