IBM Cloud Docs
Sucesos del sistema de auditoría para la infraestructura clásica

Sucesos del sistema de auditoría para la infraestructura clásica

Si tiene una cuenta de infraestructura clásica, puede gestionar sucesos de réplica de almacenamiento visualizando registros de auditoría. Los registros de auditoría realizan un seguimiento de interacciones de cada usuario, como los intentos de inicio de sesión, las actualizaciones de la velocidad de puerto y las interacciones realizadas por el personal de soporte de la infraestructura de IBM Cloud.

Visualización del registro de auditoría en la consola

Para ver el registro de auditoría, vaya a Gestionar > Cuenta en la consola de IBM Cloud® y seleccione Registro de auditoría. El registro de auditoría muestra inicialmente las últimas 25 interacciones realizadas por los usuarios en la cuenta. Puede ver hasta 200 interacciones en cualquier momento. Expanda los artículos por menú de página para ver más resultados.

Visualización de registros de acceso de un usuario

Desde la página del registro de auditoría también puede ver los datos de cada intento de acceso que realiza un usuario específico. Los registros muestran una indicación de fecha y hora y la dirección IP por cada intento de acceso. Utilice los pasos siguientes para ver los Registros de acceso de un usuario.

  1. Vaya a Gestionar > Cuenta en la consola de IBM Cloud y seleccione Registro de auditoría.
  2. A continuación, filtre por usuario, seleccione el periodo de tiempo que desee visualizar y elija el tipo de objeto.

El registro de acceso para cada usuario muestra los intentos de acceso realizados por dicho usuario por fecha, junto con la dirección IP desde la que se ha realizado el intento de acceso. La información del registro de acceso es de solo lectura.

Cómo otorgar acceso al registro de auditoría

Se necesita el rol de visor o uno superior en todos los servicios de gestión de cuentas para visualizar el registro de auditoría. Para los permisos de infraestructura clásica, se debe asignar el rol de Superusuario a un usuario.

Visualización del registro de auditoría utilizando la API de SoftLayer

Puede utilizar la API de SoftLayer para ver el registro de auditoría. SoftLayer® Application Programming Interface es la interfaz de desarrollo que proporciona a los desarrolladores y administradores de sistemas la interacción directa con el sistema de fondo IBM Cloud. SoftLayer API potencia muchas de las características de la consola de IBM Cloud, lo que normalmente significa que si es posible una interacción en la consola de IBM Cloud, también se puede ejecutar en la API. Puesto que puede interactuar mediante programación con todas las partes del entorno IBM Cloud dentro de la API, puede automatizar tareas con SoftLayer API.

SoftLayer API es un sistema de llamada de procedimiento remoto. Cada llamada implica el envío de datos a un punto final de API y la recepción de datos estructurados. El formato utilizado para enviar y recibir datos con SoftLayer API depende de la implementación de la API que elija. SoftLayer API utiliza actualmente SOAP, XML-RPC o REST para la transmisión de datos.

Para auditar mediante programación los sucesos del sistema para la infraestructura clásica, llame a SoftLayer API tal como se muestra en el ejemplo siguiente:

https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?
                    resultLimit=0,50&
                    objectMask=mask[eventName,eventCreateDate,userType]

curl -g -u $SL_USER:$SL_APIKEY 'https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?objectMask=mask[eventName,eventCreateDate,userType]&resultLimit=0,50'

The output looks something like this, in this case just the first event in the list:

[
    {
        "eventCreateDate": "2021-03-29T14:41:55.444089-06:00",
        "eventName": "Login Successful",
        "userType": "CUSTOMER"
    }
  ]
import datetime
import SoftLayer

