Study points for the RHCSA exam

From Sinfronteras
Revision as of 18:21, 16 June 2018 by Adelo Vieira (talk | contribs) (Remplace)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Red Hat reserves the right to add, modify, and remove objectives. Such changes will be made public in advance through revisions to this document.

RHCSA exam candidates should be able to accomplish the tasks below without assistance. These have been grouped into several categories.

Contents

Understand and use essential tools

Access a shell prompt and issue commands with correct syntax

Use input-output redirection (>, >>, |, 2>, etc.)

< redirige stdin

1> or > redireccionar la stdout

'1>> or >> ajoute stdout (en fin de fichier)

File descriptor 1 is the standard output (stdout).

2> redirige stderr

2>> ajoute stderr (en fin de fichier)

File descriptor 2 is the standard error (stderr).

&> or >& redirige stdout et stderr

2> &1 redirige stderr sur stdout

> &2 redirige stdout sur stderr

Sometimes you want to redirect both stdout and stderr to the same location, This is when >& is used. It points one file descriptor to another.

For example, if you want to write both stdout and stderr to the same file (be it /dev/null or output.txt), you can redirect them separately, with

app 1>/dev/null 2>/dev/null

or you could redirect one fd to the file, and the other fd into the first one:

app 1>/dev/null 2>&1
app 2>/dev/null 1>&2

In the first example, 2>&1 points fd #2 to where #1 is already pointing. The second example achieves the same, just starting with stderr instead.

A common example is a pager, or grep, or similar utility, since the pipe | normally only works on stdout, you would redirect stderr to stdout before using the pipe:

app 2>&1 | grep hello

Some shells have shortcuts for common redirections; here are examples from Bash:

1> can be shortened to just >
1>foo 2>&1 to >&foo or &>foo
2>&1 | program to |& program

Use grep and regular expressions to analyze text

Regular expressions

. caractérise n’importe quel caractère

* signifie de 0 à n fois le caractère qui précède

  • a* 0 à n fois a. En grep, esta expresión imprimirá todas las líneas del archivo debido a que el comando buscará líneas que contenta de 0 a n a.
  • aa* au moins un a. En grep, esta expresión imprimirá todas las líneas que contengan al menos una a.
  • aaa* au moins deux a. En grep, esta expresión imprimirá todas las líneas que contengan al menos dos a seguidas (aa).
  • .* n’importe quelle chaîne de caractères (y compris la chaîne vide)

[] un des caractères entre crochets

[abc] a, b ou c
[a-z] une lettre minuscule
[a-d5-8w-z] a, b, c, d, 5, 6, 7, 8, w, x, y, z

[^ ] si le premier caractère est ^, alors caractérise ceux qui ne correspondent pas avec ceux entre crochet.

[^a-zA-Z] pas une lettre

En el caso de grep, al usar la opción [^ ] el comando desplegará todas las líneas del archivo, pero serán resaltadas (en rojo) todos los caracteres que no correspondan con la expresión especificada después del ^. Por ejemplo:

grep [^0-9] despliega todas las líneas del archivo y resalta en rojo todo lo que no es un número.

Si queremos que no sean desplegadas las líneas que contienen 0-9, debemos usar la opción -v del comando grep

egrep -v [7-9] passwd


^ début de ligne

  • Líneas que empiezan por c:
egrep ^c passwd
egrep ^[c] passwd
  • Líneas que empiezan por me:
egrep ^me passwd
  • Líneas que empiezan por "c" o por "d":
egrep ^[cd] passwd


$ fin de ligne

  • Líneas que finalizan por c:
egrep c$ passwd
egrep [c]$ passwd

Lignes qui ne contient que des chiffres

^[0-9][0-9]*$

\( \) isoler des sous-chaînes. On peut les réutiliser grâce à \1 \2. Ver ejemplo en con sed

grep - egrep

egrep [options] [expression] [fichier]

Algunas opciones:

  • -i pas de différence entre majuscule et minuscule
  • -c compte le nombre de lignes
  • -v inverse le résultat
  • -n despliega el número de línea


Algunos ejemplos:

