def open_ipmi_lan_connection(self, host, target_address, user='', password='',
            routing_information=None, port=623, interface_type='ipmitool',
            alias=None):
        """Opens a LAN connection to an IPMI shelf manager.

        `host` is the IP or hostname of the shelf manager. `target_address` the
        IPMI address to which the command should be sent. `user` and `password`
        are used to authenticate against the shelf manager.
        """

        host = str(host)
        target_address = int_any_base(target_address)
        user = str(user)
        password = str(password)
        port = int_any_base(port)

        interface = pyipmi.interfaces.create_interface(interface_type, 'lanplus')
        ipmi = pyipmi.create_connection(interface)
        ipmi.session.set_session_type_rmcp(host, port)
        ipmi.session.set_auth_type_user(user, password)

        self._info('Opening IPMI connection to %s:%d/%02Xh' % (host,
            port, target_address))

        ipmi.session.establish()

        target = pyipmi.Target(target_address, routing_information)
        ipmi.target = target

        connection = IpmiConnection(ipmi, target)

        self._active_connection = connection

        return self._cache.register(connection, alias)
Пример #2
0
    def __new__(cls, *args, **kwargs):
        if not cls._instanceAardvark:
            cls._instanceAardvark = super(InvokeAadvark,
                                          cls).__new__(cls, *args, **kwargs)
            try:
                jsonpath = os.path.abspath(
                    os.path.dirname(__file__).replace('buildingblocks', '') +
                    r'workthreads/Json/Device.json')
                config = json.loads(open(jsonpath).read())
                slave = int(config['devices'][0]['slaveaddress'], 16)
                port = int(config['devices'][0]['port'], 16)
                bridge = int(config['bridge'], 16)  # 0x06
                target = int(config['target'], 16)  # 0x2c
                interface = pyipmi.interfaces.create_interface(
                    'aardvark', slave, port, None)

                cls._instanceAardvark._target = Target(target)
                connection = pyipmi.create_connection(interface)
                connection.target = cls._instanceAardvark._target
                connection.target.set_routing([(0, bridge)])
                connection.session.establish()
                cls._instanceAardvark._connection = connection
                cls._instanceAardvark._interface = interface
                cls._instanceAardvark._rc = 0
                cls._aadVarkMutex = Lock()
            except Exception as e:
                print(str(e))
        return cls._instanceAardvark
Пример #3
0
 def __init__(
         self,
         host,
         user,
         password,
         bridge=None,  #0x06,
         target=None,  #0x2c,
         port=623,
         toolname='ipmitool',
         interfacetype='lanplus',
         delay=1):
     self._interfacetype = interfacetype
     self._delay = delay
     try:
         interface = pyipmi.interfaces.create_interface(
             toolname, self._interfacetype)
         self._target = None
         if target is not None:
             self._target = Target(target)
         connection = pyipmi.create_connection(interface)
         connection.target = self._target
         if target is not None:
             connection.target.set_routing([(0, bridge)])
             connection.session.set_session_type_rmcp(host, port)
             connection.session.set_auth_type_user(user, password)
         connection.session.establish()
         self._connection = connection
         self._interface = interface
         self._rc = 0
     except Exception as e:
         self._connection = None
         print(str(e))
Пример #4
0
    def connect(self, test=False):
        "Function creates connection to given device"
        try:
            interface = pyipmi.interfaces.create_interface(
                interface='ipmitool', interface_type='lanplus')
        except Exception as ex:
            LOGGER.error(f"Error while logging in\n{ex}")
            return False

        # create connection on that interface
        ipmi = pyipmi.create_connection(interface)
        ipmi.session.set_session_type_rmcp(host=self.address,
                                           port=int(self.port))
        ipmi.session.set_auth_type_user(username=self.credentials.username,
                                        password=self.credentials.password)

        ipmi.target = pyipmi.Target(ipmb_address=0x20)
        ipmi.session.establish()
        try:
            ipmi.session.rmcp_ping()
        except IpmiTimeoutError:
            return False
        if test:
            return True
        self.connected = True
        self.interface = interface
        self.ipmi = ipmi
        return True
    def open_ipmi_lan_connection(self, host, target_address, user='', password='',
            routing_information=None, port=623, interface_type='ipmitool',
            alias=None):
        """Opens a LAN connection to an IPMI shelf manager.

        `host` is the IP or hostname of the shelf manager. `target_address` the
        IPMI address to which the command should be sent. `user` and `password`
        are used to authenticate against the shelf manager.
        """

        host = str(host)
        target_address = int_any_base(target_address)
        user = str(user)
        password = str(password)
        port = int_any_base(port)

        interface = pyipmi.interfaces.create_interface(interface_type)
        ipmi = pyipmi.create_connection(interface)
        ipmi.session.set_session_type_rmcp(host, port)
        ipmi.session.set_auth_type_user(user, password)

        self._info('Opening IPMI connection to %s:%d/%02Xh' % (host,
            port, target_address))

        ipmi.session.establish()

        target = pyipmi.Target(target_address, routing_information)
        ipmi.target = target

        connection = IpmiConnection(ipmi, target)

        self._active_connection = connection

        return self._cache.register(connection, alias)
