IBM Cloud Docs
Controllo degli eventi di sistema per l'infrastruttura classica

Controllo degli eventi di sistema per l'infrastruttura classica

Se hai un account dell'infrastruttura classica, puoi monitorare gli eventi di replica dell'archiviazione visualizzando i log di controllo. I log di controllo tracciano le interazioni di ciascun utente, come i tentativi di accesso, gli aggiornamenti della velocità di porta, i riavvii dell'alimentazione e le interazioni effettuate dallo staff di supporto dell'infrastruttura IBM Cloud.

Visualizzazione del log di controllo nella console

Per visualizzare il registro di audit, andare su Gestione > Account nella console IBM Cloud® e selezionare Registro di audit. Il log di controllo visualizza inizialmente le ultime 25 interazioni effettuate dagli utenti nell'account. Puoi visualizzare fino a 200 interazioni in qualsiasi momento. Espandi il menu Elementi per pagina per visualizzare più risultati.

Visualizzazione dei log di accesso per un utente

Dalla pagina del log di controllo, puoi anche visualizzare i dati per ciascun tentativo di accesso effettuato da uno specifico utente. I registri visualizzano la data, il timestamp e l'indirizzo IP per ogni tentativo di accesso. Utilizza la seguente procedura per visualizzare i log di accesso di un utente.

  1. Vai a Gestisci > Account nella console IBM Cloud e seleziona Log di verifica.
  2. Quindi, filtrare per l'utente, selezionare l'intervallo di tempo che si desidera visualizzare e scegliere un tipo di oggetto.

Il log di accesso per ciascun utente visualizza i tentativi di accesso effettuati da tale utente per data, insieme all'indirizzo IP da cui è stato effettuato il tentativo. Le informazioni nel log di accesso sono di sola lettura.

Concessione dell'accesso al log di controllo

Il ruolo Visualizzatore o superiore su tutti i servizi di gestione account è richiesto per visualizzare il log di controllo. Per le autorizzazioni dell'infrastruttura classica, a un utente deve essere assegnato il ruolo Super utente.

Visualizzazione del log di controllo utilizzando l' SoftLayer API

Puoi utilizzare l' SoftLayer API per visualizzare il log di verifica. SoftLayer® Application Programming Interface è l'interfaccia di sviluppo che consente agli sviluppatori e agli amministratori di sistema di interagire direttamente con il sistema di backend di IBM Cloud. SoftLayer API potenzia molte delle funzioni disponibili nella console IBM Cloud, che in genere significa che se un'interazione è possibile nella console IBM Cloud, può essere eseguita anche nella API. Poiché è possibile interagire programmaticamente con tutte le parti dell'ambiente IBM Cloud all'interno dell'API, è possibile automatizzare le attività con SoftLayer API.

SoftLayer API è un sistema di chiamata di procedura remota. Ogni chiamata comporta l'invio di dati tramite l'endpoint API e la ricezione dei dati strutturati come ritorno. Il formato utilizzato per inviare e ricevere i dati con SoftLayer API dipende da quale implementazione API scegli. Il sito SoftLayer API utilizza attualmente SOAP, XML-RPC o REST per la trasmissione dei dati.

Per controllare programmaticamente gli eventi di sistema per l'infrastruttura classica, richiama SoftLayer API come mostrato nel seguente esempio:

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)
		}
	}
}

Per ottenere tutti i registri degli eventi, utilizzare SoftLayer_Event_Log::getAllObjects(). In questo caso, vengono restituiti solo i primi 50 eventi utilizzando il limite di paginazione resultLimit=0,50. Per ulteriori informazioni, vedi Using Result Limits in SoftLayer API. In questo esempio, mask[eventName,eventCreateDate,userType], viene mostrata una maschera che limita altri campi locali e la quantità di informazioni restituite.

Questo esempio tratta di alcuni modi per estrarre i dati da SoftLayer_Event_Log. Ci possono essere molti log, quindi utilizzando un filtro, come la funzione recentLogs, è possibile limitare il tempo di ricerca degli eventi.

Questo esempio tratta alcuni modi da cui estrarre i dati SoftLayer_Event_Log. L'ultima versione delSoftLayer API Cliente perJava (v0.3.2 al momento della pubblicazione di questo esempio) non supporta i filtri degli oggetti inSoftLayer API, quindi vengono utilizzati i filtri programmatici.

Questo esempio tratta di alcuni modi per estrarre i dati da SoftLayer_Event_Log. Ci possono essere molti log, quindi utilizzando un filtro, come la funzione getRecentLogs, è possibile limitare il tempo di ricerca degli eventi. Questo esempio utilizza il valore maxNumberOfEvents per limitare il numero di log eventi richiamati.

Per ulteriori informazioni sulla SoftLayer API e sulle API del server virtuale, consulta le seguenti risorse in SoftLayer® Development Network:

Per gli esempi di utilizzo dell'API, consulta le seguenti risorse: