1#!/usr/bin/env python
2
3r"""
4This program will get the system serial number from an OBMC machine and print
5it to stdout.
6"""
7
8import sys
9import os
10import requests
11
12save_path_0 = sys.path[0]
13del sys.path[0]
14
15from gen_arg import *
16from gen_print import *
17from gen_valid import *
18
19# Restore sys.path[0].
20sys.path.insert(0, save_path_0)
21
22logging.captureWarnings(True)
23
24parser = argparse.ArgumentParser(
25    usage='%(prog)s [OPTIONS]',
26    description="%(prog)s will get the system serial number from an OBMC" +
27                " machine and print it to stdout as follows:\n\n" +
28                "mch_ser_num:<ser num>",
29    formatter_class=argparse.ArgumentDefaultsHelpFormatter,
30    prefix_chars='-+')
31
32parser.add_argument(
33    '--openbmc_username',
34    default="root",
35    help='The username for communicating with the OpenBMC machine.')
36
37parser.add_argument(
38    '--openbmc_password',
39    default="0penBmc",
40    help='The password for communicating with the OpenBMC machine.')
41
42parser.add_argument(
43    'openbmc_host',
44    help='The host name or IP address of the OpenBMC machine.')
45
46# Populate stock_list with options we want.
47stock_list = [("test_mode", 0), ("quiet", 1)]
48
49
50def exit_function(signal_number=0,
51                  frame=None):
52    r"""
53    Execute whenever the program ends normally or with the signals that we
54    catch (i.e. TERM, INT).
55    """
56
57    dprint_executing()
58    dprint_var(signal_number)
59
60    qprint_pgm_footer()
61
62
63def signal_handler(signal_number,
64                   frame):
65    r"""
66    Handle signals.  Without a function to catch a SIGTERM or SIGINT, our
67    program would terminate immediately with return code 143 and without
68    calling our exit_function.
69    """
70
71    # Our convention is to set up exit_function with atexit.register() so
72    # there is no need to explicitly call exit_function from here.
73
74    dprint_executing()
75
76    # Calling exit prevents us from returning to the code that was running
77    # when we received the signal.
78    exit(0)
79
80
81def validate_parms():
82    r"""
83    Validate program parameters, etc.  Return True or False (i.e. pass/fail)
84    accordingly.
85    """
86
87    gen_post_validation(exit_function, signal_handler)
88
89    return True
90
91
92def create_http_prefix(host):
93    r"""
94    Create and return an http prefix string.
95
96    Description of argument(s):
97    host                            The host being communicated with via the
98                                    curl command.
99    """
100
101    return "https://" + host + "/"
102
103
104def main():
105
106    if not gen_get_options(parser, stock_list):
107        return False
108
109    if not validate_parms():
110        return False
111
112    qprint_pgm_header()
113
114    session = requests.Session()
115
116    http_prefix = create_http_prefix(openbmc_host)
117
118    command = http_prefix + 'login'
119    qprint_issuing(command)
120    resp = session.post(command,
121                        json={'data': [openbmc_username, openbmc_password]},
122                        verify=False)
123    if resp.json()['status'] != 'ok':
124        json = resp.json()
125        print_error_report("http request failed:\n" + sprint_var(command))
126        raise Exception("Login failed.\n")
127
128    command = http_prefix + "xyz/openbmc_project/inventory/system"
129    qprint_issuing(command)
130    resp = session.get(command, verify=False)
131    json = resp.json()
132    if json['status'] != 'ok':
133        print_error_report("http request failed:\n" + sprint_var(command))
134        raise Exception("http request failed.\n")
135
136    try:
137        mch_ser_num = json['data']['SerialNumber']
138    except KeyError:
139        print_error_report("Failed to find 'SerialNumber' key in the" +
140                           " following data:\n" + sprint_var(json))
141        return False
142    print_var(mch_ser_num, 0, 0, 0)
143
144    return True
145
146
147# Main
148
149if not main():
150    exit(1)
151