Пример #6
0
def createSession(host, port, user, password):
    interface = pyipmi.interfaces.create_interface('rmcp',
                                                   slave_address=0x81,
                                                   host_target_address=0x20,
                                                   keep_alive_interval=0)
    ipmi = pyipmi.create_connection(interface)
    ipmi.session.set_session_type_rmcp(host, port)
    ipmi.session.set_auth_type_user(user, password)
    ipmi.session.establish()
    ipmi.target = pyipmi.Target(ipmb_address=0x20)
    return ipmi
Пример #7
0
def test_ipmi_send_message_retry_error():
    req = GetDeviceIdReq()
    rsp = GetDeviceIdRsp()

    interface = interfaces.create_interface('mock')
    cc = CompletionCodeError(CC_NODE_BUSY)
    mock = MagicMock(side_effect=(cc, cc, cc))
    mock.return_value = rsp
    interface.send_and_receive = mock
    ipmi = create_connection(interface)
    ipmi.target = None
    ipmi.send_message(req)
Пример #8
0
def test_ipmi_send_message_retry_error():
    req = GetDeviceIdReq()
    rsp = GetDeviceIdRsp()

    interface = interfaces.create_interface('mock')
    cc = CompletionCodeError(CC_NODE_BUSY)
    mock = MagicMock(side_effect=(cc, cc, cc))
    mock.return_value = rsp
    interface.send_and_receive = mock
    ipmi = create_connection(interface)
    ipmi.target = None
    ipmi.send_message(req)
Пример #9
0
def test_set_sensor_thresholds():

    rsp = SetSensorThresholdsRsp()
    rsp.completion_code = 0

    mock_send_recv = MagicMock()
    mock_send_recv.return_value = rsp

    interface = interfaces.create_interface('mock')
    ipmi = create_connection(interface)
    ipmi.send_message = mock_send_recv

    ipmi.set_sensor_thresholds(sensor_number=5, lun=1)
    args, kwargs = mock_send_recv.call_args
    req = args[0]
    eq_(req.lun, 1)
    eq_(req.sensor_number, 5)

    ipmi.set_sensor_thresholds(sensor_number=0, unr=10)
    args, kwargs = mock_send_recv.call_args
    req = args[0]
    eq_(req.set_mask.unr, 1)
    eq_(req.threshold.unr, 10)
    eq_(req.set_mask.ucr, 0)
    eq_(req.threshold.ucr, 0)
    eq_(req.set_mask.unc, 0)
    eq_(req.threshold.unc, 0)
    eq_(req.set_mask.lnc, 0)
    eq_(req.threshold.lnc, 0)
    eq_(req.set_mask.lcr, 0)
    eq_(req.threshold.lcr, 0)
    eq_(req.set_mask.lnr, 0)
    eq_(req.threshold.lnr, 0)

    ipmi.set_sensor_thresholds(sensor_number=5, ucr=11)
    args, kwargs = mock_send_recv.call_args
    req = args[0]
    eq_(req.lun, 0)
    eq_(req.set_mask.unr, 0)
    eq_(req.threshold.unr, 0)
    eq_(req.set_mask.ucr, 1)
    eq_(req.threshold.ucr, 11)
    eq_(req.set_mask.unc, 0)
    eq_(req.threshold.unc, 0)
    eq_(req.set_mask.lnc, 0)
    eq_(req.threshold.lnc, 0)
    eq_(req.set_mask.lcr, 0)
    eq_(req.threshold.lcr, 0)
    eq_(req.set_mask.lnr, 0)
    eq_(req.threshold.lnr, 0)
