Mercurial > hg > python
view newkey.py @ 41:900ff99ec749
less noisy if success
author | Henry S. Thompson <ht@inf.ed.ac.uk> |
---|---|
date | Mon, 03 Jan 2022 19:26:11 +0000 |
parents | f13017bb4502 |
children | 59517f60826d |
line wrap: on
line source
#!/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, PIPE 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,text=True, stdout=PIPE,stderr=PIPE) if res.returncode: print('failed %s'%res.returncode) outs,errs=res.communicate() print(errs) else: print('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"%(keytype, '%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: if ihost is None: res=run(['ssh','paul',cmd],stdin=keytar).returncode if res: print("paul failed",res) exit(res) else: res=run(['ssh',ihost,'/afs/inf.ed.ac.uk/user/h/ht/share/bin/goHome',cmd],stdin=keytar).returncode if res: print("going via %s failed"%ihost,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())