Translated to Spanish the day15 file
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
This commit is contained in:
parent
cb45ee8342
commit
6ca8d0659f
@ -1,111 +1,111 @@
|
||||
## Linux Commands for DevOps (Actually everyone)
|
||||
## Comandos de Linux para DevOps (en realidad son todos)
|
||||
|
||||
I mentioned [yesterday](day14.md) that we are going to be spending a lot of time in the terminal with some commands to get stuff done.
|
||||
[Ayer](day14.md) se mencionó que vamos a pasar mucho tiempo en la terminal con algunos comandos para hacer cosas.
|
||||
|
||||
I also mentioned that with our vagrant provisioned VM we can use `vagrant ssh` and gain access to our box. You will need to be in the same directory as we provisioned it from.
|
||||
También mencioné que con nuestra MV aprovisionada con vagrant podemos usar `vagrant ssh` y acceder a nuestra caja. Necesitarás estar en el mismo directorio desde el que la aprovisionamos.
|
||||
|
||||
For SSH you won't need the username and password, you will only need that if you decide to log in to the Virtual Box console.
|
||||
Para SSH no necesitarás el nombre de usuario y la contraseña, sólo lo necesitarás si decides entrar en la consola de Virtual Box.
|
||||
|
||||
This is where we want to be as per below:
|
||||
Aquí es donde queremos estar según lo indicado a continuación:
|
||||
|
||||

|
||||
|
||||
## Commands
|
||||
## Comandos
|
||||
|
||||
I cannot cover all the commands here, there are pages and pages of documentation that cover these but also if you are ever in your terminal and you just need to understand options to a specific command we have the `man` pages short for manual. We can use this to go through each of the commands we touch on during this post to find out more options for each one. We can run `man man` which will give you the help for manual pages. To escape the man pages you should press `q` for quit.
|
||||
Es imposible cubrir todos los comandos en una hora, durante 7 días, hay páginas y páginas de documentación que los cubren. Si alguna vez estás en tu terminal y sólo necesitas entender las opciones de un comando específico nos ayudarán las páginas `man` (abreviatura de manual). Podemos usar esto para ir a través de cada uno de los comandos que tocamos durante este post para encontrar más opciones para cada uno. Podemos ejecutar `man man` que nos dará la ayuda del comando del manual. Para salir de las páginas de manual hay que pulsar `q`.
|
||||
|
||||

|
||||

|
||||
|
||||
`sudo` If you are familiar with Windows and the right click `run as administrator` we can think of `sudo` as very much this. When you run a command with this command you will be running it as `root` it will prompt you for the password before running the command.
|
||||
`sudo` - Si estás familiarizado con Windows y el botón derecho `ejecutar como administrador` podemos pensar que `sudo` es algo parecido, teniendo en cuenta que no es lo mismo. Cuando ejecutes un comando con `sudo` lo estarás ejecutando como `root` y te pedirá la contraseña antes de ejecutar el comando.
|
||||
|
||||

|
||||
|
||||
For one off jobs like installing applications or services, you might need that `sudo command` but what if you have several tasks to deal with and you want to live as `sudo` for a while? This is where you can use `sudo su` again the same as `sudo` once entered you will be prompted for your `root` password. In a test VM like ours, this is fine but I would find it very hard for us to be rolling around as `root` for prolonged periods, bad things can happen. To get out of this elevated position you simply type in `exit`
|
||||
Para trabajos puntuales como la instalación de aplicaciones o servicios, puedes necesitar el comando `sudo` pero ¿qué pasa si tienes varias tareas que realizar y quieres vivir como `sudo` durante un tiempo? Aquí es donde puedes usar `sudo su` que te llevará al prompt del usuario `root`. En una VM de prueba como la nuestra, esto está bien pero me parecería muy difícil que estuviéramos rodando como `root` durante periodos prolongados, pueden pasar cosas malas. Para salir de esta posición elevada simplemente hay que teclear `exit`.
|
||||
|
||||

