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