Пример #10
0
def test_set_sensor_thresholds():

    rsp = SetSensorThresholdsRsp()
    rsp.completion_code = 0

    mock_send_recv = MagicMock()
    mock_send_recv.return_value = rsp

    interface = interfaces.create_interface('mock')
    ipmi = create_connection(interface)
    ipmi.send_message = mock_send_recv

    ipmi.set_sensor_thresholds(sensor_number=5, lun=1)
    args, _ = mock_send_recv.call_args
    req = args[0]
    eq_(req.lun, 1)
    eq_(req.sensor_number, 5)

    ipmi.set_sensor_thresholds(sensor_number=0, unr=10)
    args, _ = mock_send_recv.call_args
    req = args[0]
    eq_(req.set_mask.unr, 1)
    eq_(req.threshold.unr, 10)
    eq_(req.set_mask.ucr, 0)
    eq_(req.threshold.ucr, 0)
    eq_(req.set_mask.unc, 0)
    eq_(req.threshold.unc, 0)
    eq_(req.set_mask.lnc, 0)
    eq_(req.threshold.lnc, 0)
    eq_(req.set_mask.lcr, 0)
    eq_(req.threshold.lcr, 0)
    eq_(req.set_mask.lnr, 0)
    eq_(req.threshold.lnr, 0)

    ipmi.set_sensor_thresholds(sensor_number=5, ucr=11)
    args, _ = mock_send_recv.call_args
    req = args[0]
    eq_(req.lun, 0)
    eq_(req.set_mask.unr, 0)
    eq_(req.threshold.unr, 0)
    eq_(req.set_mask.ucr, 1)
    eq_(req.threshold.ucr, 11)
    eq_(req.set_mask.unc, 0)
    eq_(req.threshold.unc, 0)
    eq_(req.set_mask.lnc, 0)
    eq_(req.threshold.lnc, 0)
    eq_(req.set_mask.lcr, 0)
    eq_(req.threshold.lcr, 0)
    eq_(req.set_mask.lnr, 0)
    eq_(req.threshold.lnr, 0)
Пример #11
0
def test_ipmi_send_message_with_name():

    rsp = GetDeviceIdRsp()
    rsp.completion_code = 0

    mock_send_message = MagicMock()
    mock_send_message.return_value = rsp

    interface = interfaces.create_interface('mock')
    ipmi = create_connection(interface)
    ipmi.send_message = mock_send_message

    ipmi.send_message_with_name('GetDeviceId')
    args, kwargs = mock_send_message.call_args
    req = args[0]
    ok_(isinstance(req, GetDeviceIdReq))
Пример #12
0
def test_ipmi_send_message_with_name():

    rsp = GetDeviceIdRsp()
    rsp.completion_code = 0

    mock_send_message = MagicMock()
    mock_send_message.return_value = rsp

    interface = interfaces.create_interface('mock')
    ipmi = create_connection(interface)
    ipmi.send_message = mock_send_message

    ipmi.send_message_with_name('GetDeviceId')
    args, kwargs = mock_send_message.call_args
    req = args[0]
    ok_(isinstance(req, GetDeviceIdReq))
Пример #13
0
def test_ipmi_send_message_with_name_and_kwargs():

    rsp = GetSensorReadingRsp()
    rsp.completion_code = 0

    mock_send_message = MagicMock()
    mock_send_message.return_value = rsp

    interface = interfaces.create_interface('mock')
    ipmi = create_connection(interface)
    ipmi.send_message = mock_send_message

    ipmi.send_message_with_name('GetSensorReading', sensor_number=5, lun=2)
    args, kwargs = mock_send_message.call_args
    req = args[0]
    ok_(isinstance(req, GetSensorReadingReq))
    eq_(req.sensor_number, 5)
    eq_(req.lun, 2)