|
||||
|
||||
I find myself using `clear` all the time, the `clear` command does exactly what it says it is going to clear the screen of all previous commands, putting your prompt to the top and giving you a nice clean workspace. Windows I think is `cls` in the .mdprompt.
|
||||
Cada dos por tres estarás utilizando el comando `clear`. Hace exactamente lo que dice, limpiar la pantalla de todos los comandos anteriores, poniendo su prompt en la parte superior y dándole un espacio de trabajo agradable y limpio.
|
||||
|
||||

|
||||
|
||||
Let's now look at some commands where we can actually create things within our system and then visualise them in our terminal, first of all, we have `mkdir` which will allow us to create a folder in our system. With the following command, we can create a folder in our home directory called Day15 `mkdir Day15`
|
||||
Veamos ahora algunos comandos con los que podemos crear cosas dentro de nuestro sistema y luego visualizarlas en nuestra terminal. En primer lugar, tenemos `mkdir` que nos permitirá crear una carpeta en nuestro sistema. Con el siguiente comando, podemos crear una carpeta en nuestro directorio principal llamada Day15 `mkdir Day15`
|
||||
|
||||

|
||||
|
||||
With `cd` this allows us to change the directory, so for us to move into our newly created directory we can do this with `cd Day15` tab can also be used to autocomplete the directory available. If we want to get back to where we started we can use `cd ..`
|
||||
Con `cd` podemos cambiar el directorio, por lo que para movernos a nuestro directorio recién creado podemos hacerlo con la pestaña `cd Day15`. También se puede utilizar para autocompletar el directorio disponible. Si queremos volver al punto de partida podemos utilizar `cd ..`
|
||||
|
||||

|
||||
|
||||
`rmdir` allows for us to remove the directory, if we run `rmdir Day15` then the folder will be removed (note that this will only work if you have nothing in the folder)
|
||||
`rmdir` nos permite eliminar el directorio, si ejecutamos `rmdir Day15` entonces la carpeta será eliminada (ten en cuenta que esto sólo funcionará si no tienes nada en la carpeta)
|
||||
|
||||

|
||||
|
||||
I am sure we have all done it where we have navigated to the depths of our file system to a directory and not known where we are. `pwd` gives us the printout of the working directory, pwd as much as it looks like password it stands for print working directory.
|
||||
A todos nos ha pasado que hemos navegado hasta las profundidades de nuestro sistema de archivos hasta un directorio muy anidado y no sabemos dónde estamos en este momento. Con `pwd` veremos el directorio de trabajo.
|
||||
|
||||

|
||||
|
||||
We know how to create folders and directories but how do we create files? We can create files using the `touch` command if we were to run `touch Day15` this would create a file. Ignore `mkdir` we are going to see this again later.
|
||||
Sabemos cómo crear carpetas y directorios, pero ¿cómo crear archivos? Podemos crear archivos usando el comando `touch` si ejecutáramos `touch Day15` esto crearía un archivo.
|
||||
|
||||

|
||||
|
||||
`ls` I can put my house on this, you will use this command so many times, this is going to list all the files and folders in the current directory. Let's see if we can see that file we just created.
|
||||
`ls` - vas a usarlo muchas veces. Esto va a listar todos los archivos y carpetas en el directorio actual. Veamos si podemos ver el archivo que acabamos de crear.
|
||||
|
||||

|
||||
|
||||
How can we find files on our Linux system? `locate` is going to allow us to search our file system. If we use `locate Day15` it will report back the location of the file. The bonus round is that if you know that the file does exist but you get a blank result then run `sudo updatedb` which will index all the files in the file system then run your `locate` again. If you do not have `locate` available to you, you can install it using this command `sudo apt install mlocate`
|
||||
¿Cómo podemos encontrar archivos en nuestro sistema Linux? `locate` nos va a permitir buscar en nuestro sistema de archivos. Si usamos `locate Day15` nos informará de la ubicación del archivo. La ventaja es que si sabes que el archivo existe pero obtienes un resultado en blanco, entonces ejecuta `sudo updatedb` que indexará todos los archivos en el sistema de archivos y luego ejecuta tu `locate` de nuevo. Si no tienes `locate` disponible, puedes instalarlo usando este comando `sudo apt install mlocate`
|
||||
|
||||

