d64a10f42c85a92ca280fdeb94cc2be8b0c97c8e
[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     if principal is None:
13         principal = 'daemon/' + getfqdn()
14     if keytab is None:
15         keytab = '/etc/invirt/keytab'
16
17     subprocess.run(['kinit', '-k', '-t', keytab, principal],
18                    check_output=True, encoding='utf-8', check=True)
19
20 def check_kinit(principal=None, keytab=None):
21     """If we lack tickets, kinit."""
22
23     try:
24         subprocess.run(['klist', '-s'])
25     except subprocess.CalledProcessError:
26         #TODO: Does this return a specific error code that we can check for?
27         kinit(principal, keytab)
28
29 def remctl(host, *args, **kws):
30     """Perform a remctl and return the output.
31
32     kinits if necessary, and outputs errors to stderr.
33     """
34
35     check_kinit(kwargs.get('principal'), kwargs.get('keytab'))
36
37     return subprocess.run(['remctl', host] + list(args),
38                           check_output=True, encoding='utf-8', check=True)