415022691d12a80b81811e13c839ed19711f2f1a
[invirt/packages/invirt-base.git] / python / invirt / remctl.py
1 """
2 Functions to perform remctls.
3 """
4
5 import subprocess
6
7 import socket
8
9
10 def kinit(principal=None, keytab=None):
11     """Kinit with a given username and keytab"""
12
13     if principal is None:
14         principal = 'daemon/' + getfqdn()
15     if keytab is None:
16         keytab = '/etc/invirt/keytab'
17
18     subprocess.run(['kinit', '-k', '-t', keytab, principal],
19                    check_output=True, encoding='utf-8', check=True)
20
21 def check_kinit(principal=None, keytab=None):
22     """If we lack tickets, kinit."""
23
24     try:
25         subprocess.run(['klist', '-s'])
26     except subprocess.CalledProcessError:
27         #TODO: Does this return a specific error code that we can check for?
28         kinit(principal, keytab)
29
30 def remctl(host, *args, **kwargs):
31     """
32     Perform a remctl and return the output.
33
34     kinits if necessary, and outputs errors to stderr.
35     """
36
37     check_kinit(kwargs.get('principal'), kwargs.get('keytab'))
38
39     return subprocess.run(['remctl', host] + list(args),
40                           check_output=True, encoding='utf-8', check=True)