|
||||
|
||||
What about moving files from one location to another? `mv` is going to allow you to move your files. Example `mv Day15 90DaysOfDevOps` will move your file to the 90DaysOfDevOps folder.
|
||||
¿Qué pasa con el movimiento de archivos de una ubicación a otra? `mv` te va a permitir mover tus archivos. Ejemplo `mv Day15 90DaysOfDevOps` moverá tu archivo a la carpeta 90DaysOfDevOps.
|
||||
|
||||

|
||||
|
||||
We have moved our file but what if we want to rename it now to something else? We can do that using the `mv` command again... WOT!!!? yep we can simply use `mv Day15 day15` to change to upper case or we could use `mv day15 AnotherDay` to change it altogether, now use `ls` to check the file.
|
||||
Hemos movido nuestro archivo, pero ¿qué pasa si ahora queremos renombrarlo a otra cosa? Podemos hacerlo usando el comando `mv` de nuevo... Sí, podemos usar simplemente `mv Day15 day15` para cambiar a mayúsculas o podemos usar `mv day15 AnotherDay` para cambiarlo por completo, ahora usa `ls` para comprobar el archivo.
|
||||
|
||||

|
||||
|
||||
Enough is enough, let's now get rid (delete)of our file and maybe even our directory if we have one created. `rm` simply `rm AnotherDay` will remove our file. We will also use quite a bit `rm -R` which will recursively work through a folder or location. We might also use `rm -R -f` to force the removal of all of those files. Spoiler if you run `rm -R -f /` add sudo to it and you can say goodbye to your system....!
|
||||
Ya es suficiente, ahora vamos a deshacernos (borrar) de nuestro archivo y quizás incluso de nuestro directorio si tenemos uno creado. `rm` simplemente `rm OtroDía` eliminará nuestro archivo. También usaremos bastante `rm -R` que trabajará recursivamente a través de una carpeta o ubicación. También podemos usar `rm -R -f` para forzar la eliminación de todos esos archivos. ¡Spoiler si ejecuta `rm -R -f /` añada sudo y podrá decir adiós a su sistema....!
|
||||
|
||||

|
||||
|
||||
We have looked at moving files around but what if I just want to copy files from one folder to another, simply put its very similar to the `mv` command but we use `cp` so we can now say `cp Day15 Desktop`
|
||||
Hemos visto cómo mover archivos, pero ¿qué pasa si sólo quiero copiar archivos de una carpeta a otra, simplemente es muy similar al comando `mv`, pero usamos `cp` por lo que ahora podemos decir `cp Day15 Desktop`
|
||||
|
||||

|
||||
|
||||
We have created folders and files but we haven't put any contents into our folder, we can add contents a few ways but an easy way is `echo` we can also use `echo` to print out a lot of things in our terminal, I use echo a lot to print out system variables to know if they are set or not at least. we can use `echo "Hello #90DaysOfDevOps" > Day15` and this will add this to our file. We can also append to our file using `echo "Commands are fun!" >> Day15`
|
||||
Hemos creado carpetas y archivos pero no hemos puesto ningún contenido en nuestra carpeta, podemos añadir contenido de varias maneras pero una manera fácil es `echo`. También podemos usar `echo` para imprimir muchas cosas en nuestro terminal, por ejemplo, las variables del sistema, para saber si están establecidas o no. Podemos usar `echo "Hello #90DaysOfDevOps" > Day15` y esto se añadirá a un archivo. También podemos añadir a nuestro archivo usando `echo "¡Los comandos son divertidos!" >> Día15`
|
||||
|
||||

