~verterok/ols-jenkaas/dd-siab-dependencies

« back to all changes in this revision

Viewing changes to olsjenkaas/ssh.py

  • Committer: Vincent Ladeuil
  • Date: 2017-02-09 16:12:35 UTC
  • mfrom: (323.2.109 lander)
  • Revision ID: vila+ols@canonical.com-20170209161235-8igi05uo09s638fv
Unify lander with tests and jobs tags for validation without service interruption

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# This file is part of Online Services Jenkaas.
 
2
#
 
3
# Copyright 2017 Canonical Ltd.
 
4
#
 
5
# This program is free software: you can redistribute it and/or modify it under
 
6
# the terms of the GNU General Public License version 3, as published by the
 
7
# Free Software Foundation.
 
8
#
 
9
# This program is distributed in the hope that it will be useful, but WITHOUT
 
10
# ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
 
11
# SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 
12
# General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License along with
 
15
# this program.  If not, see <http://www.gnu.org/licenses/>.
 
16
from __future__ import unicode_literals
 
17
 
 
18
 
 
19
from olsvms import subprocesses
 
20
 
 
21
 
 
22
class SshAgent(object):
 
23
 
 
24
    def __init__(self):
 
25
        self._reset()
 
26
 
 
27
    def _reset(self):
 
28
        self.pid = None
 
29
        self.auth_sock = None
 
30
 
 
31
    def start(self):
 
32
        # C-shell output is easier to scan
 
33
        _, out, _ = subprocesses.run(['ssh-agent', '-c'])
 
34
        for line in out.splitlines():
 
35
            if line.startswith('echo '):
 
36
                continue
 
37
            if line.startswith('setenv '):
 
38
                _, name, value = line.split()
 
39
                value = value.rstrip(';')
 
40
                if name == 'SSH_AUTH_SOCK':
 
41
                    self.auth_sock = value
 
42
                elif name == 'SSH_AGENT_PID':
 
43
                    self.pid = value
 
44
 
 
45
    def add(self, key_path):
 
46
        subprocesses.run(['env', 'SSH_AUTH_SOCK={}'.format(self.auth_sock),
 
47
                          'ssh-add', key_path])
 
48
 
 
49
    def stop(self):
 
50
        if self.pid is None:
 
51
            return
 
52
        subprocesses.run(['env', 'SSH_AGENT_PID={}'.format(self.pid),
 
53
                          'ssh-agent', '-k'])
 
54
        self._reset()
 
55
 
 
56
    def get_env(self):
 
57
        """Get the environment variables allowing agent use.
 
58
 
 
59
        :return: A dict with SSH_AUTH_SOCK and SSH_AGENT_PID.
 
60
        """
 
61
        return dict(SSH_AUTH_SOCK=self.auth_sock, SSH_AGENT_PID=self.pid)