~jenkins-ci-charmers/jenkins-agent-charm/trunk

« back to all changes in this revision

Viewing changes to hooks/install.d/charmhelpers/canonical_ci/ssh.py

  • Committer: Ryan Finnie
  • Date: 2015-08-26 18:59:20 UTC
  • mfrom: (11.1.10 jenkins-slave-kitsune)
  • Revision ID: ryan.finnie@canonical.com-20150826185920-ojd6kmiy7a2vg24t
[hloung] Add nagios check for slave process. [r=Joe Talbott, Francis Ginther]

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import os
 
2
import pwd
 
3
 
 
4
from subprocess import check_output
 
5
from charmhelpers.core.hookenv import log
 
6
 
 
7
 
 
8
def public_ssh_key(user='root', ssh_dir=None):
 
9
    _ssh_dir = ssh_dir or os.path.join(pwd.getpwnam(user).pw_dir, '.ssh')
 
10
    try:
 
11
        with open(os.path.join(_ssh_dir, 'id_rsa.pub')) as key:
 
12
            return key.read().strip()
 
13
    except:
 
14
        return None
 
15
 
 
16
 
 
17
def initialize_ssh_keys(user='root', ssh_dir=None):
 
18
    home_dir = pwd.getpwnam(user).pw_dir
 
19
    out_dir = ssh_dir or os.path.join(home_dir, '.ssh')
 
20
    if not os.path.isdir(out_dir):
 
21
        os.mkdir(out_dir)
 
22
 
 
23
    priv_key = os.path.join(out_dir, 'id_rsa')
 
24
    if not os.path.isfile(priv_key):
 
25
        log('Generating new ssh key for user %s.' % user)
 
26
        cmd = ['ssh-keygen', '-q', '-N', '', '-t', 'rsa', '-b', '2048',
 
27
               '-f', priv_key]
 
28
        check_output(cmd)
 
29
 
 
30
    pub_key = '%s.pub' % priv_key
 
31
    if not os.path.isfile(pub_key):
 
32
        log('Generating missing ssh public key @ %s.' % pub_key)
 
33
        cmd = ['ssh-keygen', '-y', '-f', priv_key]
 
34
        p = check_output(cmd).strip()
 
35
        with open(pub_key, 'wb') as out:
 
36
            out.write(p)
 
37
    check_output(['chown', '-R', user, out_dir])