|
||||
|
||||
Another one of those commands you will use a lot! `cat` short for concatenate. We can use `cat Day15` to see the contents inside the file. Great for quickly reading those configuration files.
|
||||
¡Otro de esos comandos que usarás mucho! `cat` es la abreviatura de concatenar. Podemos usar `cat Day15` para ver el contenido dentro del archivo. Genial para leer rápidamente esos archivos de configuración.
|
||||
|
||||

|
||||
|
||||
If you have a long complex configuration file and you want or need to find something fast in that file vs reading every line then `grep` is your friend, this will allow us to search your file for a specific word using `cat Day15 | grep "#90DaysOfDevOps"`
|
||||
Si tienes un archivo de configuración largo y complejo y quieres o necesitas encontrar algo rápidamente en ese archivo frente a leer cada línea entonces `grep` es tu amigo, esto nos permitirá buscar en tu archivo una palabra específica usando `cat Day15 | grep "#90DaysOfDevOps"`.
|
||||
|
||||

|
||||
|
||||
If you are like me and you use that `clear` command a lot then you might miss some of the commands previously ran, we can use `history` to find out all those commands we have run prior. `history -c` will remove the history.
|
||||
Si eres como yo y usas mucho el comando `clear` entonces puedes perderte algunos de los comandos ejecutados anteriormente, podemos usar `history` para encontrar todos esos comandos que hemos ejecutado anteriormente. El comando `history -c` eliminará el historial.
|
||||
|
||||
When you run `history` and you would like to pick a specific command you can use `!3` to choose the 3rd command in the list.
|
||||
Cuando ejecutas `history` y quieres elegir un comando específico puedes usar `!3` para elegir el tercer comando de la lista.
|
||||
|
||||
You are also able to use `history | grep "Command` to search for something specific.
|
||||
También puede usar `history | grep "Command` para buscar algo específico.
|
||||
|
||||
On servers to trace back when was a command executed, it can be useful to append the date and time to each command in the history file.
|
||||
En los servidores, para rastrear cuándo se ejecutó un comando, puede ser útil añadir la fecha y la hora a cada comando en el archivo del historial.
|
||||
|
||||
The following system variable controls this behaviour:
|
||||
La siguiente variable del sistema controla este comportamiento:
|
||||
|
||||
```
|
||||
```shell
|
||||
HISTTIMEFORMAT="%d-%m-%Y %T "
|
||||
```
|
||||
|
||||
You can easily add to your bash_profile:
|
||||
Puedes añadir fácilmente a tu bash_profile:
|
||||
|
||||
```
|
||||
echo 'export HISTTIMEFORMAT="%d-%m-%Y %T "' >> ~/.bash_profile
|
||||
```
|
||||
|
||||
So as useful to allow the history file to grow bigger:
|
||||
Es útil para permitir que el archivo de la historia pueda crecer más:
|
||||
|
||||
```
|
||||
echo 'export HISTSIZE=100000' >> ~/.bash_profile
|
||||
@ -114,72 +114,73 @@ echo 'export HISTFILESIZE=10000000' >> ~/.bash_profile
|
||||
|
||||

|
||||
|
||||
Need to change your password? `passwd` is going to allow us to change our password. Note that when you add your password like this when it is hidden it will not be shown in `history` however if your command has `-p PASSWORD` then this will be visible in your `history`.
|
||||
¿Necesitas cambiar tu contraseña? `passwd` nos va a permitir cambiar nuestra contraseña. Ten en cuenta que cuando añades tu contraseña de esta manera cuando está oculta no se mostrará en el `history`. Sin embargo, si tu comando tiene `-p PASSWORD` será visible en tu `history`.
|
||||
|
||||

|
||||
|
||||
We might also want to add new users to our system, we can do this with `useradd` we have to add the user using our `sudo` command, we can add a new user with `sudo useradd NewUser`
|
||||
También podemos querer añadir nuevos usuarios a nuestro sistema, podemos hacerlo con `useradd` tenemos que añadir el usuario usando nuestro comando `sudo`, podemos añadir un nuevo usuario con `sudo useradd NewUser`
|
||||
|
||||

