About the bash
- [user@host ~]$ normal user.
- [user@host ~]# root user.
Ctrl Shortcouts
- Ctrl+Alt : switch between terminals or F1..F6.
- Ctrl+A : beginning in the command line.
- Ctrl+E : end in the command line.
- Ctrl+U : delete from the cursor to the beginning of the command line.
- Ctrl+K : delte from the cursor to the end of the command line.
- Ctrl+LeftArrow: Go to the beginning of the last word in the command line.
- Ctrl+RightArrow: Go to the end of the last word in the command line .
- Ctrl+R : Search a pattern in historial of the command line.
Esentials
python3 -m http.server 80 ping 192.168.4.29 -c 1 > ip.txt ; cat ip.txt | grep "64 bytes" | cut -d " " -f 4 | tr -d ":"
Patterns
- "*" Any string of zero or more characters.
- "?" Any character
- [abc...] Anything insided in between the sequence like [1..3] = 1 2 3.
- [!abc...] Anything that is not inside the sequence given.
- [[:alpha:]] Any alphabetic character.
- [[:lower:]] Any character in lowercase.
- [[:upper:]] Any character in uppercase.
- [[alnum:]] Any digit.
- [[:punct:]] Any character not alphanumeric or space.
- [[:digit]] Every single digit from 0 to 9.
- [[:space:]] Any space like tabs, newlines etc.
Man Functionality
- /string to search a string in the man page.
- N repeat previos search foward.
- Shift + N repeat previos search backward.
- G Start of the page, Shift+G end of the page, Q exit the page.
- "-K" Displays keywords list.
Jerarquy of files system
- /usr : Installed software /bin user comands, /sbin administration comands of system, /local software personalized at local level.
- /etc : configuration files.
- /var : Variables that must be conserved, and that they change dinamically, like "data bases, cache, website content".
- /run : Data of time execution, that have been initialized since last start, it includes.
- /home : Home directory for regular users, to store their data.
- /root : Home directory for the superuser/root user.
- /tmp : Temporaly files, if its files are rnot accesed, changed or modified in 10 days, they will be deleted, also in var/tmp, we have the same system but for 30 days.
- /boot : Files for boot process.
- /dev : Files that allow the system to access the hardware.
Esencial commands
- ssh remoteuser@remotehost : connect via ssh.
- ssh -i mylab.pem remoteuser@remotehost : connect via ssh with authentification viapublic key.
- passwd : change user's password.
- whoami : watch what's the current user logged in.
- command ; command : execute two commands.
- date : show actual date and hour.
- date +%R : shows actual hour 12:11.
- date +%x : shows actual date dd/mm/aaaa format.
- file : shows the type of a file.
- cat : shows the content of a file (cat file1 file2).
- head : shows the beginning of a file (first 10 lines) (-n number of lines).
- tail : shows the end of a file (last 10 lines) (-n number of lines).
- wc : counts lines, words, characters, options "-l , -w , -c".
- history : historial of commands !number execute the command in the number gaven,!string searchs a command similar in the historial.
Files
- touch : Create file.
- ls : List content (-l long list format) (-a all files, even hidden ones).
- mkdir : Create directory Fails if the directory already exist or trying to create a subdirectory in a directory that doesnt exist (-p to avoid it).
- cp : Copy a file or multiple files into the directory specified as last argument (-r copy a directory and its content).
- mv : Moving files, or rename a file.
- rm : Remove files (-r remove directories with content, -f skips confirmation).
- rmdir : Remove empty direectory.
- ln : Create hard link, to create another name/link that links to the same data stored, "-s" soft link points to another name, that points to data on the storage device.
Expressions
- VARIABLENAME = value.
- echo ${VARIABLENAME}.
- echo Today is $(date +%A).
STDIN - STDOUT - STDERR
- Standard input (stdin)(channel 0) input from keyboard.
- Standard output (stdout)(channel 1) normal output.
- Standard error (stderr)(channel 2) error messages.
- "> file" : Redirect stdout to overwrite a file.
- ">> file" : Redirect stdout to append to a file.
- "2>file" : (/tmp/output > /tmp/errors) Redirect stderr to overwrite a file.
- "2>/dev/null" : ( /tmp/output 2> /dev/null) Discard stderr messages.
- "&>file" : Redirect stdout and stderr to overwrite the file.
- "&>>file" : Redirect stdout and stderr to append to the same file .
Users and Groups
- user01 ALL=(ALL) ALL "sudo access for users" (etc/sudoers).
- %group01 ALL=(ALL) ALL "sudo access (etc/sudoers)".
- ansible ALL=(ALL) NOPASSWD:ALL "Allow users to execute sudo without password" (etc/sudoers).
- /etc/login.defs : range of system GIDs SYS_GID_MIN SYS_GID_MAX.
- ps -au Show processes (-a view user asociated).
- gpasswd -d user01 group01
- sudo usermod -L user01.
- Commands executed with sudo are stoaraged in /var/log/secure.
- sudo configuration is located in /etc/sudoers.
- useradd name : Creates a new user with the given name and creates its directory.
- userdel "Deletes info at /etc/passwd", "-r", deletes also de user's directory.
- groupadd -g "GID".
- etc/group/.
- groupadd -n New name.
- groupadd -g New GID [GID GROUP].
- groupdel Delete group.
- usermod -g Change user's primary group.
- usermod -aG Add user to a supplementary group.
usermod options
lock user in specify date : usermod -L -e 2022-05-11 user01.
- c Add users real name.
- g Add primary group.
- G Add supplementary groups..
- a Plus G, will add the new supplementary groups and appened them, not replace.
- d Specify home directory.
- m With d option, move the actual home directory to a new one.
- s Specify shell.
- L Lock users account.
- U Unlock users account.
groupmod options
- n New name for the group (groupmod -n group1 group01)
- g New GID (groupmod -g 20000 group01)
passwords
/etc/login.defs PASS_MAX_DAYS/PASS_MIN_LEN/PASS_WARN_AGE
chage -m 0 -M 90 -W 7 -I 14 user01.
- m : min days.
- M : max days.
- W : warn days.
- I : inactive days.
- d : force to change password.
CHMOD
Symbol / Binary / Octal
--- 000 0
--x 001 1
-w- 010 2
-wx 011 3
r-- 100 4
r-x 101 5
rw- 110 6
rwx 111 7
How to use CHMOD
chmod WhoWhatWhich
- Who (u,g,o,a): User,group,other,all.
- What (mas,-,=) Add deletee equal.
- Which (br,w,x) Read write and execute.
Especial permissions
- u s(suid): The file executes as the owner, not the user who executed.
- g s(sgid) The file executes as the group owner, also the files created recently the owner's group will coincide with the owner of the directory.
- o t(sticky) The userswith access to write, can only delete files whose they are owners, but cannot delete and force the saving of any file whose owner's are others.
Monitoring and Processes
- R TASK_RUNNING, the process is running or waiting to run.
Sleeping
- S TASK_INTERRUPTIBLE, the process is waiting for a condition (hardware request, system resourcess access, signal), then it goes to Running
- D TASK_UNINTERRUPTIBLE, the process does not respond to signals, but still sleeping as TASK_INTERRUPTIBLE.
- K TASK_KILLABLE, same as TASK_UNINTERRUPTIBLE , but it can allow to recieve a waiting task, that should be killed (exit completely).
- I TASK_REPORT_IDLE, The kernel does not count these processes when calculating load average. Used for kernel threads, subset of state D.
Stopped
- T TASK_STOPPED, The task has been stopped by another process or by the user, and it can be resumed by a signal to return, to continue running.
- T TASK_TRACED, The process is being debuggued so its also tempraly stopped.
Zombie
- Z EXIT_ZOMBIE, Un proceso secundario señala su proceso principal cuando finaliza. Se liberan todos los recursos, menos la identidad del proceso (PID).
- X EXIT_DEAD, Cuando el proceso principal limpia (obtiene) la estructura del proceso secundario restante, el proceso se libera completamente. Este estado nunca se observará en utilidades de listas de procesos.
PID is the unique ID of a process, PPID is the principal process id, and PGID is the process leader of the group of processes, usually generated in a tube, and SID is the intentificator for the leader of the sesion (for a job).
- top : Column s , status of the process
- ps aux : Shows all the process, even the ones without a terminal of control, column stat, status of the process.
- ps lax : More technical details, and displays the info more quickly since it does not search the username (ps -ef UNIX sintax).
-o , --sort to order
- command & : Send a process to segundo plano.
- fg %id of job : Send 2d process to first.
- bf &id of job : Initialices a suspuended in 2nd plano.
- ps j : Information related to jobs.
SIGNS
1 HUP : 2 INT 3 QUIT 9 KILL 15 FINISH N CONT APARTADO STOP 508 TSTP
Services and daemons
- systemctl : Loaded and active services.
- systemctl -t help : Visualize all types of unities avaliable.
- systemctl list-units --type=service : Shows all the unidades of services loaded and organize the exit by pages with less. UNIT : Service unit name. LOAD : Correctly loaded. ACTIVE : Started sucessfully or not. SUB : Detailed information about the unit, type, state and how is executed. DESCRIPTION : Description of the unit.
- systemctl list-units --type=service --all : Shows all services in all states.
--state = option | LOAD,ACTIVE,SUB
- systemctl status name.type (service,socket,path)
- systemctl is-active/enabled/failed name.type.
- systemctl reload-or-restar service
- systemctl stop,start,restart,reload
- systemctl list-dependencies "unit" : Units that depend from specified unit.
- systemctl mask "service" : Prevent to start a service that conflicts with another.
- systemctl enable service : Start service at boot.
- systemctl disable service : Disable service start up automatically.
SSH
ssh user@remotehost host
- w : Displays list of users logged into the computer. System storage of public key : /etc/ssh/ssh_known_hosts. User's storage of public key : /.ssh/known_hosts.
- /etc/ssh/ssh_config : StrictHostKeyChecking = yes, to abort connection if the public key do not match.
- ls /etc/ssh*key.pub : Public key stored in the SSH server.
- ssh-keygen : Create a matching public and private key and will be stored at (./ssh/id_rsa and .ssh/id_rsa.pub).
- ssh-keygen -f .ssh/key-with-pass : Create with password.
- ssh-copy-id : Copy punblic key.
Logs
systemd-journald : Collects messages from kernel, output, boot process, standard output and error, daemons, syslog events. And struturects them into a standard formad. rsyslog : However, the rsyslog service reads syslog messages received by systemd-journald from the journal as they arrive. It then processes the syslog events, recording them to its log files or forwarding them to other services according to its own configuration.
The rsyslog service sorts and writes syslog messages to the log files that do persist across reboots in /var/log. The rsyslog service sorts the log messages to specific log files based on the type of program that sent each message, or facility, and the priority of each syslog message. The operating system kernel receord a log of every event, those are kept in /var/log.
- /messages : Authentication, email processing, job execution. debugging related.
- /secure : Security and authentication events.
- /maillog : Mail server.
- /cron : Job execution.
- /boot.log : System startup.
Syslog Priorities :
- 0 emerg System is unusable
- 1 alert Action must be taken
- 2 crit Critical condition
- 3 err Non-critial error
- 4 warning Warning
- 5 notice Normal but significant event
- 6 info Informational event
- 7 debug Debugging Their configuration is located at /etc/rsyslog.conf and /etc/rsyslog.d, that has the file with extension .conf. The next line shows the last 10 logs, and keep tracking new logs and print them.
tail -f /var/log/secure
Send a message to rsyslog, that will be recorded at /boot.log
logger -p local7.notice "Log entry created"