Пример #14
0
def test_ipmi_send_message_with_name_and_kwargs():

    rsp = GetSensorReadingRsp()
    rsp.completion_code = 0

    mock_send_message = MagicMock()
    mock_send_message.return_value = rsp

    interface = interfaces.create_interface('mock')
    ipmi = create_connection(interface)
    ipmi.send_message = mock_send_message

    ipmi.send_message_with_name('GetSensorReading', sensor_number=5, lun=2)
    args, kwargs = mock_send_message.call_args
    req = args[0]
    ok_(isinstance(req, GetSensorReadingReq))
    eq_(req.sensor_number, 5)
    eq_(req.lun, 2)
    def open_ipmi_aardvark_connection(self,
                                      port_or_serial,
                                      target_address,
                                      slave_address=0x20,
                                      routing_information=None,
                                      alias=None,
                                      enable_i2c_pullups=True):
        """Opens an Aardvark connection to the IPMB.
        `target_address` is the IPMB address to which the command should be
        sent. With the `serial_number` the aardvark device can be specified. If
        `None` is set the first is selected.
        """
        target_address = int_any_base(target_address)
        slave_address = int_any_base(slave_address)

        if isinstance(port_or_serial, basestring) and '-' in port_or_serial:
            serial = port_or_serial
            port = None
            self._info('Opening Aardvark adapter with serial %s' %
                       (port_or_serial, ))
        else:
            port = int(port_or_serial)
            serial = None
            self._info('Opening Aardvark adapter on port %d' % (port, ))

        interface = pyipmi.interfaces.create_interface(
            'aardvark',
            slave_address=slave_address,
            port=port,
            serial_number=serial,
            enable_i2c_pullups=enable_i2c_pullups)
        ipmi = pyipmi.create_connection(interface)

        target = pyipmi.Target(target_address, routing_information)
        ipmi.target = target

        self._info('Opening IPMI aardvark connection to %02Xh' %
                   target_address)

        connection = IpmiConnection(ipmi, target)

        self._active_connection = connection

        return self._cache.register(connection, alias)
Пример #16
0
    def get_ipmi_ctx(self, host, user, password):
        """
        Function to get ipmi handler
        Args:
            host (str): Host mgmt address
            user (str): User Name for accessing mgmt console
            password (str): Password for accessing mgmt console

        Returns (object): ipmi handler

        """
        interface = pyipmi.interfaces.create_interface(
            "ipmitool", interface_type=defaults.IPMI_INTERFACE_TYPE
        )
        ipmi = pyipmi.create_connection(interface)
        ipmi.session.set_session_type_rmcp(host, port=defaults.IPMI_RMCP_PORT)
        ipmi.session.set_auth_type_user(user, password)
        ipmi.session.establish()
        ipmi.target = pyipmi.Target(ipmb_address=defaults.IPMI_IPMB_ADDRESS)
        return ipmi
Пример #17
0
def clean_nodes(inventory):
    inv_dict = utils.parse_yaml(inventory)
    if inv_dict is None or 'nodes' not in inv_dict:
        logging.error("Inventory file is empty or missing nodes definition")
        sys.exit(1)
    for node, node_info in inv_dict['nodes'].items():
        logging.info("Cleaning node: {}".format(node))
        try:
            interface = pyipmi.interfaces.create_interface(
                'ipmitool', interface_type='lanplus')
            connection = pyipmi.create_connection(interface)
            connection.session.set_session_type_rmcp(node_info['ipmi_ip'])
            connection.target = pyipmi.Target(0x20)
            connection.session.set_auth_type_user(node_info['ipmi_user'],
                                                  node_info['ipmi_pass'])
            connection.session.establish()
            connection.chassis_control_power_down()
        except Exception as e:
            logging.error("Failure while shutting down node {}".format(e))
            sys.exit(1)
Пример #18
0
def clean_nodes(inventory):
    inv_dict = utils.parse_yaml(inventory)
    if inv_dict is None or 'nodes' not in inv_dict:
        logging.error("Inventory file is empty or missing nodes definition")
        sys.exit(1)
    for node, node_info in inv_dict['nodes'].items():
        logging.info("Cleaning node: {}".format(node))
        try:
            interface = pyipmi.interfaces.create_interface(
                'ipmitool', interface_type='lanplus')
            connection = pyipmi.create_connection(interface)
            connection.session.set_session_type_rmcp(node_info['ipmi_ip'])
            connection.target = pyipmi.Target(0x20)
            connection.session.set_auth_type_user(node_info['ipmi_user'],
                                                  node_info['ipmi_pass'])
            connection.session.establish()
            connection.chassis_control_power_down()
        except Exception as e:
            logging.error("Failure while shutting down node {}".format(e))
            sys.exit(1)
Пример #19
0
    def get_ipmi_connection(self, bmc_addr, node_name):
        type_position = bmc_addr.find("://")
        if type_position == -1:
            host = bmc_addr
        else:
            host = bmc_addr[type_position + 3 :]
        port_position = host.find(":")
        if port_position == -1:
            port = 623
        else:
            port = int(host[port_position + 1 :])
            host = host[0:port_position]

        # Determine correct username and password
        # If specified, uses device-specific user/pass. Else uses the global one.
        if self.bm_info is not None and node_name in self.bm_info:
            user = self.bm_info[node_name].get("bmc_user", self.user)
            passwd = self.bm_info[node_name].get("bmc_password", self.passwd)
        else:
            user = self.user
            passwd = self.passwd
        if user is None or passwd is None:
            logging.error(
                "Missing IPMI BMI user and/or password for baremetal cloud. "
                "Please specify either a global or per-machine user and pass"
            )
            sys.exit(1)

        # Establish connection
        interface = pyipmi.interfaces.create_interface("ipmitool", interface_type="lanplus")

        connection = pyipmi.create_connection(interface)

        connection.target = pyipmi.Target(ipmb_address=0x20)
        connection.session.set_session_type_rmcp(host, port)
        connection.session.set_auth_type_user(user, passwd)
        connection.session.establish()
        return connection