|
||||
|
||||
Creating a group again requires `sudo` and we can use `sudo groupadd DevOps` then if we want to add our new user to that group we can do this by running `sudo usermod -a -G DevOps` `-a` is add and `-G` is group name.
|
||||
La creación de un grupo requiere nuevamente de `sudo` y podemos usar `sudo groupadd DevOps` luego si queremos agregar nuestro nuevo usuario a ese grupo podemos hacerlo ejecutando `sudo usermod -a -G DevOps`. `-a` es añadir y `-G` es el nombre del grupo.
|
||||
|
||||

|
||||
|
||||
How do we add users to the `sudo` group, this would be a very rare occasion for this to happen but to do this it would be `usermod -a -G sudo NewUser`
|
||||
Como añadimos usuarios al grupo `sudo`, esto sería una ocasión muy rara para que esto ocurra pero sería así: `usermod -a -G sudo NewUser`
|
||||
|
||||
### Permissions
|
||||
### Permisos
|
||||
|
||||
read, write and execute are the permissions we have on all of our files and folders on our Linux system.
|
||||
leer, escribir y ejecutar son los permisos que tenemos en todos nuestros archivos y carpetas en nuestro sistema Linux.
|
||||
|
||||
A full list:
|
||||
Una lista completa:
|
||||
|
||||
- 0 = None `---`
|
||||
- 1 = Execute only `--X`
|
||||
- 2 = Write only `-W-`
|
||||
- 3 = Write & Execute `-WX`
|
||||
- 4 = Read Only `R--`
|
||||
- 5 = Read & Execute `R-X`
|
||||
- 6 = Read & Write `RW-`
|
||||
- 7 = Read, Write & Execute `RWX`
|
||||
- 0 = Ninguno `---`
|
||||
- 1 = Solo ejecutar `--X`
|
||||
- 2 = Solo escribir `-W-`
|
||||
- 3 = Escribir y ejecutar `-WX`
|
||||
- 4 = Solo leer `R--`
|
||||
- 5 = Leer y ejecutar `R-X`
|
||||
- 6 = Leer y escribir `RW-`
|
||||
- 7 = Leer , escribir y ejecutar `RWX`
|
||||
|
||||
You will also see `777` or `775` and these represent the same numbers as the list above but each one represents **User - Group - Everyone**
|
||||
También verás `777` o `775` y estos representan los mismos números que la lista anterior pero cada uno representa **User - Group - Everyone**
|
||||
|
||||
Let's take a look at our file. `ls -al Day15` you can see the 3 groups mentioned above, user and group have read & write but everyone only has read.
|
||||
|
||||

|
||||
|
||||
We can change this using `chmod` you might find yourself doing this if you are creating binaries a lot on your systems as well and you need to give the ability to execute those binaries. `chmod 750 Day15` now run `ls -al Day15` if you want to run this for a whole folder then you can use `-R` to recursively do that.
|
||||
Podemos cambiar esto usando `chmod`. Puedes encontrarte haciendo esto si estás creando binarios en tus sistemas, que necesitarás dar la capacidad de ejecutar esos binarios. Si quieres ejecutar esto para toda una carpeta, puedes usar `R` para hacerlo recursivamente.
|
||||
|
||||

|
||||
|
||||
What about changing the owner of the file? We can use `chown` for this operation, if we wanted to change the ownership of our `Day15` from user `vagrant` to `NewUser` we can run `sudo chown NewUser Day15` again `-R` can be used.
|
||||
¿Qué pasa con el cambio de propietario del archivo? Podemos usar `chown` para esta operación, si queremos cambiar la propiedad de nuestro `Day15` del usuario `vagrant` a `NewUser` podemos ejecutar `sudo chown NewUser Day15` de nuevo se puede usar `-R`.
|
||||
|
||||