class example():

    def __init__(self):

        self.client = SoftLayer.Client()
        debugger = SoftLayer.DebugTransport(self.client.transport)
        self.client.transport = debugger

    def recentLogs(self):
        """REST API CALL
        'https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?
            resultLimit=0,50&
            objectFilter={"eventCreateDate":{"operation":"greaterThanDate","options":[{"name":"date","value":["2018-04-18T00:00:00.0000-06:00"]}]}}'
        """
        _filter = {
            'eventCreateDate': {
                'operation': 'greaterThanDate',
                'options': [
                    {'name': 'date', 'value': [getDateString(30)]}
                ]
            }
        }
        for event in self.getAllObjects(_filter):
            printLogs(event)

    def systemLogs(self):
        """REST API CALL
        'https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?
            resultLimit=0,50&
            objectFilter={"userType":{"operation":"SYSTEM"}}'
        """
        _filter = {'userType': {'operation': 'SYSTEM'}}
        for event in self.getAllObjects(_filter):
            printLogs(event)

    def loginLogs(self):
        """REST API CALL
        https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?
            resultLimit=0,50&
            objectFilter={"eventName":{"operation":"^= Login"}}'
        """
        _filter = {
            'eventName': {
                'operation': '^= Login'
            }
        }
        for event in self.getAllObjects(_filter):
            printLogs(event)

    def allLogs(self):
        """REST API CALL
        'https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?resultLimit=0,50'
        """
        for event in self.getAllObjects(None):
            printLogs(event)


    def getAllObjects(self, _filter, limit=50, offset=0):
        """Pages through all results from the Event_Log. This might take long time."""
        notDone = True
        while notDone:
            events = self.client.call('SoftLayer_Event_Log', 'getAllObjects', filter=_filter, limit=limit, offset=offset)
            print("%s from getAllObjects, offset = %s" % (len(events), offset))

            for event in events:
                yield event
            if len(events) < limit:
                notDone = False
            offset = offset + limit
            notDone = False

    def debug(self):
        for call in self.client.transport.get_last_calls():
            print(self.client.transport.print_reproduceable(call))


def getDateString(self, delta=30):
    date_object = datetime.date.today() - datetime.timedelta(days=delta)
    return date_object.strftime("%Y-%m-%dT00:00:00.0000-06:00")

def printLogs(log):
    print("%s - %s - %s" % (log['eventName'],log['eventCreateDate'], log['userType']))

if __name__ == "__main__":
    main = example()
    main.allLogs()
    main.debug()
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.softlayer.api.ApiClient;
import com.softlayer.api.RestApiClient;
import com.softlayer.api.ResultLimit;
import com.softlayer.api.service.event.Log;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class EventLogExample {
  private final ApiClient client;
  private final Log.Service  logService;
  public EventLogExample() {
    String username = "set-me";
    String apiKey = "set-me";
    client = new RestApiClient().withCredentials(username, apiKey).withLoggingEnabled();
    logService = Log.service(client);
  }
  public static void main(String[] args) {
    EventLogExample eventLogExample = new EventLogExample();
    eventLogExample.getAllTypes();
    eventLogExample.getUserTypes();
    eventLogExample.allLogs();
    eventLogExample.loginLogs();
    eventLogExample.recentLogs();
    eventLogExample.systemLogs();
  }
  /**
   * Running GET on https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/AllEventObjectNames.json with no body
   */
  private void getAllTypes() {
    print(logService.getAllEventObjectNames());
  }
  /***
   * Running GET on https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/AllUserTypes.json with no body
   */
  private void getUserTypes() {
    print(logService.getAllUserTypes());
  }
  /***
   * Running GET on https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/AllObjects.json?resultLimit=0,50 with no body
   */
  private void systemLogs() {
    List<Log> logs=getAllEvents(false);
    String systemName="SYSTEM";
    List<Log> systemLogs = logs.stream()
            .filter(log -> systemName.equalsIgnoreCase(log.getEventName()))
            .collect(Collectors.toList());
    printEventLogs(systemLogs);
  }
  /**
   * Running GET on https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/AllObjects.json?resultLimit=0,50 with no body
   */
  private void recentLogs() {
    LocalDate daysAgo = LocalDate.now().minusDays(30);
    List<Log> logs=getAllEvents(false);
    List<Log> recentLogs = logs.stream()
            .filter(log -> log.getEventCreateDate()
                    .toZonedDateTime()
                    .toLocalDate()
                    .compareTo(daysAgo)>0)
            .collect(Collectors.toList());
    printEventLogs(recentLogs);
  }
  /**
   * Running GET on https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/AllObjects.json?resultLimit=0,50 with no body
   */
  private void loginLogs() {
    List<Log> logs=getAllEvents(false);
    String loginName="login";
    List<Log> loginLogs = logs.stream()
            .filter(log -> log
                    .getEventName()
                    .toLowerCase()
                    .contains(loginName))
            .collect(Collectors.toList());
    printEventLogs(loginLogs);
  }
  /**
   * Running GET on https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/AllObjects.json?resultLimit=0,50 with no body
   */
  private void allLogs() {
    printEventLogs(getAllEvents(false));
  }
  /**
   * Pages through all results from the Event_Log. This might take long time.
   */
  private List<Log> getAllEvents(boolean allEvents) {
    List<Log> result=new ArrayList<>();
    int limit =50;
    int offset =0;
    ResultLimit resultLimit =new ResultLimit(offset,limit);
    boolean iterateEvents=true;
    while(iterateEvents) {
      logService.setResultLimit(resultLimit);
      List<Log> logs = logService.getAllObjects();
      result.addAll(logs);
      if (logs.size() < resultLimit.limit) {
        iterateEvents = false;
      }
      offset+=limit;
      resultLimit=new ResultLimit(offset,limit);
      iterateEvents=iterateEvents&&allEvents;
    }
    return result;
  }
  void print(Object object) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json;
    json = gson.toJson(object);
    System.out.println(json);
  }
  void printEventLogs(List<Log> logs){
    for (Log event :logs) {
      System.out.println(String.format("%s - %s - %s",
                      event.getEventName(),
                      event.getEventCreateDate().getTime(),
                      event.getUserType()));
    }
  }
}
package main

import (
	"encoding/json"
	"fmt"
	"github.com/softlayer/softlayer-go/datatypes"
	"github.com/softlayer/softlayer-go/filter"
	"github.com/softlayer/softlayer-go/services"
	"github.com/softlayer/softlayer-go/session"
	"time"
)

// Session created using values set in the environment, or from the local configuration file (i.e. ~/.softlayer).
var sess = session.New()

// Set the limit number of events that the API retrieves in each SoftLayer_Event_Log::getAllObjects  method call.
var pagination = 50

// Set the max number of events to retrieve in each log example function.
var maxNumberOfEvents =200

func main() {

	sess.Debug = true

	//shows the all user type events
	getEventUserTypes()
	userType:="EMPLOYEE"
	//shows the events with names is a userType value
	getLogsByUserType(userType)

	//shows the all user type events
	getEventNames()
	eventName:="Authentication"
	//shows the events which names contain the eventName value
	getLogsByName(eventName)

	//shows the events created from a specific number of days ago
	daysAgo:=30
	getRecentLogs(daysAgo)

	//shows the system logs
	getSystemLogs()

	//shows the login logs
	getLoginLogs()
}

/**
Shows the Event Logs by user type.
Request URL:
GET https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?
objectFilter={"userType":{"operation":"userType"}}&
objectMask=mask[userType,eventName,eventCreateDate]&
resultLimit=0,50
*/
func getLogsByUserType(eventUserType string) {
	filter := filter.Build(filter.Path("userType").Eq(eventUserType))
	mask:="userType,eventName,eventCreateDate"
	systemEvents:=getAllEvents(filter,mask,pagination,maxNumberOfEvents)
	printLogs(systemEvents)
}

/**
Shows the Event Logs which eventName contains nameQuery value
RequestURL:
GET https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?
objectFilter={"eventName":{"operation":"^=+nameQuery"}}&
objectMask=mask[userType;eventName,eventCreateDate]&
resultLimit=0,50
*/
func
getLogsByName(nameQuery string){
	filterQuery:=fmt.Sprintf("^= %s",nameQuery)
	filter := filter.Build(filter.Path("eventName").Eq(filterQuery))
	mask:="userType;eventName,eventCreateDate"
	eventLogs :=getAllEvents(filter,mask,pagination,maxNumberOfEvents)
	printLogs(eventLogs)
}


/**
Shows the SYSTEM Logs.
Request URL:
GET https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?
objectFilter={"userType":{"operation":"SYSTEM"}}&
objectMask=mask[userType,eventName,eventCreateDate]&
resultLimit=0,50
*/
func getSystemLogs(){
	getLogsByUserType("SYSTEM")
}

/**
Shows the Login Logs
RequestURL:
GET https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?
objectFilter={"eventName":{"operation":"^=+Login"}}&
objectMask=mask[userType;eventName,eventCreateDate]&
resultLimit=0,50
*/
func getLoginLogs(){
	getLogsByName("Login")
}

/**
Shows the recent Logs, based on a number of days ago.
Request URL:
GET https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?
objectFilter={"eventCreateDate":{"operation":"greaterThanDate",
	"options":[{"name":"date","value":["2021-04-24T00:00:00.0000-06:00"]}]}}&
objectMask=mask[userType;eventName,eventCreateDate]&
resultLimit=0,50
*/
func getRecentLogs(daysAgo int){
	offsetDate :=getDateString(-daysAgo)
	filterObject:=filter.Build(filter.Path("eventCreateDate").DateAfter(offsetDate))
	mask:="userType;eventName,eventCreateDate"
	recentEvents:=getAllEvents(filterObject,mask,pagination,maxNumberOfEvents)
	printLogs(recentEvents)
}