Пример #20
0
    def open_ipmi_aardvark_connection(self, port_or_serial, target_address,
        slave_address=0x20,  routing_information=None, alias=None,
        enable_i2c_pullups=True):
        """Opens an Aardvark connection to the IPMB.
        `target_address` is the IPMB address to which the command should be
        sent. With the `serial_number` the aardvark device can be specified. If
        `None` is set the first is selected.
        """
        target_address = int_any_base(target_address)
        slave_address = int_any_base(slave_address)

        if isinstance(port_or_serial, basestring) and '-' in port_or_serial:
            serial = port_or_serial
            port = None
            self._info('Opening Aardvark adapter with serial %s' %
                    (port_or_serial,))
        else:
            port = int(port_or_serial)
            serial = None
            self._info('Opening Aardvark adapter on port %d' % (port,))

        interface = pyipmi.interfaces.create_interface('aardvark',
                slave_address=slave_address, port=port, serial_number=serial,
                enable_i2c_pullups=enable_i2c_pullups)
        ipmi = pyipmi.create_connection(interface)

        target = pyipmi.Target(target_address, routing_information)
        ipmi.target = target

        self._info('Opening IPMI aardvark connection to %02Xh' % target_address)

        connection = IpmiConnection(ipmi, target)

        self._active_connection = connection

        return self._cache.register(connection, alias)
Пример #21
0
def main():
    interface = pyipmi.interfaces.create_interface('ipmitool', interface_type='lanplus')
    connection = pyipmi.create_connection(interface)
    connection.target = pyipmi.Target(0x20)
    connection.session.set_session_type_rmcp('192.168.65.27', port=623)
    connection.session.set_auth_type_user('admin', 'adminoseasy')
    connection.session.establish()

    ret = connection.get_fru_inventory(fru_id=0)
    b = ret.board_info_area
    print 'board_info_area:'
    print '    custom_mfg_info:', b.custom_mfg_info
    print '    format_version:', b.format_version
    print '    fru_file_id:', b.fru_file_id.value
    print '    language_code:', b.language_code
    print '    manufacturer:', b.manufacturer.value
    print '    mfg_date:', b.mfg_date
    print '    part_number:', b.part_number.value
    print '    product_name:', b.product_name.value
    print '    serial_number:', b.serial_number.value
    c = ret.chassis_info_area
    if c is not None:
        print 'chassis_info_area:', dir(c)
        print '    custom_chassis_info:', c.custom_chassis_info
        print '    format_version:', c.format_version
        print '    part_number:', c.part_number.value
        print '    serial_number:', c.serial_number.value
        print '    type:', c.type
        for t in (
            'TYPE_ALL_IN_ONE', 'TYPE_BUS_EXPANSION_CHASSIS', 'TYPE_DESKTOP',
            'TYPE_DOCKING_STATION', 'TYPE_EXPANSION_CHASSIS', 'TYPE_HAND_HELD',
            'TYPE_LAPTOP', 'TYPE_LOW_PROFILE_DESKTOP', 'TYPE_LUNCH_BOX',
            'TYPE_MAIN_SERVER_CHASSIS', 'TYPE_MINI_TOWER', 'TYPE_NOTEBOOK',
            'TYPE_OTHER', 'TYPE_PERIPHERAL_CHASSIS', 'TYPE_PIZZA_BOX',
            'TYPE_PORTABLE', 'TYPE_RACK_MOUNT_CHASSIS', 'TYPE_RAID_CHASSIS',
            'TYPE_SPACE_SAVING', 'TYPE_SUB_CHASSIS', 'TYPE_SUB_NOTEBOOK',
            'TYPE_TOWER', 'TYPE_UNKNOWN',
        ):
            print '        ', t, getattr(c, t)
    c = ret.common_header
    print 'common_header:'
    print '    board_info_area_offset:', c.board_info_area_offset
    print '    chassis_info_area_offset:', c.chassis_info_area_offset
    print '    format_version:', c.format_version
    print '    internal_use_area_offset:', c.internal_use_area_offset
    print '    multirecord_area_offset:', c.multirecord_area_offset
    print '    product_info_area_offset:', c.product_info_area_offset
    print 'multirecord_area:', ret.multirecord_area
    p = ret.product_info_area
    print 'product_info_area:'
    print '    asset_tag:', p.asset_tag.value
    print '    custom_mfg_info:', p.custom_mfg_info
    print '    format_version:', p.format_version
    print '    fru_file_id:', p.fru_file_id.value
    print '    language_code:', p.language_code
    print '    manufacturer:', p.manufacturer.value
    print '    name:', p.name.value
    print '    part_number:', p.part_number.value
    print '    serial_number:', p.serial_number.value
    print '    version:', p.version.value
    return
