comparison newkey.py @ 39:a0b702a76872

works from maritain
author Henry S. Thompson <ht@inf.ed.ac.uk>
date Mon, 03 Jan 2022 14:17:17 +0000
parents
children f13017bb4502
comparison
equal deleted inserted replaced
36:30f8af85c3fd 39:a0b702a76872
1 #!/usr/bin/python3
2 '''Install a new ssh key on paul and in a list of hosts,
3 confirm success, and if so comment out any older versions
4 Usage: newkey.py [-v intermediary] keytype [-i] [-c client | client list filename]
5 client list filename defaults to /etc/sshclients _on Paul_
6 If -i, read tar with new key pair from stdin, otherwise from ~/.ssh/id_$keytype.pub
7
8 If run on a machine other than paul, will try to get it to Paul to distribute:
9 1) Using ssh-copy-id directly;
10 2) Using ssh-copy-id via intermediary (defaults to $DESKTOP)
11 [change this to maritain once it's worked for everbody''' # '
12
13 import sys, os
14 from socket import gethostname
15 from subprocess import run
16
17 hack=os.environ.copy()
18 hack['SSH_AUTH_SOCK']='/home/ht/.gnupg/S.gpg-agent.ssh'
19
20 def ssh_copy_id(keyfile,client):
21 print(["ssh-copy-id","-i",keyfile,client],'...',sep='',end='')
22 res=run(["ssh-copy-id","-i",keyfile,client],env=hack).returncode
23 print('failed %s'%res if res else 'succeeded')
24
25 ihost=None
26 if sys.argv[1]=='-v':
27 sys.argv.pop(1)
28 ihost=sys.argv.pop(1).lower()
29
30 keytype=sys.argv.pop(1)
31
32 if len(sys.argv)>1 and sys.argv[1]=='-i':
33 # Working for some other client
34 sys.argv.pop(1)
35 res=os.system("cd /tmp ; rm -rf keys ; tar -xzf -")
36 if res:
37 print("untar failed",res)
38 exit(res)
39 keydir="/tmp/keys"
40 else:
41 keydir=os.path.expanduser("~/.ssh")
42
43 keyfile="%s/id_%s.pub"%(keydir,keytype)
44
45 try:
46 clients=sys.argv.pop(1)
47 if clients=='-c':
48 clients="-c %s"%sys.argv.pop(1)
49 except:
50 clients='/etc/sshclients'
51
52 host=gethostname().lower()
53
54 print(keytype,keyfile,ihost,clients)
55
56 if host!='paul':
57 if clients[0]!='-':
58 print("Note, %s will be dereferenced on paul, not locally"%clients,
59 file=sys.stderr)
60 cmd="/home/ht/bin/newkey.py %s -i %s %s"%(keytype,
61 "-v %s"%ihost if ihost is not None else '',
62 '%s'%clients if clients is not None else '')
63 print(cmd)
64 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))
65 if res:
66 print("tar failed",res)
67 exit(res)
68 with open("/tmp/keys.tar.gz","rb") as keytar:
69 res=run(['ssh','paul',cmd],stdin=keytar).returncode
70 if res:
71 print("paul failed",res)
72 exit(res)
73
74 if clients[0]=='-':
75 ssh_copy_id(keyfile,clients[3:])
76 else:
77 with open(clients) as cfile:
78 for l in cfile:
79 ssh_copy_id(keyfile,l.rstrip())
80
81