/**
Pages through all results from the Event_Log. This might take long time.
*/
func getAllEvents(
	filter string,
	mask string,
	pagination int,
	maxNumberOfEvents int,
) (resp []datatypes.Event_Log) {
	limit:=pagination
	offset:=0
	eventsSize:=limit
	var allEvents []datatypes.Event_Log
	for eventsSize<=maxNumberOfEvents {
		events := getAllObjects(limit,offset,filter,mask)
		// return if the events are a list of empty structure like [{}]
		if events[0]==(datatypes.Event_Log{}){
			return allEvents
		}
		allEvents=append(allEvents, events...)
		eventsSize=eventsSize+pagination
	}
	return allEvents
}

/**
Request URL:
GET https://api.softlayer.com/rest/v3.1/SoftLayer_Event_Log/getAllObjects.json?
objectFilter= filter &
objectMask= mask &
resultLimit=0,50

It returns an array of Event_Log encountered.
*/
func getAllObjects(
	limit int,
	offset int,
	filter string,
	mask string,
) (resp []datatypes.Event_Log) {
	var service = services.GetEventLogService(sess)
	result, err := service.
		Limit(limit).
		Offset(offset).
		Filter(filter).
		Mask(mask).
		GetAllObjects()
	if err != nil {
		fmt.Printf("\n Unable to get Events:\n - %s\n", err)
		return
	}

	return result
}

/**
Shows the Event Logs Names.
*/
func getEventNames(){
	var service = services.GetEventLogService(sess)
	result, err := service.GetAllEventObjectNames()
	if err != nil {
		fmt.Printf("\n Unable to get Events:\n - %s\n", err)
		return
	}
	printAsJsonFormat(result)
}

/**
Shows the Event Logs User Types.
*/
func getEventUserTypes() {
	var service = services.GetEventLogService(sess)
	result, err := service.GetAllUserTypes()
	if err != nil {
		fmt.Printf("\n Unable to get User types:\n - %s\n", err)
		return
	}
	printAsJsonFormat(result)
}

/**
Gets a date offset in days determined by offsetDays value.
It returns a string date with SL API date filtering format.
*/
func getDateString(offsetDays int) (resp string) {
	years:=0
	months:=0
	days:= offsetDays
	offsetTime:=time.Now().AddDate(years,months,days)
	return fmt.Sprintf(
		"%d-%02d-%02dT00:00:00.0000-06:00",
		offsetTime.Year(),
		offsetTime.Month(),
		offsetTime.Day())
}

/**
Prints the data as format JSON.
*/
func printAsJsonFormat(data interface{}){
	jsonData, jsonErr := json.MarshalIndent(data, "", "    ")
	if jsonErr != nil {
		fmt.Println(jsonErr)
		return
	}
	println(string(jsonData))
}

/**
Prints the Event Logs.
*/
func printLogs(logs []datatypes.Event_Log){
	fmt.Printf("| %35s | %25s |%10s |\n","Event Name","Event Create Date","User Type")
	for _, log := range logs {
		if log!=(datatypes.Event_Log{}){
			fmt.Printf("| %35s ", *log.EventName)
			fmt.Printf("| %25s ", log.EventCreateDate)
			fmt.Printf("| %10s |\n", *log.UserType)
		}
	}
}

Para obtener todos los registros de sucesos, utilice SoftLayer_Event_Log::getAllObjects (). En este caso, solo se devuelven los primeros 50 sucesos utilizando el límite de paginación resultLimit=0,50. Para obtener más información, consulte Utilización de límites de resultados en la API de SoftLayer. En este ejemplo se muestra una máscara, mask[eventName,eventCreateDate,userType], que restringe otros campos locales y limita la cantidad de información devuelta.

Este ejemplo trata algunas formas de extraer datos de SoftLayer_Event_Log. Puede haber muchos registros, por lo que puede limitar el tiempo de búsqueda de sucesos utilizando un filtro como la función recentLogs.

Este ejemplo trata algunas formas de extraer datos de SoftLayer_Event_Log. La versión más reciente del cliente API de SoftLayer para Java (v0.3.2 en el momento de publicar este ejemplo) no admite filtros de objeto en la API de SoftLayer, por lo que en su lugar se utilizan filtros programáticos.

Este ejemplo trata algunas formas de extraer datos de SoftLayer_Event_Log. Puede haber muchos registros, por lo que puede limitar el tiempo de búsqueda de sucesos utilizando un filtro como la función getRecentLogs. En este ejemplo se utiliza el valor maxNumberOfEvents para limitar el número de registros de sucesos que se recuperan.

Para obtener más información sobre las API de servidor virtual y de SoftLayer API, consulte los recursos siguientes en SoftLayer® Development Network:

Para ver ejemplos de uso de la API, consulte los siguientes recursos: