summaryrefslogtreecommitdiffstats
path: root/get-gitlab-keys
blob: 6981e8f183d81c13ad1f1cfb311de0c95b7f939e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python3
import os
import argparse
import pathlib

import gitlab


def get_config_files():
    files = []
    for cfg in ['gitlab.cfg', '~/.gitlab.cfg', '/etc/gitlab.conf']:
        path = os.path.expanduser(cfg)
        if os.path.exists(path):
            files.append(path)
    return files


def write_keys(directory, user):
    keys = user.keys.list()
    if len(keys) == 0:
        return

    filename = '%s.pub' % user.username.lower()
    with open(os.path.join(directory, filename), 'w+') as keyfile:
        for key in keys:
            keyfile.write('%s\n' % key.key)


def main():
    parser = argparse.ArgumentParser(
        description='Get all public ssh keys of all '
                    'members of a gitlab group.')
    parser.add_argument('group_id', metavar='GROUP_ID', type=int,
                        help='id of the gitlab group')
    parser.add_argument('path', metavar='PATH', type=pathlib.Path,
                        help='path to the output directory')
    args = parser.parse_args()
    
    if not os.path.exists(args.path):
       os.makedirs(args.path)

    gl = gitlab.Gitlab.from_config('gitlab', get_config_files())

    group = gl.groups.get(args.group_id)
    for member in group.members.all(all=True):
        if member.access_level >= gitlab.const.DEVELOPER_ACCESS:
            user = gl.users.get(member.id)
            write_keys(args.path, user)

if __name__ == '__main__':
    main()