Category Archives: GNU / Linux

El acrónimo recursivo GNU, GNU’s Not Unix (GNU no es Unix), proviene de las herramientas básicas de sistema operativo creadas por el proyecto GNU, iniciado por Richard Stallman en 1983 y mantenido por la FSF. El nombre Linux viene del núcleo Linux, inicialmente escrito por Linus Torvalds en 1991

The GNU / Linux system

The file system GNU / Linux

GNU / Linux is based on UNIX file system, which has a tree structure. The point of origin is called root and is represented with the symbol /

Un sistema GNU / Linux puede ser instalado en una "única partición" o en múltiples particiones. Existiendo la partición especial para el intercambio con la memoria, la partición swap. Esta partición permite al sistema usar el disco cuando agota la memoria

Underneath the root (/), hang all the system directories. Really root hangs the system root partition that contains the basic files for the boot and operation of the system. The other partitions, we can establish hang of directories

It is possible to have in different partitions, user files, user applications, files, of variable length, temporary files. The multiple partitions allow us to better manage the system

We can create backup copies of all of the parts that interests us or limit the use of certain parts to a particular user. In this way we prevent the disk from filling up completely, as the only one that has write permission on the partition root is the administrator user

The type of partition most used in GNU / Linux systems is the ext2 or ext3. The units are not fixed, such as cd-rom, blu-disk, zip, pendrive, etc, hang on different directories with a descriptive name that refers to them, within the directory /mnt

The description of the properties of each partition is done in the file /etc/fstab

Name of files

A valid filename for the Linux kernel can contain any character except the characters ‘/’ (bar) or ‘\0’ (void)

