Merge pull request #251 from manuelver/feature/translateES-05

This commit is contained in:
Michael Cade 2022-11-28 01:05:18 +00:00 committed by GitHub
commit 34ee1946a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 100 additions and 101 deletions

View File

@ -1,47 +1,51 @@
## The Big Picture: DevOps and Linux
## El panorama: DevOps & Linux
Linux and DevOps share very similar cultures and perspectives; both are focused on customization and scalability. Both of these aspects of Linux are of particular importance for DevOps.
Linux y DevOps comparten culturas y perspectivas muy similares; ambos se centran en la personalización y la escalabilidad. Estos dos aspectos de Linux son de especial importancia para DevOps.
A lot of technologies start on Linux, especially if they are related to software development or managing infrastructure.
Muchas tecnologías parten de Linux, especialmente si están relacionadas con el desarrollo de software o la gestión de infraestructuras.
As well lots of open source projects, especially DevOps tools, were designed to run on Linux from the start.
Además, muchos proyectos de código abierto, especialmente las herramientas DevOps, se diseñaron para funcionar en Linux desde el principio.
From a DevOps perspective or any operations role perspective, you are going to come across Linux I would say mostly. There is a place for WinOps but the majority of the time you are going to be administering and deploying Linux servers.
Desde el punto de vista de DevOps o de cualquier función de operaciones, te encontrarás con Linux. Hay un lugar para WinOps pero la mayor parte del tiempo vas a estar administrando y desplegando servidores Linux. 🐧
I have been using Linux daily for several years but my go to desktop machine has always been either macOS or Windows. However, when I moved into the Cloud Native role I am in now I took the plunge to make sure that my laptop was fully Linux based and my daily driver, whilst I still needed Windows for work-based applications and a lot of my audio and video gear does not run on Linux I was forcing myself to run a Linux desktop full time to get a better grasp of a lot of the things we are going to touch on over the next 7 days.
Michael Cade ha estado usando Linux diariamente durante varios años, aun siendo su equipo Desktop de macOS o Windows. Sin embargo, cuando empezó el rol de Cloud Native en el que está actualmente, se aseguró de que su portátil estuviera completamente basado en Linux y fuera el Sistema Operativo utilizado a diario, mientras que todavía necesitaba Windows por aplicaciones para el trabajo que no son multiplataforma y por incompatibilidad de equipos de audio y vídeo que no se ejecutan en Linux por secuestro corporativo de Windows o Mac. Quería ejecutar un Linux Desktop a tiempo completo para obtener una mejor comprensión de muchas de las cosas que vamos a ver en los próximos 7 días.
## Getting Started
Por otra parte, el traductor, lleva más de 10 años con Sistemas Operativos Linux, solo utilizando Windows o MacOS en momentos puntuales por imperativos de entornos sociales o laborales. Tan solo echo de menos Windows si me apetece jugar a un juego de vanguardia o quiero probar software, en el primer caso tengo un disco duro preparado por si fuera necesario; y en el segundo caso, para simplemente probar, tengo una virtualización de Windows 10. Windows 11, hasta la fecha es un verdadero desastre. Y tengo que decir que Microsoft se puso mucho las pilas con la versión 10 y, aunque no cumple mis necesidades operativas y de privacidad, tengo que admitir que es bastante robusto comparado a sus anteriores fiascos.
I am not suggesting you do the same as me by any stretch as there are easier options which are less destructive but I will say that taking that full-time step forces you to learn faster how to make things work on Linux.
## Empecemos
For the majority of these 7 days, I am going to deploy a Virtual Machine in Virtual Box on my Windows machine. I am also going to deploy a desktop version of a Linux distribution, whereas a lot of the Linux servers you will be administering will likely be servers that come with no GUI and everything is shell-based. However, as I said at the start a lot of the tools that we covered throughout this whole 90 days started on Linux I would also strongly encourage you to dive into running that Linux Desktop for that learning experience as well.
No se pretende conseguir que el lector siga los mismos pasos descritos anteriormente, ni mucho menos, pero sí que puede ser interesante conocer las opiniones anteriores. Hay opciones más sencillas, por supuesto, los Sistemas Operativos de Microsoft o Apple son un "llave en mano", pero hay que destacar que dar el paso de utilizar a tiempo completo alguna distribución Linux te obliga a aprender más rápido cómo hacer que las cosas funcionen, familiarizandote con la shell y, al fin y al cabo, te permite conocer como funcionan los Sistemas Operativos, la red y su relación con el hardware.
For the rest of this post, we are going to concentrate on getting a Ubuntu Desktop virtual machine up and running in our Virtual Box environment. Now we could just download [Virtual Box](https://www.virtualbox.org/) and grab the latest [Ubuntu ISO](https://ubuntu.com/download) from the sites linked and go ahead and build out our desktop environment but that wouldn't be very DevOps of us, would it?
Durante la mayor parte de estos 7 días, desplegaremos una máquina virtual en Virtual Box con una versiones Desktop de una distribución de Linux. Muchos de los servidores Linux que administrarás probablemente serán servidores que vienen sin interfaz gráfica de usuario ([GUI](https://es.wikipedia.org/wiki/Interfaz_gr%C3%A1fica_de_usuario)) y todo está basado en el shell ([CLI](https://es.wikipedia.org/wiki/Interfaz_de_l%C3%ADnea_de_comandos)). Sin embargo, como dije al principio, muchas de las herramientas que cubrimos a lo largo de estos 90 días empezaron en Linux, es aconsejable que te sumerjas en la ejecución de distribuciones Linux, sobre todo en CLI, para tener también esa experiencia de aprendizaje que te servirá u mucho, incluso para entender mejor otros Sistemas Operativos como Windows o MacOS.
Another good reason to use most Linux distributions is that they are free and open-source. We are also choosing Ubuntu as it is probably the most widely used distribution deployed not thinking about mobile devices and enterprise RedHat Enterprise servers. I might be wrong there but with CentOS and the history there I bet Ubuntu is high on the list and it's super simple.
Para el resto de este post, vamos a centrarnos en conseguir una máquina virtual de Ubuntu Desktop en nuestro entorno de Virtual Box. Antes de seguir descarga de las páginas oficiales [Virtual Box](https://www.virtualbox.org/) y la última versión de [Ubuntu ISO](https://ubuntu.com/download).
## Introducing HashiCorp Vagrant
Otra buena razón para utilizar distribuciones Linux es que son gratuitas y de [código abierto](https://es.wikipedia.org/wiki/C%C3%B3digo_abierto), e incluso algunas de [software libre](https://es.wikipedia.org/wiki/Software_libre). Elegimos Ubuntu, ya que actualmente es la distribución más utilizada, sin pensar en los smartphones y los servidores empresariales RedHat Enterprise. Esto es una visión subjetiva, puede ser errónea, pero con lo sucedido en los últimos tiempos con CentOS puede que Ubuntu se haya puesto en lo alto de la lista.
Vagrant is a CLI utility that manages the lifecycle of your virtual machines. We can use vagrant to spin up and down virtual machines across many different platforms including vSphere, Hyper-v, Virtual Box and also Docker. It does have other providers but we will stick with Virtual Box here so we are good to go.
## Presentación de HashiCorp Vagrant
The first thing we need to do is get Vagrant installed on our machine, when you go to the downloads page you will see all the operating systems listed for your choice. [HashiCorp Vagrant](https://www.vagrantup.com/downloads) I am using Windows so I grabbed the binary for my system and went ahead and installed this on my system.
Vagrant es una utilidad CLI que gestiona el ciclo de vida de tus máquinas virtuales. Podemos utilizar vagrant para hacer girar y bajar las máquinas virtuales a través de muchas plataformas diferentes, incluyendo vSphere, Hyper-v, Virtual Box y también Docker. Tiene otros proveedores, pero nos quedaremos con Virtual Box, así que estamos listos para continuar.
Next up we also need to get [Virtual Box](https://www.virtualbox.org/wiki/Downloads) installed. Again, this can also be installed on many different operating systems and a good reason to choose this and vagrant is that if you are running Windows, macOS, or Linux then we have you covered here.
Lo primero que tenemos que hacer es instalar Vagrant en nuestra máquina, cuando vayas a la página de descargas verás todos los sistemas operativos listados para tu elección. [HashiCorp Vagrant](https://www.vagrantup.com/downloads).
Both installations are pretty straightforward and both have great communitites around them so feel free to reach out if you have issues and I can try and assist too.
Lo siguiente que tenemos que hacer es instalar [Virtual Box](https://www.virtualbox.org/wiki/Downloads) Se puede instalar en muchos sistemas operativos diferentes y una buena razón para elegir esto y vagrant es que podrás utilizarlo tanto en Windows, macOS, o Linux.
## Our first VAGRANTFILE
Ambas instalaciones son bastante sencillas y ambas tienen una gran comunidad alrededor de ellas, así que siéntete libre de contactar con ellos si tienes problemas. Sus páginas de Documentación:
- [Virtual Box](https://www.virtualbox.org/wiki/Documentation)
- [Ubuntu](https://help.ubuntu.com/)
- [Vagrant](https://developer.hashicorp.com/vagrant/docs)
The VAGRANTFILE describes the type of machine we want to deploy. It also defines the configuration and provisioning for this machine.
## Nuestro primer VAGRANTFILE
When it comes to saving these and organizing your VAGRANTFILEs I tend to put them in their folders in my workspace. You can see below how this looks on my system. Hopefully following this you will play around with Vagrant and see the ease of spinning up different systems, it is also great for that rabbit hole known as distro hopping for Linux Desktops.
El VAGRANTFILE describe el tipo de máquina que queremos desplegar. También define la configuración y el aprovisionamiento para esta máquina.
Para guardar máquinas virtuales, los VAGRANTFILEs se ordenan en carpetas en distintos espacios de trabajo. Puedes ver a continuación cómo se ve esto en un Windows. Espero que después de esto juegues con Vagrant y veas la facilidad de hacer girar diferentes sistemas, también es genial para ese agujero de conejo conocido como salto de distro para Linux Desktop.
![](Images/Day14_Linux1.png)
Let's take a look at that VAGRANTFILE and see what we are building.
Echemos un vistazo a ese VAGRANTFILE y veamos lo que estamos construyendo.
```
Vagrant.configure("2") do |config|
config.vm.box = "chenhan/ubuntu-desktop-20.04"
@ -57,54 +61,48 @@ Vagrant.configure("2") do |config|
end
end
```
This is a very simple VAGRANTFILE overall. We are saying that we want a specific "box", a box being possibly either a public image or private build of the system you are looking for. You can find a long list of "boxes" publicly available here in the [public catalogue of Vagrant boxes](https://app.vagrantup.com/boxes/search)
Este es un VAGRANTFILE muy simple. Estamos diciendo que queremos una "box" específica, siendo una imagen pública o una construcción privada del sistema que estás buscando. Puedes encontrar una larga lista de "boxes" disponibles públicamente aquí en el [catálogo público de boxes Vagrant](https://app.vagrantup.com/boxes/search)
Next line we're saying that we want to use a specific provider and in this case it's `VirtualBox`. We also define our machine's memory to `8GB` and the number of CPUs to `4`. My experience tells me that you may want to also add the following line if you experience display issues. This will set the video memory to what you want, I would ramp this right up to `128MB` but it depends on your system.
En la siguiente línea decimos que queremos usar un proveedor específico y en este caso es `VirtualBox`. También definimos la memoria de nuestra máquina a `8GB` y el número de CPUs a `4`. Mi experiencia me dice que es posible que quieras añadir también la siguiente línea si experimentas problemas de visualización. Esto establecerá la memoria de vídeo a lo que usted quiere, yo aumentaría esto hasta `128MB` pero depende de su sistema.
```
v.customize ["modifyvm", :id, "--vram", ""]
```
I have also placed a copy of this specific vagrant file in the [Linux Folder](Linux/VAGRANTFILE)
También hay que colocar una copia de este archivo específico de vagrant en la [Carpeta Linux](Linux/VAGRANTFILE)
## Provisioning our Linux Desktop
## Aprovisionando nuestro Linux Desktop
We are now ready to get our first machine up and running, in our workstation's terminal. In my case I am using PowerShell on my Windows machine. Navigate to your projects folder and where you will find your VAGRANTFILE. Once there you can type the command `vagrant up` and if everything's alright you will see something like this.
Ya estamos listos para poner en marcha nuestra primera máquina, en el terminal de nuestra estación de trabajo. Más abajo puedes ver un ejemplo en PowerShell de Windows. Navega hasta tu carpeta de proyectos y allí encontrarás tu VAGRANTFILE. Una vez allí puedes escribir el comando `vagrant up` y si todo está bien verás algo así.
![](Images/Day14_Linux2.png)
Another thing to add here is that the network will be set to `NAT` on your virtual machine. At this stage we don't need to know about NAT and I plan to have a whole session talking about it in the Networking session. Know that it is the easy button when it comes to getting a machine on your home network, it is also the default networking mode on Virtual Box. You can find out more in the [Virtual Box documentation](https://www.virtualbox.org/manual/ch06.html#network_nat)
Otra cosa que hay que añadir aquí es que la red estará configurada como `NAT` en la máquina virtual. En esta etapa no necesitamos saber sobre NAT ya que tendremos una sesión completa hablando sobre ello en la sesión de Redes. Sepa que es el botón fácil cuando se trata de conseguir una máquina en su red doméstica, también es el modo de red por defecto en Virtual Box. Puedes encontrar más información en la [documentación de Virtual Box](https://www.virtualbox.org/manual/ch06.html#network_nat).
Once `vagrant up` is complete we can now use `vagrant ssh` to jump straight into the terminal of our new VM.
Una vez que `vagrant up` se ha completado podemos usar `vagrant ssh` para saltar directamente a la terminal de nuestra nueva VM.
![](Images/Day14_Linux3.png)
This is where we will do most of our exploring over the next few days but I also want to dive into some customizations for your developer workstation that I have done and it makes your life much simpler when running this as your daily driver, and of course, are you really in DevOps unless you have a cool nonstandard terminal?
Aquí es donde vamos a hacer la mayor parte de nuestra exploración en los próximos días, pero también nos sumergiremos en algunas personalizaciones para su estación de trabajo de desarrollador y que harán su vida mucho más simple cuando ejecuta esto a diario, y por supuesto, ¿estás realmente en DevOps solamente cuando tengas el buen terminal fresco?
But just to confirm in Virtual Box you should see the login prompt when you select your VM.
Para confirmar en Virtual Box, deberías ver el prompt de login cuando seleccionas tu VM.
![](Images/Day14_Linux4.png)
Oh and if you made it this far and you have been asking "WHAT IS THE USERNAME & PASSWORD?"
Ah y si has llegado hasta aquí y te has preguntado **¿QUÉ NOMBRE DE USUARIO Y CONTRASEÑA?** 🤔
- Username = vagrant
- Password = vagrant
Tomorrow we are going to get into some of the commands and what they do, The terminal is going to be the place to make everything happen.
Mañana veremos algunos comandos y lo que hacen. La terminal va a ser el lugar para hacer que todo suceda y acabará siendo tu amiga.
## 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/)
There are going to be lots of resources I find as we go through and much like the Go resources I am generally going to be keeping them to FREE content so we can all partake and learn here.
Habrá muchos recursos que encontrarás a medida que vayamos avanzando y, al igual que los recursos de Go, generalmente mantendré los que tengan contenido GRATUITO.
As I mentioned next up we will take a look at the commands we might be using on a daily whilst in our Linux environments.
See you on [Day15](day15.md)
Nos vemos en el [día 15](day15.md)

View File

@ -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:
![](Images/Day15_Linux1.png)
## 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`.
![](Images/Day15_Linux2.png)
![](Images/Day15_Linux3.png)
`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.
![](Images/Day15_Linux4.png)
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`.
![](Images/Day15_Linux5.png)
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.
![](Images/Day15_Linux6.png)
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`
![](Images/Day15_Linux7.png)
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 ..`
![](Images/Day15_Linux8.png)
`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)
![](Images/Day15_Linux9.png)
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.
![](Images/Day15_Linux10.png)
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.
![](Images/Day15_Linux11.png)
`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.
![](Images/Day15_Linux12.png)
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`
![](Images/Day15_Linux13.png)
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.
![](Images/Day15_Linux14.png)
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.
![](Images/Day15_Linux15.png)
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....!
![](Images/Day15_Linux16.png)
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`
![](Images/Day15_Linux17.png)
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`
![](Images/Day15_Linux18.png)
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.
![](Images/Day15_Linux19.png)
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"`.
![](Images/Day15_Linux20.png)
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
![](Images/Day15_Linux21.png)
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`.
![](Images/Day15_Linux22.png)
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`
![](Images/Day15_Linux23.png)
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.
![](Images/Day15_Linux24.png)
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.
![](Images/Day15_Linux25.png)
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.
![](Images/Day15_Linux26.png)
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`.
![](Images/Day15_Linux27.png)
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.
![](Images/Day15_Linux28.png)
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.
![](Images/Day15_Linux29.png)
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`
![](Images/Day15_Linux30.png)
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.
![](Images/Day15_Linux31.png)
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.

View File

@ -61,7 +61,7 @@ Empecemos con lo que vas a poder ver en estos 90 días.
### Conociendo lo básico de Linux
- [✔️] 🐧 14 > [El panorama: DevOps & Linux](Days/day14.md)
- [✔️] 🐧 15 > [Comandos Linux para DevOps (En realidad todos)](Days/day15.md)
- [✔️] 🐧 15 > [Comandos de Linux para DevOps (en realidad son todos)](Days/day15.md)
- [✔️] 🐧 16 > [Gestión de tu sistema Linux, sistema de archivos y almacenamiento](Days/day16.md)
- [✔️] 🐧 17 > [Editores de texto - nano vs vim](Days/day17.md)
- [✔️] 🐧 18 > [SSH & Web Server(LAMP)](Days/day18.md)