Пример #22
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 't:hvVI:H:U:P:o:b:p:r:')
    except getopt.GetoptError as err:
        print(str(err))
        usage()
        sys.exit(2)
    verbose = False
    interface_name = 'aardvark'
    target_address = 0x20
    target_routing = None
    rmcp_host = None
    rmcp_port = 623
    rmcp_user = ''
    rmcp_password = ''
    interface_options = list()
    for o, a in opts:
        if o == '-v':
            verbose = True
        elif o == '-h':
            usage()
            sys.exit()
        elif o == '-V':
            version()
            sys.exit()
        elif o == '-t':
            target_address = int(a, 0)
        elif o == '-b':
            target_routing = [(0x20, int(a), 0)]
        elif o == '-r':
            target_routing = a
        elif o == '-H':
            rmcp_host = a
        elif o == '-p':
            rmcp_port = int(a, 0)
        elif o == '-U':
            rmcp_user = a
        elif o == '-P':
            rmcp_password = a
        elif o == '-I':
            interface_name = a
        elif o == '-o':
            interface_options = a
            #interface_options = a.split(',')
        else:
            assert False, 'unhandled option'

    # fake sys.argv
    sys.argv = [sys.argv[0]] + args

    if len(args) == 0:
        usage()
        sys.exit(1)

    handler = logging.StreamHandler()
    if verbose:
        handler.setLevel(logging.DEBUG)
    else:
        handler.setLevel(logging.INFO)
    pyipmi.logger.add_log_handler(handler)
    pyipmi.logger.set_log_level(logging.DEBUG)

    for i in range(len(args)):
        cmd = _get_command_function(' '.join(args[0:i + 1]))
        if cmd is not None:
            args = args[i + 1:]
            break
    else:
        usage()
        sys.exit(1)

    interface_options = parse_interface_options(interface_name,
                                                interface_options)

    try:
        interface = pyipmi.interfaces.create_interface(interface_name,
                                                       **interface_options)
    except RuntimeError as e:
        print(e)
        sys.exit(1)

    ipmi = pyipmi.create_connection(interface)
    ipmi.target = pyipmi.Target(target_address)

    if target_routing is not None:
        ipmi.target.set_routing(target_routing)

    if rmcp_host is not None:
        ipmi.session.set_session_type_rmcp(rmcp_host, rmcp_port)
        ipmi.session.set_auth_type_user(rmcp_user, rmcp_password)
        ipmi.session.establish()

    try:
        cmd(ipmi, args)
    except pyipmi.errors.CompletionCodeError as e:
        print('Command returned with completion code 0x%02x' % e.cc)
        if verbose:
            traceback.print_exc()
        sys.exit(1)
    except pyipmi.errors.IpmiTimeoutError as e:
        print('Command timed out')
        if verbose:
            traceback.print_exc()
        sys.exit(1)
    except KeyboardInterrupt as e:
        if verbose:
            traceback.print_exc()
        sys.exit(1)

    finally:
        if rmcp_host is not None:
            ipmi.session.close()
Пример #23
0
    try:
        if interface_name == 'aardvark':
            interface = pyipmi.interfaces.create_interface(interface_name,
                            serial_number=aardvark_serial)
        else:
            interface = pyipmi.interfaces.create_interface(interface_name)
    except RuntimeError, e:
        print e
        sys.exit(1)

    if aardvark_pullups:
        interface.enable_pullups(aardvark_pullups)
    if aardvark_target_power:
        interface.enable_target_power(target_power)

    ipmi = pyipmi.create_connection(interface)
    ipmi.target = pyipmi.Target(target_address)
    ipmi.target.set_routing_information(target_routing)

    if rmcp_host is not None:
        ipmi.session.set_session_type_rmcp(rmcp_host)
        ipmi.session.set_auth_type_user(rmcp_user, rmcp_password)
        ipmi.session.establish()

    try:
        cmd(ipmi, args)
    except pyipmi.errors.CompletionCodeError, e:
        print 'Command returned with completion code 0x%02x' % e.cc
        if verbose:
            traceback.print_exc()
        sys.exit(1)
Пример #24
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 't:hvVI:H:U:P:o:b:')
    except getopt.GetoptError as err:
        print(str(err))
        usage()
        sys.exit(2)
    verbose = False
    interface_name = 'aardvark'
    target_address = 0x20
    target_routing = [(0x20, 0)]
    rmcp_host = None
    rmcp_user = ''
    rmcp_password = ''
    interface_options = list()
    for o, a in opts:
        if o == '-v':
            verbose = True
        elif o == '-h':
            usage()
            sys.exit()
        elif o == '-V':
            version()
            sys.exit()
        elif o == '-t':
            target_address = int(a, 0)
        elif o == '-b':
            target_routing = [(0x20, int(a))]
        elif o == '-H':
            rmcp_host = a
        elif o == '-U':
            rmcp_user = a
        elif o == '-P':
            rmcp_password = a
        elif o == '-I':
            interface_name = a
        elif o == '-o':
            interface_options = a.split(',')
        else:
            assert False, 'unhandled option'

    # fake sys.argv
    sys.argv = [sys.argv[0]] + args

    if len(args) == 0:
        usage()
        sys.exit(1)

    handler = logging.StreamHandler()
    if verbose:
        handler.setLevel(logging.DEBUG)
    else:
        handler.setLevel(logging.INFO)
    pyipmi.logger.add_log_handler(handler)
    pyipmi.logger.set_log_level(logging.DEBUG)

    for i in range(len(args)):
        cmd = _get_command_function(' '.join(args[0:i + 1]))
        if cmd is not None:
            args = args[i + 1:]
            break
    else:
        usage()
        sys.exit(1)

    aardvark_serial = None
    aardvark_pullups = None
    aardvark_target_power = None

    for option in interface_options:
        (name, value) = option.split('=', 1)
        if (interface_name, name) == ('aardvark', 'serial'):
            aardvark_serial = value
        elif (interface_name, name, value) == ('aardvark', 'pullups', 'on'):
            aardvark_pullups = True
        elif (interface_name, name, value) == ('aardvark', 'pullups', 'off'):
            aardvark_pullups = False
        elif (interface_name, name, value) == ('aardvark', 'power', 'on'):
            aardvark_target_power = True
        elif (interface_name, name, value) == ('aardvark', 'power', 'off'):
            aardvark_target_power = False
        else:
            print('Warning: unknown option %s' % name)

    try:
        if interface_name == 'aardvark':
            interface = pyipmi.interfaces.create_interface(
                interface_name, serial_number=aardvark_serial)
        else:
            interface = pyipmi.interfaces.create_interface(interface_name)
    except RuntimeError as e:
        print(e)
        sys.exit(1)

    if aardvark_pullups:
        interface.enable_pullups(aardvark_pullups)
    if aardvark_target_power:
        interface.enable_target_power(aardvark_target_power)

    ipmi = pyipmi.create_connection(interface)
    ipmi.target = pyipmi.Target(target_address)
    ipmi.target.set_routing(target_routing)

    if rmcp_host is not None:
        ipmi.session.set_session_type_rmcp(rmcp_host)
        ipmi.session.set_auth_type_user(rmcp_user, rmcp_password)
        ipmi.session.establish()

    try:
        cmd(ipmi, args)
    except pyipmi.errors.CompletionCodeError as e:
        print('Command returned with completion code 0x%02x' % e.cc)
        if verbose:
            traceback.print_exc()
        sys.exit(1)
    except pyipmi.errors.TimeoutError as e:
        print('Command timed out')
        if verbose:
            traceback.print_exc()
        sys.exit(1)
    except KeyboardInterrupt as e:
        if verbose:
            traceback.print_exc()
        sys.exit(1)

    if rmcp_host is not None:
        ipmi.session.close()
Пример #25
0
    for option in interface_options:
        (name, value) = option.split('=', 1)
        if (interface_name, name) == ('aardvark', 'pullups'):
            if value == 'on':
                interface.enable_pullups(True)
            else:
                interface.enable_pullups(False)
        elif (interface_name, name) == ('aardvark', 'power'):
            if value == 'on':
                interface.enable_target_power(True)
            else:
                interface.enable_target_power(False)
        else:
            print 'Warning: unknown option %s' % name

    ipmi = pyipmi.create_connection(interface)
    ipmi.target = pyipmi.Target(target_address)
    ipmi.target.set_routing_information(target_routing)

    if rmcp_host is not None:
        ipmi.session.set_session_type_rmcp(rmcp_host)
        ipmi.session.set_auth_type_user(rmcp_user, rmcp_password)
        ipmi.session.establish()

    try:
        cmd(ipmi, args)
    except pyipmi.errors.CompletionCodeError, e:
        print 'Command returned with completion code 0x%02x' % e.cc
        if verbose:
            traceback.print_exc()
        sys.exit(1)
Пример #26
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 't:hvVI:H:U:P:o:b:')
    except getopt.GetoptError as err:
        print(str(err))
        usage()
        sys.exit(2)
    verbose = False
    interface_name = 'aardvark'
    target_address = 0x20
    target_routing = [(0x20, 0)]
    rmcp_host = None
    rmcp_user = ''
    rmcp_password = ''
    interface_options = list()
    for o, a in opts:
        if o == '-v':
            verbose = True
        elif o == '-h':
            usage()
            sys.exit()
        elif o == '-V':
            version()
            sys.exit()
        elif o == '-t':
            target_address = int(a, 0)
        elif o == '-b':
            target_routing = [(0x20, int(a))]
        elif o == '-H':
            rmcp_host = a
        elif o == '-U':
            rmcp_user = a
        elif o == '-P':
            rmcp_password = a
        elif o == '-I':
            interface_name = a
        elif o == '-o':
            interface_options = a.split(',')
        else:
            assert False, 'unhandled option'

    # fake sys.argv
    sys.argv = [sys.argv[0]] + args

    if len(args) == 0:
        usage()
        sys.exit(1)

    handler = logging.StreamHandler()
    if verbose:
        handler.setLevel(logging.DEBUG)
    else:
        handler.setLevel(logging.INFO)
    pyipmi.logger.add_log_handler(handler)
    pyipmi.logger.set_log_level(logging.DEBUG)

    for i in range(len(args)):
        cmd = _get_command_function(' '.join(args[0:i+1]))
        if cmd is not None:
            args = args[i+1:]
            break
    else:
        usage()
        sys.exit(1)

    aardvark_serial = None
    aardvark_pullups = None
    aardvark_target_power = None

    for option in interface_options:
        (name, value) = option.split('=', 1)
        if (interface_name, name) == ('aardvark', 'serial'):
            aardvark_serial = value
        elif (interface_name, name, value) == ('aardvark', 'pullups', 'on'):
            aardvark_pullups = True
        elif (interface_name, name, value) == ('aardvark', 'pullups', 'off'):
            aardvark_pullups = False
        elif (interface_name, name, value) == ('aardvark', 'power', 'on'):
            aardvark_target_power = True
        elif (interface_name, name, value) == ('aardvark', 'power', 'off'):
            aardvark_target_power = False
        else:
            print('Warning: unknown option %s' % name)

    try:
        if interface_name == 'aardvark':
            interface = pyipmi.interfaces.create_interface(
                                                interface_name,
                                                serial_number=aardvark_serial)
        else:
            interface = pyipmi.interfaces.create_interface(interface_name)
    except RuntimeError as e:
        print(e)
        sys.exit(1)

    if aardvark_pullups:
        interface.enable_pullups(aardvark_pullups)
    if aardvark_target_power:
        interface.enable_target_power(aardvark_target_power)

    ipmi = pyipmi.create_connection(interface)
    ipmi.target = pyipmi.Target(target_address)
    ipmi.target.set_routing(target_routing)

    if rmcp_host is not None:
        ipmi.session.set_session_type_rmcp(rmcp_host)
        ipmi.session.set_auth_type_user(rmcp_user, rmcp_password)
        ipmi.session.establish()

    try:
        cmd(ipmi, args)
    except pyipmi.errors.CompletionCodeError as e:
        print('Command returned with completion code 0x%02x' % e.cc)
        if verbose:
            traceback.print_exc()
        sys.exit(1)
    except pyipmi.errors.IpmiTimeoutError as e:
        print('Command timed out')
        if verbose:
            traceback.print_exc()
        sys.exit(1)
    except KeyboardInterrupt as e:
        if verbose:
            traceback.print_exc()
        sys.exit(1)

    if rmcp_host is not None:
        ipmi.session.close()