Número de líneas en donde se encuentra la palabra bash:
egrep -c bash/etc/passwd
3
egrep -c BASH/etc/passwd
0
egrep -ci BASH/etc/passwd
3
Número de líeas en donde NO se encuentra la palabra bash: 
egrep -civ BASH/etc/passwd
33
Líneas en donde se encuentra ba o sa
egrep "ba|sa" /etc/passwd

find

http://www.binarytides.com/linux-find-command-examples/

find [chemin] [expression...]
Searches for files by their name -name -iname
find ./test -name "abc.txt"
find ./test -name "*.php"

Para que no haya distinción entre mayúsculas y minúsculas usamos la opción -iname:

find ./test -iname "*.Php"
Limit depth of directory traversal -maxdepth
find ./test -maxdepth 2 -name "*.php"
./test/subdir/how.php
./test/cool.php
find ./test -maxdepth 1 -name *.php
./test/cool.php
Search for files that do no match a given name or pattern -not !
find ./test -not -name "*.php"
./test
./test/abc.txt
./test/subdir

También podemos usar ! en lugar de -not:

find ./test ! -name "*.php"
Combine multiple search criterias
find ./test -name 'abc*' ! -name '*.php'
./test/abc.txt
./test/abc

The above find command looks for files that begin with abc in their names and do not have a php extension.

OR operator

When using multiple name criterias, the find command would combine them with AND operator, which means that only those files which satisfy all criterias will be matched. However if we need to perform an OR based matching then the find command has the "o" switch.

find -name '*.php' -o -name '*.txt'
./abc.txt
./subdir/how.php
./abc.php
./cool.php

The above command search for files ending in either the php extension or the txt extension.

Search only files or only directories

Only files: -type f:

find ./test -type f -name "abc*"
./test/abc.txt

Only directories: -type d:

find ./test -type d -name "abc*"
./test/abc
Search multiple directories together
find ./test ./dir2 -type f -name "abc*"
./test/abc.txt
./dir2/abcdefg.txt
Find hidden files
find ~ -type f -name ".*"

Filtre-éditeur sed

Commande très puissante (presque un mini-langage de script)

Remplace

Reemplazar cadenas de caracteres en archivos de texto.

sed 's/regexp/replacement/g' file

Quelques remarques :

  • Es importante notar que el delimitador (en el ejemplo /) puede ser cualquier caractér. Esto es de utilidad cuando el string que queremos reemplazar comtiene «/». En este caso podemos usar otro delimitador (~ por ejemplo) para que el comando no tome el «/» del string ingresado como un delimitador.
  • -i : Por defecto, sed no modifica el «file» sino que imprime el resultado en consola. Si queremos que el «file» sea editado debemos usar la opción -i.
  • 's/regexp/replacement/'  : realizará un sólo reemplazo por línea
  • 's/regexp/replacement/g' : con la opción g al final se realizarán varios reemplazos por cada línea
$ echo -e "Du:texte:en:colonnes\nEt:sur:deux:lignes" > colonnes.txt && more colonnes.txt
Du:texte:en:colonnes
Et:sur:deux:lignes


$ sed 's/te/tt/' colonnes.txt
Du:ttxte:en:colonnes
Et:sur:deux:lignes
  • De la forma anterior, el archivo «colonnes.txt» no es modificado, el resultado anterior se imprime en cónsola.
  • Sólo se reemplaza el primer match encontrado en la línea.


$ sed -i 's/te/tt/g' colonnes.txt && more colonnes.txt
Du:ttxtt:en:colonnes
Et:sur:deux:lignes
  • De la forma anterior, el archivo «colonnes.txt» será modificado.
  • Se reemplazaran todos los matchs encontrados en cada línea.


También se pueden realizar cambios en varios archivos a la vez:

$ sed -i 's/te/tt/g' colonnes.txt otro.txt
$ sed -i 's/te/tt/g' *

En caso de que querramos reemplazar en todos los archivos (*) hay que considerar que sed lanza un error cuando encuentra un archivo que no es un archivo regular de texto (sed: couldn't edit assignment: not a regular file) y luego que lanza este error no continúa la ejecución hacia los otros archivos. Leer el siguiente post: https://unix.stackexchange.com/questions/356437/passing-regular-files-only-to-sed-i


$ echo "ceci est un poids : 676Kg" | sed -e 's/^[^0-9]*\([0-9][0-9]*\).*/Valeur=\1/'
Valeur=676
^[^0-9]* : Depuis le debut de la ligne prendre un caractère qui n'est pas un chiffre répété * fois.
\([0-9][0-9]*\) : Capture un chiffre suivi d'un autre chiffre répété * fois.
\1 : Le chiffre qu'on a capturé est placé grace à cet expression.

touch

Modifie la date d’accès et la date de modification d’un fichier; les fichiers n’existant pas sont créés, leur contenu est vide. Souvent utilisé pour créer des fichiers vides.

cat

Para desplegar el número de línea:

cat -n file

The -b / --number-nonblank option number all nonempty output lines, starting with one and the syntax is:

cat -b file
cat > file.txt
<texte frappé au clavier>
Ctrl + D

more

Afficher le contenu d’un fichier page par page.

tail

Donne les dernières lignes d’un fichier.

tail [-n number] [filename...]

heat

Donne les n premières lignes du fichier. Par défaut, n = 10

head [-number j -n number] [filename...]

wc

Compte le nombre de lignes, de mots et de caractères des fichiers.

wc [options] [<fichier> ...]

-w (words),-l (lines),-c (Characters)

wc prueba.txt
1 10 52 prueba.txt

cut

Permet de découper les lignes d’un fichier en champs et d’extraire des champs particuliers

cut -f<liste> [-d<caractère>]

How to cut by byte position: -b

echo 'baz' | cut -b 2
a
echo 'baz' | cut -b 1-2
ba
echo 'baz' | cut -b 1,3
bz

How to cut by character: -c

How to cut based on a delimiter: -d<delimiter> -f<field that should be cut>

names.csv
John,Smith,34,London
Arthur,Evans,21,Newport
George,Jones,32,Truro


cut -d',' -f1,4 names.csv
John,London
Arthur,Newport
George,Truro

How to cut by complement pattern: --complement

echo 'foo' | cut --complement -c 1
oo

In the following example the -c option is used to select the first character. Because the --complement option is also passed to cut the second and third characters are cut.

How to modify the output delimiter: --output-delimiter

echo 'how;now;brown;cow' | cut -d ':' -f 1,3,4 --output-delimiter=' '
how brown cow

tr

tr [option] [set1] [set2]

Convertir minúsculas en mayúsculas o viceversa

echo "essai : tagada" | tr a-z A-Z
ESSAI : TAGADA
echo "essai : tagada" | tr [:lower:] [:upper:]
tr <file.txt a-z A-Z

Eliminar espacios en blanco

echo "essai :         tagada" | tr -s " "
essai : tagada

sort

sort is a simple and very useful command which will rearrange the lines in a text file so that they are sorted, numerically and alphabetically. By default, the rules for sorting are:

sort [OPTION]... [FILE]...

  • Lines starting with a number will appear before lines starting with a letter;
  • Lines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in the alphabet;
  • Lines starting with a lowercase letter will appear before lines starting with the same letter in uppercase.

The rules for sorting can be changed according to the options you provide to the sort command; these are listed below:

Algunas opciones:

  • -r, --reverse: Reverse the result of comparisons.
  • -t séparateur
  • -k champ

Let's say you have a file, data.txt, which contains the following ASCII text:

apples
oranges
pears
kiwis
bananas
sort data.txt  will produce the following output:
apples
bananas
kiwis
oranges
pears

Note que por defecto el comando sort reescribe el mismo archivo. Si queremos que el resultado sea escrito en otro archivo debemos:

  • Usar la opción -o:
sort -o output.txt data.txt
  • o redireccionar la salida hacia un archivo:
sort data.txt > soutput.txt

Opción -k

For instance, if you have an input file data.txt With the following data:

01 Joe
02 Marie
03 Albert
04 Dave

...and you sort it without any options, obtendrás el mismo archivo. If you want to sort based on the names, you can use the option -k:

sort -k2 data.txt

This command will sort the second field, and ignore the first. It will produce the following output:

03 Albert
04 Dave
01 Joe
02 Marie

Opción -t

Si nuestro input file data.txt es así:

01:Joe
02:Marie
03:Albert
04:Dave

... y queremos ordenar en base a los nombres, debemos indicar que el separador de campos es : (ya que el comando considera el espacio en blanco como el separador por defecto).

sort -t: -k2 data.txt

Algunos ejemplos

cat /etc/passwd | grep adelo | cut -f7 -d:
/bin/bash
cat /etc/passwd | grep adelo | cut -f7 -d: | sed -e 's/\//*/'
*bin/bash
cat /etc/passwd | grep adelo | cut -f7 -d: | sed -e 's/\//*/g'
*bin*bash

Access remote systems using ssh

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/ch-OpenSSH.html

SSH (Secure Shell) is a protocol which facilitates secure communications between two systems using a client-server architecture and allows users to log in to server host systems remotely. Unlike other remote communication protocols, such as FTP or Telnet, SSH encrypts the login session, rendering the connection difficult for intruders to collect unencrypted passwords. The ssh program is designed to replace older, less secure terminal applications used to log in to remote hosts, such as telnet or rsh. A related program called scp replaces older programs designed to copy files between hosts, such as rcp. https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/ch-OpenSSH.html

Red Hat Enterprise Linux includes the general OpenSSH package, openssh, as well as the OpenSSH server, openssh-server, and client, openssh-clients, packages. Note, the OpenSSH packages require the OpenSSL package openssl-libs, which installs several important cryptographic libraries, enabling OpenSSH to provide encrypted communications.

Why Use SSH

Potential intruders have a variety of tools at their disposal enabling them to disrupt, intercept, and re-route network traffic in an effort to gain access to a system. In general terms, these threats can be categorized as follows:

Interception of communication between two systems:

The attacker can be somewhere on the network between the communicating parties, copying any information passed between them. He may intercept and keep the information, or alter the information and send it on to the intended recipient.

This attack is usually performed using a packet sniffer, a rather common network utility that captures each packet flowing through the network, and analyzes its content.

Impersonation of a particular host:

Attacker's system is configured to pose as the intended recipient of a transmission. If this strategy works, the user's system remains unaware that it is communicating with the wrong host.

This attack can be performed using a technique known as DNS poisoning, or via so-called IP spoofing. In the first case, the intruder uses a cracked DNS server to point client systems to a maliciously duplicated host. In the second case, the intruder sends falsified network packets that appear to be from a trusted host.

Main Features

The SSH protocol provides the following safeguards:

No one can pose as the intended server

After an initial connection, the client can verify that it is connecting to the same server it had connected to previously.


No one can capture the authentication information

The client transmits its authentication information to the server using strong, 128-bit encryption.


No one can intercept the communication

All data sent and received during a session is transferred using 128-bit encryption, making intercepted transmissions extremely difficult to decrypt and read.


Additionally, it also offers the following options:

It provides secure means to use graphical applications over a network:

Using a technique called X11 forwarding, the client can forward X11 (X Window System) applications from the server.

It provides a way to secure otherwise insecure protocols:

The SSH protocol encrypts everything it sends and receives. Using a technique called port forwarding, an SSH server can become a conduit to securing otherwise insecure protocols, like POP, and increasing overall system and data security.

It can be used to create a secure channel:

The OpenSSH server and client can be configured to create a tunnel similar to a virtual private network for traffic between server and client machines.

It supports the Kerberos authentication:

OpenSSH servers and clients can be configured to authenticate using the GSSAPI (Generic Security Services Application Program Interface) implementation of the Kerberos network authentication protocol.

Log in and switch users in multiuser targets

Archive, compress, unpack, and uncompress files using tar, star, gzip, and bzip2

Create and edit text files

Create, delete, copy, and move files and directories

Create hard and soft links

List, set, and change standard ugo/rwx permissions

Locate, read, and use system documentation including man, info, and files in /usr/share/doc

Operate running systems

Boot, reboot, and shut down a system normally

To reboot the system, choose one command among these

# reboot
# shutdown -r now
# init 6

To shutdown the system, choose one command among these

# shutdown -h now
# init 0

To switch off the system, choose one command among these

# halt
# poweroff

Boot systems into different targets manually

Runlevel - Targets Definition

http://www.linfo.org/runlevel_def.html

A runlevel is a preset operating state on a Unix-like operating system.

A system can be booted into (i.e., started up into) any of several runlevels. They allow access to a different combination of processes (i.e., instances of executing programs).

Booting into a different runlevel can help solve certain problems. For example, if a change made in the X Window System configuration on a machine that has been set up to boot into a GUI has rendered the system unusable, it is possible to temporarily boot into a console (i.e., all-text mode) runlevel (i.e., runlevels 3 or 1) in order to repair the error and then reboot into the GUI. The X Window System is a widely used system for managing GUIs on single computers and on networks of computers.

Likewise, if a machine will not boot due to a damaged configuration file or will not allow logging in because of a corrupted /etc/passwd file (which stores user names and other data about users) or because of a forgotten password, the problem can solved by first booting into single-user mode (i.e. runlevel 1).


https://www.certdepot.net/rhel7-boot-systems-different-targets-manually/

Systemd: Current State

With Systemd, new commands are available:

  • systemctl rescue: to move to single user mode/maintenance level with mounted local file systems,
  • systemctl emergency: to move to single user mode/maintenance with only /root mounted file system,
  • systemctl isolate multi-user.target: to move to multi-user level without graphical interface (equivalent to previous run level 3),
  • systemctl isolate graphical.target: to move to multi-user level with graphical interface (equivalent to previous run level 5),
  • systemctl set-default graphical.target: to set the default run level to multi-user graphical mode,
  • systemctl get-default: to get the default run level.

To boot into a systemd target from the grub menu, append to the kernel line for example:

systemd.unit=graphical.target

Init: In the old days

Before Systemd.

The are differences in the runlevels according to the operating system. Seven runlevels are supported in the standard Linux kernel (i.e., core of the operating system). They are:

  • 0: System halt; no activity, the system can be safely powered down.
  • 1: Single user: maintenance level. Rarely used.
  • 2: Multiple users. without network resources (no NFS[network filesystem], etc). Also used rarely
  • 3: multi-user level without graphical interface. The standard runlevel for most Linux-based server hardware.
  • 4: User-definable.
  • 5: multi-user level with graphical interface. The standard runlevel for most Linux-based desktop systems.
  • 6: rebooting.

To get the current run level:

runlevel

To change the current run level (where X is the run level), type:

init X

The default runlevel for a system is specified in the /etc/inittab file, which will contain an entry such as id:3:initdefault: if the system starts in runlevel 3, or id:5:initdefault: if it starts in runlevel 5.

The runlevel into which the system boots can be changed by modifying /etc/inittab manually with a text editor. However, it is generally easier and safer (i.e., less chance of accidental damage to the file) to use telinit. It is always wise to make a backup copy of /etc/inittab or any other configuration file before attempting to modify it manually.

Interrupt the boot process in order to gain access to a system

https://www.certdepot.net/rhel7-interrupt-boot-gain-access-system/

Ver la discusión que, en la página listada arriba, se hace acerca de la existencia de otros métodos más rápidos y de la importancia del ahorro de tiempo en el examen.

Note: This is a critical RHCSA 7 exam objective (if you can’t take control of a VM through a reboot at the beginning of the exam, you will fail it entirely). Presentation

In RHEL 7, the procedure to get access to a system during the boot process and modify the root password has changed because of the adoption of Systemd.

There were several procedures floating around to recover the root password. Some were working with physical servers but not with virtual machines, some the other way around.

The following procedure works all the time. Procedure

At the beginning of the boot process, at the GRUB 2 menu, type the e key to edit.
Then, go to the kernel line (the line starting with linux16) and add the following statements at the end:
rd.break enforcing=0

Caution: The keys to press are those of a US keyboard (querty). Note: rd.break asks for a break at an early stage of the boot process. enforcing=0 puts the system into SELinux Permissive mode. Don’t confuse with selinux=0 that completely disables SELinux.

Press Ctrl x to resume the boot process
Then, mount the /sysroot partition as read/write:
mount –o remount,rw /sysroot
Execute the chroot command on the /sysroot partition:
chroot /sysroot

Change the root password:

sh-4.2# passwd root
Changing password for user root.
New passwd: mypassword
Retype new password: mypassword
passwd: all authentication token updated successfully.
sh-4.2# exit
exit
switch_root:/# exit
logout


Connect to your server at the console (don’t reboot now!) with the root user and the new password:
...
[  OK  ] Started Network Manager Script Dispatcher Service.
[  OK  ] Started Crash recovery kernel arming.
[  OK  ] Reached target Multi-User System.
...
CentOS Linux 7 (Core)
Kernel 3.10.0-229.14.1.el7.x86_64 on an x86_64
...
vm login: root
Password: mypassword
Then type:
restorecon /etc/shadow
reboot

If you strictly follow this procedure, you don’t need to force a SELinux relabel (# touch /.autorelabel) or load the SELinux policy (# /usr/sbin/load_policy -i).

You don’t even need to reboot at the end! In this case, type
setenforce enforcing

For the RHCSA exam, you need to intensely practice this procedure.


https://github.com/ahaitoute/RHCSA-notitie/blob/master/2-Operate%20running%20systems/3-Interrupt%20the%20boot%20process%20in%20order%20to%20gain%20access%20to%20a%20system.md

Identify CPU/memory intensive processes, adjust process priority with renice, and kill processes

What is a process

https://en.wikipedia.org/wiki/Process_(computing)

In computing, a process is an instance of a computer program that is being executed.

A computer program is a passive collection of instructions, while a process is the actual execution of those instructions.

top: To get a dynamic real-time view of a running system - processes being managed by the Linux kernel

https://www.certdepot.net/sys-identify-cpu-memory-intensive-processes/

The top program provides a dynamic real-time view of a running system. It can display system summary information as well as a list of processes or threads currently being managed by the Linux kernel.

top
(use ‘virt-top‘ on a KVM hypervisor)

ps: To get details about processes

ps -edf
ps -eF
ps -ely

Para ver el arbol de procesos (parent/child process tree): https://docs.oseems.com/general/operatingsystem/linux/view-process-tree

ps auxf
pstree

Process Priority

https://www.nixtutor.com/linux/changing-priority-on-linux-processes/

The Processor or CPU is like a human juggling multiple tasks at the same time. Sometimes we can have enough room to take on multiple projects. Sometimes we can only focus on one thing at a time.

In Linux we can set guidelines for the CPU to follow when it is looking at all the tasks it has to do. These guidelines are called niceness or nice value.

The Linux niceness scale goes from -20 to 19. The lower the number the more priority that task gets. If the niceness value is high number like 19 the task will be set to the lowest priority and the CPU will process it whenever it gets a chance. The default nice value is zero.

top, ps: Checking the Priority of Running Processes

The nice value es marked as NI.

A través del comand top:

top

A través del comando ps:

ps -eo pid,ni,comm
ps -eo pid,uid,ppid,pri,ni,comm,cmd
ps -o pid,uid,ppid,pri,ni,comm,cmd -p 3029
Setting priority
nice: On new processes

To change the priority when issuing a new command you do:

nice -n 10 apt-get upgrade

This will increment the default nice value by a positive 10 for the command, ‘apt-get upgrade’ This is often useful for times when you want to upgrade apps but don’t want the extra process burden at the given time. Remember a positive number is gives less priority for a process.

renice: On Existing Processes

To change the priority of an existing process just do renice [nice value] -p [process id]:

renice 10 -p 21827

Alternatively:

renice +5 `pgrep script.sh`
Setting Permanent Priority on all Processes for a Specific User

You can set the default nice value of a particular user or group in the /etc/security/limits.conf file.

/etc/security/limits.conf

It uses this syntax:

[username] [hard|soft] priority [nice value]
backupuser hard priority 1

Kill processes

kill -9 789

Alternatively:

pkill script.sh

System Reporting

To display details about IO activities, type:
iostat
To show network card activities, type:
netstat -i
To display socket activities, type:
netstat -a
To get details about virtual memory activities (memory, swap, run queue, cpu usage, etc) every 5 second, type:
vmstat 5
To get a full report of a server activity, type:
sar -A

Linux Memory Usage

free -m

Locate and interpret system log files and journals

What is a Log file

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/3/html/System_Administration_Guide/ch-logfiles.html

Log files are files that contain messages about the system, including the kernel, services, and applications running on it. There are different log files for different information. For example, there is a default system log file, a log file just for security messages, and a log file for cron tasks.

Log files can be very useful when trying to troubleshoot a problem with the system such as trying to load a kernel driver or when looking for unauthorized log in attempts to the system.

Locating Log Files

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/3/html/System_Administration_Guide/ch-logfiles.html

Most log files are located at:

/var/log/

Some applications such as httpd and samba have a directory within /var/log/ for their log files.

Notice the multiple files in the log file directory with numbers after them. These are created when the log files are rotated. Log files are rotated so their file sizes do not become too large. The logrotate package contains a cron task that automatically rotates log files according to the /etc/logrotate.conf configuration file and the configuration files in the /etc/logrotate.d/ directory. By default, it is configured to rotate every week and keep four weeks worth of previous log files.

Common Log Files

Log File Description
/var/log/audit/audit.log SELinux writes here; audit messages
/var/log/boot.log System startup logs
/var/log/cron Cron jobs log file
/var/log/cups Print service CUPS
/var/log/dmesg Kernel log messages
/var/log/httpd/ Apache web server
/var/log/maillog Mail related messages
/var/log/messages Most system messages written here. Generic log file.
/var/log/secure Authentication related messages
/var/log/sssd Authentication messages related to sssd service

Syslogd

https://fr.wikipedia.org/wiki/Systemd

Systemd is an init used in Linux distributions to bootstrap the user space and manage all processes subsequently.

Some log files are controlled by syslogd. A list of log messages maintained by syslogd can be found in the /etc/syslog.conf configuration file.

Systemd primary task is to manage the boot process and provides informations about it.

To get the boot process duration, type:

systemd-analyze

To get the time spent by each task during the boot process, type:

systemd-analyze blame


Init

In Unix-based computer operating systems, init (short for initialization) is the first process started during booting of the computer system. Init is a daemon process that continues running until the system is shut down. It is the direct or indirect ancestor of all other processes and automatically adopts all orphaned processes. Init is started by the kernel using a hard-coded filename; a kernel panic will occur if the kernel is unable to start it. Init is typically assigned process identifier 1.

Daemon

In multitasking computer operating systems, a daemon is a computer program that runs as a background process, rather than being under the direct control of an interactive user. Traditionally, the process names of a daemon end with the letter d, for clarification that the process is, in fact, a daemon, and for differentiation between a daemon and a normal computer program. For example, syslogd is the daemon that implements the system logging facility, and sshd is a daemon that serves incoming SSH connections.

In a Unix environment, the parent process of a daemon is often, but not always, the init process.

Bootstrap

In general parlance, bootstrapping usually refers to a self-starting process that is supposed to proceed without external input. In computer technology the term (usually shortened to booting) usually refers to the process of loading the basic software into the memory of a computer after power-on

Access a virtual machine's console

Start and stop virtual machines

Start, stop, and check the status of network services

Securely transfer files between systems

Configure local storage

Create and configure file systems

Deploy, configure, and maintain systems

Manage users and groups

Crear un usuario

adduser nom_usuario

También existe el comando useradd pero la sintaxis cambia.

Crear un groupo

groupadd nom_grupo

There are two kinds of groups: http://www.hostingadvice.com/how-to/linux-add-user-to-group/

Primary Group: This is the group applied to you when you log in; in most user cases it has the same name as your login name. The primary group is used by default when creating new files (or directories), modifying files, or executing commands.

Secondary Groups (AKA Supplementary Groups): These are groups you are a member of beyond your primary group. As an example, this means that if a directory or file belongs to the www-data group (as used by the web server process in this case), then all www-data group members can read or modify these files directly (assuming the permissions also allow for this).

Change the Primary Group of a User: usermod -g

sudo usermod -g www-data foobar
The lowercase -g option refers to a primary group.

Add or Change Users in Secondary Groups: adduser and usermod -G

adduser usuario grupo

Creo que también se puede usar el comando addgroup para este fin:

addgroup usuario grupo

There is another way to achieve the same result as above using the usermod command:

sudo usermod -G www-data foobar

The uppercase -G option refers to a secondary or supplementary group. Now foobar will have access to the www-data group files, but new files created by that user will not have the www-data group label by default.

It’s also possible to add a user to several secondary groups at once using the usermod command:

usermod -a -G group1, group2, group3 foobar 

Delete a Group: groupdel

We can then remove group1 from the Linux system utilizing the groupdel command:

sudo groupdel group1

Para listar y ver toda la información de los usuarios

passwd

cat /etc/passwd

Este archivo incluye:

System users: Usuarios creados por el sistema para distintos propósitos.

Normal users: Creados por usuarios para ingresar al sistema. Ej. adelo , root

Each user account have a unique number, the UID. It's common to give programs (sytem users) an account with a low number (lower than 1000), and real people (normal users) an account with a higher number (1000 and up) so that programs that check user accounts can easily distinguish between them should they need to. https://ubuntuforums.org/showthread.php?t=1146686

Also, system users are non privileged, have no password set (*) or disabled (!), and often use /bin/false or /bin/sh instead of /bin/bash (este último es usado para normal users). https://ubuntuforums.org/showthread.php?t=1146686


Si queremos listar sólo los normal users: http://askubuntu.com/questions/437224/list-all-non-system-users

I do not clear solution. But I can help you to find real users.

First solution:

In /etc/passwd, last column showing default shell/ command. In Ubuntu it is usually /bin/bash, but it is not a rule. So you can try:

sudo grep '/bin/bash' /etc/passwd | cut -d: -f1

Also usually real users home folder located in /home. You can try:

sudo grep '/home/' /etc/passwd | cut -d: -f1

Or both of them:

sudo grep -E '/home.*/bin/bash' /etc/passwd | cut -d: -f1

Get User ID and Groups Information: id command

http://www.hostingadvice.com/how-to/linux-add-user-to-group/

To show all the user information and group memberships, we can use the id command:

id adelo

El siguiente archivo contiene los mots de passe de los usuarios pero en un formato crypté

/etc/shadow

Listar grupos

A list of all currently available groups can be found in the /etc/group file.

Listar todos los grupos a los cuales pertenece un usuario

id -Gn someusername 

returns the list of groups for the specified user

groups someusername

Listar todos los miembros de un grupo

https://www.cyberciti.biz/faq/linux-list-all-members-of-a-group/

grep 'grpup-name-here' /etc/group
awk -F':' '/ftponly/{print $4}' /etc/group

También podemos usar el comando members:

members grpup-name-here

En Red Hat creo "lid" sería el comando análogo.

Para desactivar una cuenta il faut editer le ficher

/etc/passwd  # Là il faut remplacer le "x" pour une "*"
toto:x:1002:1002:Toto,39,39383,8386734,9038734:/home/toto:/bin/bash

Archiver le compte

tar cvzf toto.tar.gz /home/toto

Para construir un mot de passe solide

Una buena forma es elegir una frase y tomar la primera letra de cada palabra. Luego podemos colocar algunas letrans en mayúsculas o cambiarlas por números:

Ej: Te Estoy Buscando América Y Temo No Encontrarte --> tebaytne --> t3b4Ytn3

Pour se faire passer pour un utilisateur

su nom_usuario
su - nom_usuario

Para cambiar a root en ubuntu se usa:

sudo su

Para poder hacer esto, es necesario que dicho comando se ejecute desde un usuario administrador.

Manage security