changeset 39:a0b702a76872

works from maritain
author Henry S. Thompson <ht@inf.ed.ac.uk>
date Mon, 03 Jan 2022 14:17:17 +0000
parents 30f8af85c3fd
children f13017bb4502
files newkey.py
diffstat 1 files changed, 81 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/newkey.py	Mon Jan 03 14:17:17 2022 +0000
@@ -0,0 +1,81 @@
+#!/usr/bin/python3
+'''Install a new ssh key on paul and in a list of hosts,
+confirm success, and if so comment out any older versions
+Usage: newkey.py [-v intermediary] keytype [-i] [-c client | client list filename]
+client list filename defaults to /etc/sshclients _on Paul_
+If -i, read tar with new key pair from stdin, otherwise from ~/.ssh/id_$keytype.pub
+
+If run on a machine other than paul, will try to get it to Paul to distribute:
+   1) Using ssh-copy-id directly;
+   2) Using ssh-copy-id via intermediary (defaults to $DESKTOP)
+[change this to maritain once it's worked for everbody''' # '
+
+import sys, os
+from socket import gethostname
+from subprocess import run
+
+hack=os.environ.copy()
+hack['SSH_AUTH_SOCK']='/home/ht/.gnupg/S.gpg-agent.ssh'
+
+def ssh_copy_id(keyfile,client):
+   print(["ssh-copy-id","-i",keyfile,client],'...',sep='',end='')
+   res=run(["ssh-copy-id","-i",keyfile,client],env=hack).returncode
+   print('failed %s'%res if res else 'succeeded')
+
+ihost=None
+if sys.argv[1]=='-v':
+   sys.argv.pop(1)
+   ihost=sys.argv.pop(1).lower()
+
+keytype=sys.argv.pop(1)
+
+if len(sys.argv)>1 and sys.argv[1]=='-i':
+   # Working for some other client
+   sys.argv.pop(1)
+   res=os.system("cd /tmp ; rm -rf keys ; tar -xzf -")
+   if res:
+      print("untar failed",res)
+      exit(res)
+   keydir="/tmp/keys"
+else:
+   keydir=os.path.expanduser("~/.ssh")
+
+keyfile="%s/id_%s.pub"%(keydir,keytype)
+
+try:
+   clients=sys.argv.pop(1)
+   if clients=='-c':
+      clients="-c %s"%sys.argv.pop(1)
+except:
+   clients='/etc/sshclients'
+
+host=gethostname().lower()
+
+print(keytype,keyfile,ihost,clients)
+
+if host!='paul':
+   if clients[0]!='-':
+      print("Note, %s will be dereferenced on paul, not locally"%clients,
+	    file=sys.stderr)
+   cmd="/home/ht/bin/newkey.py %s -i %s %s"%(keytype,
+					     "-v %s"%ihost if ihost is not None else '',
+					     '%s'%clients if clients is not None else '')
+   print(cmd)
+   res=os.system("mkdir -p /tmp/keys ; cd /tmp ; bash -c 'cp -a %s keys' ; tar -czf keys.tar.gz keys"%os.path.expanduser("~/.ssh/id_%s{,.pub}"%keytype))
+   if res:
+      print("tar failed",res)
+      exit(res)
+   with open("/tmp/keys.tar.gz","rb") as keytar:
+      res=run(['ssh','paul',cmd],stdin=keytar).returncode
+      if res:
+         print("paul failed",res)
+      exit(res)
+
+if clients[0]=='-':
+   ssh_copy_id(keyfile,clients[3:])
+else:    
+   with open(clients) as cfile:
+      for l in cfile:
+         ssh_copy_id(keyfile,l.rstrip())
+
+