Sin embargo no es prudente usar caracteres especiales usados por la shell (la línea de comandos) tales como ($, ", ‘, &, #, (, ), *, [, ], {, }, …). Tampoco debe empezar por el carácter ‘-‘ que puede ser confundido con una opción

When a user is created, the shell defines the default which will use the input directory named like the user name. The value of this directory entry can be found in the system variable $HOME

In each directory there are at least two accessible entrances, which are ‘.’ (reference to the current directory) and ‘..’ (a reference to the parent directory). In the $PATH variable stores the reference to the subdirectory current. If you want to run commands contained in the current directory, use the command

The ‘/’ character is used to separate the different levels of directories within the file name

When the file name begins ‘/’ then we are stating the full path name or the name of the absolute path. If on the other hand starts with ‘./’ or ‘../’, then we are indicating a name of the relative path, because we are using the subdirectory current where we are. The last part of the name after the last ‘/’ character is the name base name

The files that start with ‘.’ are not considered and therefore are considered to be hidden to the system, except that certain commands are directed. For example, to list a directory using the ls command, but starting with ‘.’ does not list them in the list despite being the files the same as the rest

The system identifies internally the files with a number, which is called the number of i-node. In the i-node are saved for different properties of the file such as:

  • file type
  • id of the owner
  • id of the group owner
  • number of links
  • its size
  • date of last access
  • date of the last modification
  • date of change of the number of i-node
  • an array with the data blocks that holds the file

Types of files

  • Regular: mere stores of information. Some contain executable code
  • Directories: table that contains the numbers of i-nodes and the names of all the files contained in the within the directory
  • Special files: can be a device of type character or block device. The handling of these files depends on the particular device
  • Symbolic links: files that contain a pointer to another file that could be stored in a different filesystem
  • Hard links: file which can be seen with different names within the file system (similar to aliases). That is to say, we can list them as if they were files identical but that share the same i-node. The information resides in one place and the changes made in a file also occur in the other equivalent. Links of this type do not work with file systems different, have to be of the same type. Not all file systems support hard links, as that is a concept very much tied to UNIX-like operating systems

The directory tree

The directories and files of the GNU / Linux systems are standardized in a document called the FSSTND. Among the various distributions of Linux we can find some differences

We will describe the main directories defined by the standard and what it contains:

  • /bin: basic commands of the operating system
  • /boot: boot files, including the file of the kernel that has the form vmlinuz-x.x. x x.x
  • /dev: device files
  • /etc: configuration files of the system
  • /etc/X11: configuration files for the X Windows (libraries for the management of the graphical environment, like Windows)
  • /home: directories of the users. By default the same name as the user name
  • /initrd: directory for the boot process
  • /lib: libraries necessary for the implementation of the resident programs in the directories /bin and /sbin
  • /mnt: to mount the removable devices (Cd-Rom, Blu-Disk, Zip, pen drive, ...)
  • /proc: houses special files for that, or collect information from the kernel, or the provide. The files generate the information when you view them
  • /root: home directory of the super user administrator (has all permissions on the system)
  • /sbin: contains executable files that can only be run by root root
  • /tmp: are saved to temporary files
  • /usr: files that can be shared throughout the system. It is the place in which you are installing the user applications. Contains directories such as /usr/bin, /usr/sbin, /usr/lib, /usr/man, /usr/X11R6, ...
  • /usr/local: it is for the exclusive use of root, to the installation of particular software of the machine, the peripheral drivers
  • /var: ficheros de longitud variable. Esto incluye los directorios y ficheros de "spool", datos de administración y registro, así como ficheros transitorios y temporales que no se guarden en el directorio /tmp

To move in the path of directories we use the cd command. For example, if we want to access the directory man, write in the command line cd /usr/man

File permissions

Files have many attributes in addition to its name. To see the more significant when we run the ls -l

Numeric notation for permissions

The permissions of the files are stored in binary format and can be referenced numerically. To do so is given the value 4 to the read permission, the value 2 to the write permission and 1 for the execute permission. Then summed the values for user owner, group, and user either, getting a three-digit number. Let's look at an example:

Other permissions

There are also permissions SUIG and SGID, that allow to identify when a program is executed by the owner of the file or the group of the file instead of the user that has launched. In general it is used when the root wants to give permission for execution of one of its programs to another user

Another permission is the sticky bit, or townhouse (bit sticky), it is for the process to stay in RAM memory while it runs. It uses little

The numerical values for the SUIG are 4, for the SGID is 2, and for the bit sticky is 1, added in front of the other 3 values of permissions. As well, we could give to our program, the permit 4751

Command for permissions

The command to change permissions is chmod, and supports numeric format or character format. In the character formatting is used u (user), g (group), o (other) and to (all) to indicate to whom they affect. The symbols + (for adding permissions), – (for removing permissions), = (set permission). Finally, r (read), w (write), x (execution) s t (bit sticky)

Permissions for the directories

To understand how the permissions applied to a directory it is necessary to imagine that a directory is a regular file that only contains a table that lists the files present in that directory. In each directory there are always a couple of entries that are ‘.’ (for the current directory) and ‘..’ for the parent directory. The permission of execution is understood as access

If a directory does not have read permission, it will prove impossible for any command, including ls, read your content

If a directory does not have execute permission, will not be able to cd to that directory, or any of the subdirectories that hang of it. This makes it impossible all the operations that use that directory as part of the road

If you do not have write permission may not be given high, low, or modifications in the table, that is to say, you can not delete files nor create new ones, or rename them

Finally, in a directory, the bit sticky is understood as that it is protected before the creation of the same file by different users, even if they have sufficient permissions. It is usually applied to the /tmp directory

Other related commands

  • umask: sets the default permissions for creation of files
  • chown: allows you to change the user owner of a file or several files
  • chgrp: allows you to change the group owner of a file or several files

How to run UNIX commands

UNIX commands follow the following structure:

box_unix

The standard input is usually a file or the keyboard. The standard output is usually the screen, and the output of the standard error is also the screen

The format of the command follows the structure:

  • order: the name of the command
  • -: the minus sign indicates that it is an option
  • options: one or more characters of options
  • arguments: are literal, taken as input parameters for the command

Redirection and connections

Both the outputs as a standard input you can redirect to a file or device (remember that from the point of view of the system all are files)

We may also pass the standard output of one command to the standard input of another, using the connection

For these operations we use the following metacharacters for the shell:

> command >file directs the standard output to the file
>> command >>file appends standard output to file
< command <file extracted file to the standard input
<<str follows the standard input until the next str in the line
p1¦p2 connects the standard output of p1 to the standard input of p2

The connections give a great power to the system, as, although it is a command by itself, then a trivial task, when combined with others become the tools of general and useful. This allows us to easily create new commands and that the growth of the system is limited only by our ability of creation

Other metacharacters of the shell

* matches any string of zero or more characters in the files
? matches any single character in the file
[ccc] match any single character from ccc in files, are valid ranges 0-9 or a-z
; p1;p2 when the command p1 runs the command p2
& as ; but do not expect it to end p1
`...` run command in ...; output replaces `...`
(...) run command ... in a subshell
$1, $2, ... we replace the arguments in a file of the shell
$var value of the variable var in the shell
${var} value of the shell variable var avoids confusion when concatenating with text
\ \c it literally takes the character c
‘...’ it takes ... literally
"…" se toma … literalmente después de interpretar $, ‘…’ y \
var=value it assigns the value to the variable var
p1&&p2 p1&&p2 run p1if it succeeds, run p2
p1¦¦p2 p1¦¦p2 run p1 if this is not accomplished, run p2

UNIX commands

We're not going to expose here is a list of UNIX commands, explaining their functionality.

In the first place because there are multiple pages dedicated to it, and in the second place by the system itself provides us with multiple aids on them

With the man command you can get help from any program or setup file, if we want to know how it works, it can call itself in the following way: man man

When we do not know the name of a command we can use the command apropos, and to indicate something related to it

Another help command is the info command. This command usually complete the help of man

Many commands give help among its options by running the command

Another source of help are the HOWTOs. Are tutorials on how to perform certain operations in the system. Are published by The linux documentation project (The Linux Documentation Project) and available in many languages

Some packages include own documentation in a subdirectory of /usr/share/doc that has the same name as the package

Note: do not forget that with the tab key, the shell completes the file names, which helps to locate the commands and files even if we don't remember his full name. In addition to avoid many errors when typing

The Linux shell

The Linux shell

A shell or command interpreter is a program interface that allows a user to write instructions to the operating system. In the Linux environment there are three major families of shells: sh, csh and ksh. The bash shell (Bourne Again Shell) belongs to the family sh

One of the main features of a command interpreter is that it can be programmed using text files that contain commands that are to be interpreted in the execution of the same

These text files are called files commands or scripts (also scripts, shell scripts or scripts shell). Therefore, a file of commands is a text file executable that contains commands that can be interpreted by the shell

Features

The first line of the file indicates the type of shell that must be interpreted, in our case bash:

Each line of the file contains a command that will be executed by the interpreter

If you want to run multiple commands on the same line must be separated by ‘;’

To continue a command in the next line it must end with '/'

The ‘#’ character at the beginning of a line indicates that it is a comment and therefore the interpreter will not execute it

To display text or variables on the screen, use the echo command

Variables

Each shell has associated with some variables, that the user can use. There are two types of variables:

  • Local Variables: Are not inherited by the child processes of the shell when doing a fork
  • Environment Variables: Are inherited by the child process when a fork

All variables are preceded by ‘$’

Use of variables

To define a new variable or a value to a variable use the =operator

As we have mentioned before, to display on the screen the value of the variable use the echo command

To convert a local variable into an environment variable use the export command

To delete a variable and its value from memory, use the command unset

To display all variables (local and environment), we will use the set command

To show only environment variables, use the command env

We can use the following environment variables pre-defined within the shell

$HOME Home directory of the user
$PWD Working directory of the user
$PATH Absolute path of directories to search for executables. The working directory of the user is not included by default
$PS1 Prompt main shell
$PS2 Prompt secondary
$IFS Internal separator Field. Used by the command internal read

Arguments

Like any program, a script can receive values through arguments or parameters, in the command line. The arguments received are stored in a series of variables that the script can use

$1 The first argument
$2 The second argument
$3 Third argument
$4 Fourth argument
$5 Fifth argument
$6 Sixth argument
$7 The seventh argument
$8 Eighth argument
$9 Ninth argument
$C Name of the script
$* String containing all the arguments
$# The number of arguments received by the script
shift To move all arguments to the left position. That is to say, the value $1 disappears and is replaced by the $2, and so on

Quotes

Simple ‘ ‘

String of characters that the shell takes literally

Reverse ` `

Must enclose a complete command (with its name and its arguments) produces a run in three phases:

  1. Evaluation of variables
  2. Substitution of the command for a string that contains the standard output of the command
  3. Execution of the result

Dobles " "

Allow the evaluation of variables and command substitution

Commands flow control

Sentence if

expression can be a comparison expression or a command. Its value will be the one that returns the expression or the execution of a command

To enter by the branch that follows then, expression must have returned a 0 (true) and to enter an elif branch or an else branch, expression must have returned a value other than 0 (false)

Expressions

If we want to compare two values we must use the test

test evaluates the expression. If this is true it returns code 0 and if this is false a code other than 0

The most common expressions are:

-r file true if the file exists and has read permission
-w file true if the file exists and you have write permission
-x file true if the file exists and you have execute permission
-f file true if the file exists and is a file
-d file true if the file exists and is a directory
-s file true if the file exists and its size is greater than 0
-z string true if the file exists and its size is 0
-n string true if the file exists and its size is different from 0
string1 == string2 true if string1 is equal to string2
string1 != string2 true if string1 is different from string2
string true if string is not the null string
n1 -eq n2 true if n1 is equal to n2
n1 -ne n2 true if n1 is different than n2
n1 -gt n2 true if n1 is greater than n2
n1 -ge n2 true if n1 is greater or equal to n2
n1 -lt n2 true if n1 is less than n2
n1 -le n2 true if n1 is less than or equal to n2

These expressions elementals can be combined using parenthesis and the following operators:

! negates the expression
-to is equivalent to the AND operator
-or is equivalent to the OR operator

Case statement

Compares the string with the patterns, executing the list of commands corresponding to the first pattern with which it agrees, after which the execution of the case statement ends. A pattern can include any of the metacharacters of the shell

* is the default pattern and runs when none of the others

For statement

The list of commands is executed as many times as items are in the list. Before each iteration the next value of the list is assigned to variable, starting the first iteration by the first value

It is very useful if we want to go through all the arguments

Sentence while

command_list runs as many times as true expression

Judgment until

command_list is executed as many times as false expression

OR operator

command1 is executed; if it returns an error code other than 0 then the command2 is executed, and the code it returns is the code returned by the complete command; if command1 succeeds (code 0) then command2 is not executed and all expression succeeds

The previous example checks to see if the fich1 file exists. If it exists, nothing is done, otherwise a message is displayed by the standard error channel

AND operator

command1 is executed; if it returns an error code equal to 0 then the command2

In the example checks to see if there is a directory called dir1. If it exists, the content is displayed, otherwise nothing is done

Note: there is an operator object command

Read command

value_list are variables separated by a space

The execution of the read command reads from its standard input a line of text divided into words (i.e. strings separated by blanks or tabs)

Assigns the first word to the first variable, the second to the second variable, and so on until you complete the value_list

If not entered enough words, to the variables remaining to be assigned the null string

If in the line there are more words than variables, then it is assigned to the last variable a string consisting of all the words leftovers

Example of trace line to line of a file

Exit command

All command returns a code to notify the end if its execution has been correct or if it has appeared an error. If the execution has been correct, it returns error code 0, and if there has been any problem it is returned as a code any positive number

The files command returned at the end of a code error; the exact error code returned by the last command in the file that is running. To modify this situation by default we have to use the exit command

Where the optional argument n will be an integer greater than or equal to 0. If you do not specify an argument is equivalent to exit 0

When running the exit command, it immediately terminates the execution of the file command and is returned as an error code the integer n

Linux User

Linux User

Each Linux user is identified to the system with a user name because that is a multi-user system

To this name the system associates a unique number (UID), a password, your full name, a boot directory (the home user) and a login shell (there are different shell programs, and choose between one or the other according to the characteristics of the user or the type of shell you prefer)

All these data saved the system in the /etc/passwd and /etc/shadow. The /etc/shadow file contains the encrypted password and data over the same (such as the validity time, in days to warn before expiry, every time you have to force your change, etc). The creation of this file came as a matter of safety, as the file passwd must be accessible to all users

Structure

The structure of the file passwd is the following:

user Not supported numbers at the beginning of a user name
x An “x” indicates that the password is stored in /etc/shadow, in the case of a “!” is that the user is locked. “!!” indicates that it has no password
uid Each user has an assigned id number (uid) between 0 (root) and 65535. Reserved for special users, such as root (which is always zero) and for users of services of the system. Systems-Red hat and derivatives between 1 and 499. In Debian systems and derivatives between 1 and 999
gid Each user is assigned a number id of the primary group (gid), that is to say, always belongs to at least one group, but can belong to more than one group
full name This option is designed for the user to enter their full name, although it can also be used to write a description of what makes that user or which is its usefulness, in the case of a service system
home directory Is the home folder that the user will use by default when you start your session
shell command The users associated with a system service, or users with limited permissions should not have a shell command, that is to say, ability to login in console mode, normally, this field is populated as /usr/bin/nologin or /bin/false

Some of the most common can be found in the following table:

User UID GID Home directory Terminal
root 0 0 /root /bin/bash
bin 1 1 /bin /sbin/nologin
daemon 2 2 /sbin /sbin/nologin
adm 3 4 /var/adm /sbin/nologin
lp 4 7 /var/spool/lpd /sbin/nologin
sync 5 0 /sbin /bin/sync
shutdown 6 0 /sbin /sbin/shutdown
halt 7 0 /sbin /sbin/halt
mail 8 12 /var/spool/mail /sbin/nologin
news 9 13 /var/spool/news
uucp 10 14 /var/spool/uucp /sbin/nologin
operator 11 0 /root /sbin/nologin
games 12 100 /usr/games /sbin/nologin
gopher 13 30 /usr/lib/gopher-data /sbin/nologin
ftp 14 50 /var/ftp /sbin/nologin
nobody 99 99 / /sbin/nologin
vcsa 69 69 /dev /sbin/nologin
rpm 37 37 /var/lib/rpm /bin/bash
wnn 49 49 /var/lib/wnn /bin/bash
ntp 38 38 /etc/ntp /sbin/nologin
nscd 28 28 / /bin/false
apache 48 48 /var/www /bin/false
mysql 27 27 /var/mysql /bin/bash
mailnull 47 47 /var/spool/mqueue /sbin/nologin
smmsp 51 51 /var/spool/mqueue /sbin/nologin
rpc 32 32 / /sbin/nologin
xfs 43 43 /etc/X11/fs /sbin/nologin
gdm 42 42 /var/gdm /sbin/nologin
rpcuser 29 29 /var/libs/nfs /sbin/nologin
nsfnobody 65534 65534 /var/libs/nfs /sbin/nologin
ident 98 98 / /sbin/nologin
radvd 75 75 / /sbin/nologin
sshd 74 74 /var/empty/sshd /sbin/login
postgres 26 26 /var/lib/pgsql /bin/bash
squid 23 23 /var/spool/quid /dev/null
named 25 25 /var/named /bin/false
pcap 77 77 /var/arpwatch /sbin/bash
amanda 33 6 /var/lib/amanda /bin/bash
mailman 41 41 /var/mailman /bin/false
netdump 34 34 /var/crash /bin/bash
ldap 55 55 /var/lib/ldap /bin/false
postfix 89 89 /var/spool/postfix /bin/true
privoxy 100 101 /etc/privoxy
Pvm 24 24 /usr/share/pvm3 /bin/bash

Add

The command to add a user is useradd

In the example we created the patxi user who belongs to the users group and ftp, has as shell /bin/shell, we assign the password key and their home folder will be /home/patxi

This command supports the following parameters:

-d User's home directory
-s The user's Shell
-p Password
-g Primary group to which we assign the user
-G Groups which the user belongs
-m We force the creation of the directory in your home

In the file /etc/default/useradd saved default settings for the useradd command and in the directory /etc/skel are the files and directories by default will be in the user's home directory when you create it

Edit

The command to modify users is usermod

In the example we have modified the user patxi who belonged to the group users and ftp, now his main group is a server, although it still belongs to the groups users and ftp

This command supports the following parameters:

-d To modify a user's home directory
-s Modify the user's shell
-p Modify Password
-g Change primary group to which we assign the user
-G Modify groups which the user belongs

Delete

The command to delete users is userdel

In the example deletion by user patxi and in addition we have forced to delete the contents of your home when you use the-r parameter, if we had not used, would still exist

Change the key

The command to change the key of a user is the passwd command. Keep in mind that you must have sufficient permissions to be able to make the change, either because of who is running the command is the user or the superuser root

If we want to change the password of the root user, and we have sufficient permissions, can be done by leaving the parameter empty user

shadow

The structure of the file shadow is the following:

user Name of the user
encrypted password The password with a strong encryption
1 Days since 1-1-1970 where the password was changed for the last time
2 The minimum number of days between password changes
3 Maximum days of validity of the account
4 Days of warning before password expires
5 Days after a password expires to disable account
6 Expiration date. days since 1-1-1970, where the account is deshabilatada and the user will not be able to log in

Groups Linux

The users are grouped into groups. The groups are also identified by a name and the system associates an identification number (GID). Every user has a primary group, but can belong to multiple groups, which inherits its privileges. Groups allow you to give the rights and restrict options globally to multiple users

The relationship of the groups is saved in the file /etc/group. There is also the file /etc/gshadow for encrypted passwords of group, although it is not very used

Structure

The structure of the group file is the following:

group The name of the group (it is recommended that you do not have more than 8 characters)
x An “x” indicates that the password is stored in /etc/gshadow
gid Each group is assigned a number identifier (gid) between 0 (root) and 65535 (the gid 0 to 499 are reserved by the system), so it will start numbering from 500
members list List of the members of the group, separated by commas (without spaces)

Some of the most common groups can be found in the following table:

Group GID Members
root 0 root
bin 1 root, bin, daemon
daemon 2 root, bin, daemon
sys 3 root, bin, adm
adm 4 root, adm, daemon
tty 5
disk 6 root
lp 7
mem 8
kmem 9
wheel 10 root
mail 12 mail
news 13 news
uucp 14 uucp
man 15
games 20
gopher 30
dip 40
ftp 50
lock 54
nobody 99
users 100
slocate 21
floppy 19
vcsa 69
rpm 37 rpm
utmp 22
wnn 49
ntp 38
nscd 28
apache 48
mysql 27
mailnull 47
smmsp 51
rpc 32
xfs 43
gdm 42
rpcuser 29
nfsnobody 65534
ident 98
radvd 75
sshd 74
postgres 26
squid 23
named 25
pcap 77
wine 66
Mailman 41
netdump 34
ldap 55
postdrop 90
postfix 89
privoxy 101
pvm 24

Add

The command to add groups groupadd

In the example we have set the group server with a gid of 500, in case you do not put anything you would use the greater than 500 is not used by another group. You can use the-g parameter to set the gid manually

If you want to add existing users to the newly created group will use the gpasswd command

In the example we added the user patxi with the parameter -a to the group server

Edit

The command to change groups is groupmod

In the example we have modified the gid to 501 of the group server

This command supports the following parameters:

-g Change gid of the group
-n Modify the name of the group

This command only makes changes in the file /etc/group, so the rest of
modifications involved in changing the gid of a group, you have to do manually in the files /etc/passwd and /etc/gshadow

Delete

The command to delete a group groupdel

In the example deleted the group server

You cannot delete a group that is a initial group for any user, without first deleting the user

The command does not traverse the file system looking for files owned by the group. If
we want to remove them, we have manually or with command-deletion of files

If we want to delete existing users to the newly created group will use the gpasswd command

In the example we have removed the user patxi with the-d parameter of the group server. But this will not delete the home directory of the group