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
53    r"""
54    Execute whenever the program ends normally or with the signals that we
55    catch (i.e. TERM, INT).
56    """
57
58    dprint_executing()
59    dprint_var(signal_number)
60
61    qprint_pgm_footer()
62
63
64def signal_handler(signal_number,
65                   frame):
66
67    r"""
68    Handle signals.  Without a function to catch a SIGTERM or SIGINT, our
69    program would terminate immediately with return code 143 and without
70    calling our exit_function.
71    """
72
73    # Our convention is to set up exit_function with atexit.register() so
74    # there is no need to explicitly call exit_function from here.
75
76    dprint_executing()
77
78    # Calling exit prevents us from returning to the code that was running
79    # when we received the signal.
80    exit(0)
81
82
83def validate_parms():
84
85    r"""
86    Validate program parameters, etc.  Return True or False (i.e. pass/fail)
87    accordingly.
88    """
89
90    gen_post_validation(exit_function, signal_handler)
91
92    return True
93
94
95def create_http_prefix(host):
96
97    r"""
98    Create and return an http prefix string.
99
100    Description of argument(s):
101    host                            The host being communicated with via the
102                                    curl command.
103    """
104
105    return "https://" + host + "/"
106
107
108def main():
109
110    if not gen_get_options(parser, stock_list):
111        return False
112
113    if not validate_parms():
114        return False
115
116    qprint_pgm_header()
117
118    session = requests.Session()
119
120    http_prefix = create_http_prefix(openbmc_host)
121
122    command = http_prefix + 'login'
123    qprint_issuing(command)
124    resp = session.post(command,
125                        json={'data': [openbmc_username, openbmc_password]},
126                        verify=False)
127    if resp.json()['status'] != 'ok':
128        json = resp.json()
129        print_error_report("http request failed:\n" + sprint_var(command, 1))
130        raise Exception("Login failed.\n")
131
132    command = http_prefix + "xyz/openbmc_project/inventory/system"
133    qprint_issuing(command)
134    resp = session.get(command, verify=False)
135    json = resp.json()
136    if json['status'] != 'ok':
137        print_error_report("http request failed:\n" + sprint_var(command, 1))
138        raise Exception("http request failed.\n")
139
140    try:
141        mch_ser_num = json['data']['SerialNumber']
142    except KeyError:
143        print_error_report("Failed to find 'SerialNumber' key in the" +
144                           " following data:\n" + sprint_var(json))
145        return False
146    pvar(mch_ser_num, 0, 0, 0)
147
148    return True
149
150
151# Main
152
153if not main():
154    exit(1)
155