|
||||
|
||||
A command that you will come across is `awk` which comes in real use when you have an output that you only need specific data from. like running `who` we get lines with information, but maybe we only need the names. We can run `who | awk '{print $1}'` to get just a list of that first column.
|
||||
Un comando que te encontrarás es `awk` que viene en uso real cuando tienes una salida de la que sólo necesitas datos específicos. Ejecutando `who` obtenemos líneas con información, pero tal vez sólo necesitamos los nombres. Podemos ejecutar `who | awk '{print $1}'` para obtener sólo una lista de esa primera columna.
|
||||
|
||||

|
||||
|
||||
If you are looking to read streams of data from standard input, then generate and execute command lines; meaning it can take the output of a command and passes it as an argument of another command. `xargs` is a useful tool for this use case. If for example, I want a list of all the Linux user accounts on the system I can run. `cut -d: -f1 < /etc/passwd` and get the long list we see below.
|
||||
Si lo que buscas es leer flujos de datos desde la entrada estándar, entonces genera y ejecuta líneas de comando; lo que significa que puede tomar la salida de un comando y pasarla como argumento de otro comando. `xargs` es una herramienta útil para este caso de uso. Si, por ejemplo, quiero una lista de todas las cuentas de usuario de Linux en el sistema, puedo ejecutar `cut -d: -f1 < /etc/passwd` y obtener la larga lista que vemos a continuación.
|
||||
|
||||

|
||||
|
||||
If I want to compact that list I can do so by using `xargs` in a command like this `cut -d: -f1 < /etc/passwd | sort | xargs`
|
||||
Si quiero compactar esa lista puedo hacerlo usando `xargs` en un comando como este `cut -d: -f1 < /etc/passwd | sort | xargs`
|
||||
|
||||

|
||||
|
||||
I didn't mention the `cut` command either, this allows us to remove sections from each line of a file. It can be used to cut parts of a line by byte position, character and field. The `cut -d " " -f 2 list.txt` command allows us to remove that first letter we have and just display our numbers. There are so many combinations that can be used here with this command, I am sure I have spent too much time trying to use this command when I could have extracted data quicker manually.
|
||||
El anterior comando `cut` nos permite eliminar secciones de cada línea de un archivo. Se puede utilizar para cortar partes de una línea por posición de byte, carácter y campo. El comando `cut -d " " -f 2 list.txt` nos permite eliminar la primera letra que tenemos y sólo mostrar nuestros números. Hay tantas combinaciones que se pueden usar aquí con este comando, que estoy seguro que he pasado demasiado tiempo tratando de usar este comando cuando podría haber extraído los datos más rápidamente de forma manual.
|
||||
|
||||

|
||||
|
||||
Also to note if you type a command and you are no longer happy with it and you want to start again just hit control + c and this will cancel that line and start you fresh.
|
||||
También hay que tener en cuenta que si escribes un comando y ya no estás contento con él y quieres empezar de nuevo sólo tienes que pulsar control + c y esto cancelará esa línea y empezará de nuevo.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [Learn the Linux Fundamentals - Part 1](https://www.youtube.com/watch?v=kPylihJRG70)
|
||||
- [Linux for hackers (don't worry you don't need to be a hacker!)](https://www.youtube.com/watch?v=VbEx7B_PTOE)
|
||||
- [Webminal](https://www.webminal.org/)
|
||||
|
||||
See you on [Day16](day16.md)
|
||||
Nos vemos el [Día 16](day16.md)
|
||||
|
||||
This is a pretty heavy list already but I can safely say that I have used all of these commands in my day to day, be it from an administering Linux servers or on my Linux Desktop, it is very easy when you are in Windows or macOS to navigate the UI but in Linux Servers, they are not there, everything is done through the terminal.
|
||||
Esta es una lista bastante pesada, pero esos comandos se usan en el día a día, ya sea desde una administración de servidores Linux o en en un Desktop de Linux. Es muy fácil cuando estás en Windows o macOS navegar por la UI pero si quieres ser verdaderamente rápido y eficaz, este es el camino, gestionar todo a través de la terminal.
|
Loading…
Reference in New Issue
Block a user