-
Notifications
You must be signed in to change notification settings - Fork 74
/
ipmitool.py
240 lines (191 loc) · 8.47 KB
/
ipmitool.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# Copyright (c) 2014 Kontron Europe GmbH
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import re
from subprocess import Popen, PIPE
from array import array
from ..session import Session
from ..errors import IpmiTimeoutError
from ..logger import log
from ..msgs import encode_message, decode_message, create_message
from ..msgs.constants import CC_OK
from ..utils import py3dec_unic_bytes_fix, ByteBuffer
class Ipmitool(object):
"""This interface uses the ipmitool raw command to "emulate" a RMCP
session.
It uses the session information to assemble the correct ipmitool
parameters. Therefore, a session has to be established before any request
can be sent.
"""
NAME = 'ipmitool'
IPMITOOL_PATH = 'ipmitool'
supported_interfaces = ['lan', 'lanplus', 'serial-terminal']
def __init__(self, interface_type='lan'):
if interface_type in self.supported_interfaces:
self._interface_type = interface_type
else:
raise RuntimeError('interface type %s not supported' %
interface_type)
self.re_completion_code = re.compile(
b"Unable to send RAW command \(.*rsp=(0x[0-9a-f]+)\)")
self.re_timeout = re.compile(
b"Unable to send RAW command \(.*cmd=0x[0-9a-f]+\)")
self._session = None
def establish_session(self, session):
# just remember session parameters here
self._session = session
def rmcp_ping(self):
if self._interface_type == 'serial-terminal':
raise RuntimeError(
'rcmp_ping not supported on "serial-terminal" interface')
# for now this uses impitool..
cmd = self.IPMITOOL_PATH
cmd += (' -I %s' % self._interface_type)
cmd += (' -H %s' % self._session.rmcp_host)
cmd += (' -p %s' % self._session.rmcp_port)
if self._session.auth_type == Session.AUTH_TYPE_NONE:
cmd += (' -A NONE')
elif self._session.auth_type == Session.AUTH_TYPE_PASSWORD:
cmd += (' -U "%s"' % self._session.auth_username)
cmd += (' -P "%s"' % self._session.auth_password)
cmd += (' session info all')
_, rc = self._run_ipmitool(cmd)
if rc:
raise IpmiTimeoutError()
def is_ipmc_accessible(self, target):
try:
self.rmcp_ping()
accessible = True
except IpmiTimeoutError:
accessible = False
return accessible
def send_and_receive_raw(self, target, lun, netfn, raw_bytes):
if self._interface_type in ['lan', 'lanplus']:
cmd = self._build_ipmitool_cmd(target, lun, netfn, raw_bytes)
elif self._interface_type in ['serial-terminal']:
cmd = self._build_serial_ipmitool_cmd(target, lun, netfn,
raw_bytes)
else:
raise RuntimeError('interface type %s not supported' %
self._interface_type)
output, rc = self._run_ipmitool(cmd)
# check for errors
match_completion_code = self.re_completion_code.match(output)
match_timeout = self.re_timeout.match(output)
data = array('B')
if match_completion_code:
cc = int(match_completion_code.group(1), 16)
data.append(cc)
elif match_timeout:
raise IpmiTimeoutError()
else:
if rc != 0:
raise RuntimeError('ipmitool failed with rc=%d' % rc)
# completion code
data.append(CC_OK)
output = py3dec_unic_bytes_fix(output)
output_lines = output.split('\n')
# strip 'Close Session command failed' lines
output_lines = [l for l in output_lines
if not l.startswith(
'Close Session command failed')]
output = ''.join(output_lines).replace('\r', '').strip()
if len(output):
for value in output.split(' '):
data.append(int(value, 16))
log().debug('IPMI RX: {:s}'.format(
''.join('%02x ' % b for b in array('B', data))))
return data.tostring()
def send_and_receive(self, req):
log().debug('IPMI Request [%s]', req)
req_data = ByteBuffer((req.cmdid,))
req_data.push_string(encode_message(req))
rsp_data = self.send_and_receive_raw(req.target, req.lun, req.netfn,
req_data.tostring())
rsp = create_message(req.netfn + 1, req.cmdid, req.group_extension)
decode_message(rsp, rsp_data)
log().debug('IPMI Response [%s])', rsp)
return rsp
@staticmethod
def _build_ipmitool_raw_data(lun, netfn, raw):
cmd = ' -l {:d} raw '.format(lun)
cmd += ' '.join(['0x%02x' % (d)
for d in [netfn] + array('B', raw).tolist()])
return cmd
@staticmethod
def _build_ipmitool_target(target):
cmd = ''
if target.routing is not None:
# we have to do bridging here
if len(target.routing) == 1:
pass
if len(target.routing) == 2:
# ipmitool/shelfmanager does implicit bridging
cmd += (' -t 0x%02x' % target.routing[1].rs_sa)
cmd += (' -b %d' % target.routing[0].channel)
elif len(target.routing) == 3:
cmd += (' -T 0x%02x' % target.routing[1].rs_sa)
cmd += (' -B %d' % target.routing[0].channel)
cmd += (' -t 0x%02x' % target.routing[2].rs_sa)
cmd += (' -b %d' % target.routing[1].channel)
else:
raise RuntimeError('The impitool interface at most double '
'briding %s' % target)
elif target.ipmb_address:
cmd += (' -t 0x%02x' % target.ipmb_address)
return cmd
def _build_ipmitool_cmd(self, target, lun, netfn, raw_bytes):
if not hasattr(self, '_session'):
raise RuntimeError('Session needs to be set')
cmd = self.IPMITOOL_PATH
cmd += (' -I %s' % self._interface_type)
cmd += (' -H %s' % self._session.rmcp_host)
cmd += (' -p %s' % self._session.rmcp_port)
if self._session.auth_type == Session.AUTH_TYPE_NONE:
cmd += ' -P ""'
elif self._session.auth_type == Session.AUTH_TYPE_PASSWORD:
cmd += (' -U "%s"' % self._session.auth_username)
cmd += (' -P "%s"' % self._session.auth_password)
else:
raise RuntimeError('Session type %d not supported' %
self._session.auth_type)
cmd += self._build_ipmitool_target(target)
cmd += self._build_ipmitool_raw_data(lun, netfn, raw_bytes)
cmd += (' 2>&1')
return cmd
def _build_serial_ipmitool_cmd(self, target, lun, netfn, raw_bytes):
if not hasattr(self, '_session'):
raise RuntimeError('Session needs to be set')
cmd = '{path!s:s} -I {interface!s:s} -D {port!s:s}:{baud!s:s}'\
.format(
path=self.IPMITOOL_PATH,
interface=self._interface_type,
port=self._session.serial_port,
baud=self._session.serial_baudrate
)
cmd += self._build_ipmitool_target(target)
cmd += self._build_ipmitool_raw_data(lun, netfn, raw_bytes)
return cmd
@staticmethod
def _run_ipmitool(cmd):
"""Legacy call of ipmitool (will be removed in future).
"""
log().debug('Running ipmitool "%s"', cmd)
child = Popen(cmd, shell=True, stdout=PIPE)
output = child.communicate()[0]
log().debug('return with rc=%d, output was:\n%s',
child.returncode,
output)
return output, child.returncode