Linux

From Sinfronteras
Revision as of 15:06, 22 February 2020 by Adelo Vieira (talk | contribs) (Mounting windows partition)
Jump to: navigation, search

Contents



1 Instalación


1.1 Creating a bootable USB flash drive


1.1.1 Creating a bootable Linux USB flash drive desde el terminal usando dd

Siguiendo el siguiente procedimiento, creé uno de Ubuntu 15, 18.04, CentOs 7, Red Hat 7.5, desde Ubuntu 15 y todos funcionaron correctamente.

  • Antes de crear el bootable drive es apropiado formatear el dispositivo en Fat32 (vFat).
  • Debemos desmontar el dispositivos antes de ejecutar el comando dd:

umount /dev/sdb*

  • Creación del bootable USB flash a través de dd:
dd if=CentOS-6.5-x86_64-bin-DVD1.iso of=/dev/sdb
Nota_sdb

Make sure you select as destination the device corresponding to the USB key (/dev/sdb in the above example) and not a partition (such as /dev/sdb1). Esta advertencia creo que depende de en que dev se encuentre montado el usb drive. Generalmente mis USB drives se montaban en /dev/sdb1. En este caso creo que se tendría que poner sdb1 en el comando (no estoy seguro). Sin embargo luego de la última vez que formateé mi USB drive, éste se monta en en /dev/sdb (sin ningún número). En este caso por supuesto habría que colocar sdb en el comando dd como se suguiere arriba. Algo parecido se presenta al formatear el USB drive.

Con este método el bootable CentOS se creó correctamente. En el USB drive se crearon dos particiones:

sdb    iso9660 CentOS 7 x86_64 2015-12-09-23-03-16-00
├─sdb1 iso9660 CentOS 7 x86_64 2015-12-09-23-03-16-00
└─sdb2 vfat    ANACONDA        C522-73DA

1.1.2 How can I create a Windows bootable USB stick with Ubuntu:

https://www.cyberciti.biz/faq/create-a-bootable-windows-10-usb-in-linux/

1.1.2.1 WoeUSB

https://www.cyberciti.biz/faq/create-a-bootable-windows-10-usb-in-linux/

En la página anterior se describen varios métodos. A través del primer método descrito en dicho link (WoeUSB) creé un bootable-windows-10-usb correctamente en Ubuntu 18.04. A continuación se describe el método.

1.1.2.1.1 Installing WoeUSB

Clone WoeUSB:

git clone https://github.com/slacka/WoeUSB.git

Set the application version string:

cd WoeUSB/
./setup-development-environment.bash

Install WoeUSB’s build dependencies on a Debian or Ubuntu Linux:

sudo apt-get install devscripts equivs gdebi-core
mk-build-deps
sudo gdebi woeusb-build-deps_*.deb
dpkg-buildpackage -uc -b
sudo gdebi ../woeusb*.deb
1.1.2.1.2 Make a Bootable Windows 10 USB from Linux
sudo woeusb --device win_10.iso /dev/sdc

Not a fan of the CLI? Try gui version:

woeusbgui
1.1.2.2 winusb

http://sourcedigit.com/20589-how-to-install-winusb-on-ubuntu-16-04/

http://askubuntu.com/questions/289559/how-can-i-create-a-windows-bootable-usb-stick-with-ubuntu

Esto lo había realizado con éxito a través del comando winusb en Ubuntu 14; instalándolo a partir de los repositorios:

sudo add-apt-repository ppa:colingille/freshlight
sudo apt-get update
sudo apt-get install winusb

Sin embargo, en Ubuntu 16, no pude instalar winusb de dicha manera.

En este post se indica cómo instalarlo manualmente: http://sourcedigit.com/20589-how-to-install-winusb-on-ubuntu-16-04/

Install WinUSB in Ubuntu 16.04

Although WinUSB hasn’t been updated for Ubuntu 16.04 Systems, users can install WinUSB on Ubuntu 16.04 by compiling the WinUSB source code.

Before you begin to install WinUSB, run the command given below to install the dependencies:

sudo apt-get install gcc build-essential libwxbase3.0-dev libwxgtk3.0-dev

Once the dependencies are installed, run the command below to download the WinUSB package and extract it accordingly:

wget ftp://ftp.ru.debian.org/gentoo-distfiles/distfiles/winusb-1.0.11.tar.gz
tar zxf winusb-1.0.11.tar.gz
cd winusb*/src
sed -i -- 's#wxStandardPaths().GetInstallPrefix()#wxStandardPaths::Get().GetInstallPrefix()#g' findFile.cpp
sed -i -- 's#wxStandardPaths().GetDataDir()#wxStandardPaths::Get().GetDataDir()#g' findFile.cpp

Now it’s time to compile winusb-1.0.11 bu running the commands given below:

cd ..
./configure
make
sudo make install
cd ..
rm -rf winusb-1.0.11

Luego de realizar la instalación manual como se indica arriba, tampoco fui capaz de crear el Windows USB bootable debido a que se producían ciertos errores cuando intentaba hacerlo. Luego de varios intentos lo logré. Sin embargo no estoy seguro de cual fue la solución. Creo que a la hora de seleccionar el dispositivo donde será creado el USB bootable, tenemos que utilizar la opciones del programa que nos permiten seleccionar (haciendo clic) el dispositivo exacto en donde lo queremos crear (/dev/sdb1, por ejemplo); y no seleccionar el dispositivo propuesto a penas abrimos el programa (generalmente /dev/sdb, sin el número de partición).

Lo otro importante es que el dispositivo USB debe ser formateado en NTFS.

Sólo a través de este programa (winusb) he logrado crear con éxito un Windows USB bootable.

1.1.2.3 A través de dd

Lo intenté hacer desde la línea de comando a través del comando dd y no resultó.

1.2 Proceso de instalación

1.2.1 Algunos notas sobre el instalador de Ubuntu

  • En el proceso de instalación de Ubuntu se propone de una vez la instalación de «Third-party sortwares» (algunos de estos son propietarios). Así, el sistema fue capaz de habilitar directamente el WiFi en mi computadora.
Ubuntu third party sortwares.png
  • Cuando elegimos la partición en donde será instalado Ubuntu y tenemos, por supuesto, que asignarle un «Mount point», el instalador no da la opción de asignar el «Moint point» hasta que seleccionemos «Format the partition» e indiquemos, por supuesto, el «File System». Por tamto, así le hayamos dado un formato a la partición antes de iniciar el intalador de Ubuntu (a través de Gparted), tendremos que realizar el formateo de la partición en cuestión durante el proceso de instalación.
  • Si hemos creado la partición swap previamente con Gparted, el instalador no marca la selección de la partición swap (ver las imágenes abajo). Lo que quiero decir es que el instalador no es claro (al momento de la selección de las particiones) en indicar que hemos seleccionado una partición swap para la instalación. Sin embargo, luego de hacer click en «Install Now», una ventana de warning se abre e indica las particiones que hemos elegido para la instalación del SO. Ahí sí podemos corroborar con claridad las particiones que han sido configuradas para la instalación de Ubuntu.
Formatear la particion durante instalacion.jpg
Seleccion de la particion swap en Ubuntu1.jpg
Seleccion de la particion swap en Ubuntu2.jpg

1.2.2 Creating and selecting the partition where the SO will be installed

Notes about the last installation:

Tradicionalmente, los disco duros permiten un máximo de cuatro (4) particiones primarias (o 3 más una extendida). Sólo puede haber una (1) Extendida y dentro de ésta última pueden haber un máximo de 23 particiones lógicas (https://es.wikipedia.org/wiki/Partici%C3%B3n_de_disco). However, the last time I configured partitions, I did it for a GPT disc. In this kind of discs, no extended or logic partition can be created. You can created as many primary partitions as you want (well! I'm not sure what is the maximum): https://askubuntu.com/questions/927927/why-cant-i-create-an-extended-partition

The other important detail about the last installation was that when I first try to reduce space in the Default "C:" Windows partition using Gparted, I was NOT allowed to do it. The solution that I found was to do it from Windows in a very easy way even with the partition mounted was possible to do it as it is explained here: https://support.lenovo.com/ie/en/solutions/ht505250 . After reducing space that way, I was able to normally manage the partitions using Gparted.


Ver nota sobre el Tamaño de la partición.


La parte más delicada es cuando debemos crear (si no existe ya) y seleccionar la partición en la que se instalará el SO.


Para el particionamiento se pueden usar las opciones propuestas por el instalador o podemos también hacer el particionamiento antes de iniciar el instalador a través del programa GParted

GParted se puede utilizar desde Ubuntu Live (Running Ubuntu directly from either a USB stick or a DVD). Recomiendo hacerlo de esta forma para esquemas de particiones complejos

Si se hace a través del instalador, la única confución que se presetan es que este programa no detalla el tipo de partición «Extendida». De hecho, cuando se va a crear una partición, el programa sólo propone como tipos de particiones: «Primaria» o «Lógica». Sin embargo, no es coherente crear una partición lógica antes que una Extendida. Es por ello que cuando creamos la primera partición Lógica el programa automáticamente crea la partición extendida donde, por supuesto, se encontrará la partición Lógica que estamos creando. De ahí en adelante toda partición Lógica que creemos se incluirá dentro de dicha partición Extendida (puesto que sólo puede haber una partición Extendida en el disco). Además, si por equivocación ejecutamos la creacion de una quinta partición Primaria, el programa no dará ningún error y creará la partición sin ningún problema, sólo que ésta no será Primaria sino que el programa aútomáticamente la creará de tipo Lógica.

GParted es un poco mejor puesto que es un programa hecho exclusivamente para particionamiento. Este programa si detalla adecuadamente el tipo de partición Extendida.

Para instalar Linux tenemos que crear por lo menos dos particiones (Indispensables):

La partición Swap : Puede ser Primaria o Lógica -- Se puede crear en cualquier posición -- Filesystem: Swap -- Tamaño -- Utilidad.
La particion root / : Primaria o Lógica -- Cualquier posición -- Filesystem: Ext4 (EXT2 pour une installation sur clef USB) -- Tamaño: Minimum 8Go. Pour une question de confort au moins 15Go. 


En muchos forums se propone también la creación de las siguientes particiones (Opcionales):

/boot : Ésta podría ser indispensable -- Creo que debe ser primaria -- Se debe crear al inicio del disco -- Filesystem: Linux (généralement EXT4) -- Tamaño: 250Mo~1Go -- Utilidad -- Punto de montaje: /boot https://doc.ubuntu-fr.org/tutoriel/partitionner_manuellement_avec_installateur_ubuntu
/home : Primaria o Lógica -- Cualquier posición -- Filesystem: Ext4 (EXT2 pour une installation sur clef USB) (Remarque: d'autres systèmes de fichiers sont disponibles) -- Tamaño: Selon votre usage -- Utilidad -- Punto de montaje: /home https://doc.ubuntu-fr.org/tutoriel/partitionner_manuellement_avec_installateur_ubuntu

También he visto que podría ser ventajoso crear particiones para:

/tmp 
/var
/usr

Sin embargo, después de consultar distintas páginas llegué a la conclusión de que no es ventajosa la creación de las particiones opcionales sino en casos particulares.

En la siguiente página se exponen las útilidades (pro y contras) de algunas de las particiones opcionales https://doc.ubuntu-fr.org/tutoriel/partitionner_manuellement_avec_installateur_ubuntu

1.2.3 La partición swap

What is swap?

Swap space is the area on a hard disk which is part of the Virtual Memory of your machine, which is a combination of accessible physical memory (RAM) and the swap space. Swap space is used when your system decides that it needs physical memory for active processes and there is insufficient unused physical memory available. https://help.ubuntu.com/community/SwapFaq

1.2.3.1 Utilidad

Utilité : L'espace d'échange (en anglais, swap space) est une extension de la mémoire vive (RAM) de votre ordinateur. Afin d'éviter un blocage de votre ordinateur lorsque sa RAM est pleine, Ubuntu se sert de cette partition pour décharger temporairement la RAM. Son utilisation à cet effet est plutôt rare dans les ordinateurs modernes, disposant d'au moins 1 Go de RAM. Cependant, elle sert aussi de décharge de la RAM lors de la mise en hibernation, c'est pour cette raison que la taille de la partition swap doit être d'au moins la taille de votre RAM si vous souhaitez utiliser cette fonction. https://doc.ubuntu-fr.org/tutoriel/partitionner_manuellement_avec_installateur_ubuntu

1.2.3.2 Que tamaño debe tener la partición swap

How much swap do I need?

For less then 1GB of physical memory (RAM), it's highly recommended that the swap space should, as a base minimum, be equal to the amount of RAM. Also, it's recommended that the swap space is maximum twice the amount of RAM

For more modern systems (>1GB), your swap space should be at a minimum minimum be equal to your physical memory (RAM) size "if you use hibernation", otherwise you need a minimum of round(sqrt(RAM)) and a maximum of twice the amount of RAM. https://help.ubuntu.com/community/SwapFaq

I have 16GB RAM. Do I need 32GB swap?

It entirely depends on what you plan to do with the machine. For example if it were a Sap server then yes, I would add 32gb swap (we have boxes at work with 128gb ram and 32gb swap). If you were manipulating massive pictures and video then it makes sense to have a little swap. 32gb is probably overkill. http://askubuntu.com/questions/49109/i-have-16gb-ram-do-i-need-32gb-swap

Here's a very good recommendation from RedHat:

In years past, the recommended amount of swap space increased linearly with the amount of RAM in the system. But because the amount of memory in modern systems has increased into the hundreds of gigabytes, it is now recognized that the amount of swap space that a system needs is a function of the memory workload running on that system. However, given that swap space is usually designated at install time, and that it can be difficult to determine beforehand the memory workload of a system, we recommend determining system swap using the following table. https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Installation_Guide/s2-diskpartrecommend-ppc.html#id4394007

Amount of RAM in the system   Recommended swap space         Recommended swap space 
                                                             if allowing for hibernation
---------------------------   ----------------------------   ---------------------------
2GB of RAM or less            2 times the amount of RAM      3 times the amount of RAM
2GB to 8GB of RAM             Equal to the amount of RAM     2 times the amount of RAM
8GB to 64GB of RAM            0.5 times the amount of RAM    1.5 times the amount of RAM
64GB of RAM or more           At least 4 GB                  No extra space needed
1.2.3.3 Donde colocar la partición Swap

Estuve leyendo y al parecer no importa donde la colocamos en el disco duro: al principio, en el medio o al final. It doesn’t matter where on the hard drive the swap partition is located (beginning, middle or the end).

1.2.3.4 Utilizar la misma partición Swap para distintas instalaciones de Linux

https://forum.ubuntu-fr.org/viewtopic.php?id=762271

Por ejemplo, si en mi computadora instalo Ubuntu y Red Hat... puedo emplear la misma partición Swap para ambos sistemas?

Si tu n'utilises pas la fonction d'hibernation, tu peux utiliser la même swap pour les deux. Il peut y avoir souci si la 2ème install formate la partition swap, changeant ainsi son UUID (la 1ère distrib ne la trouvera donc plus). Ça se règle en corrigeant le UUID dans le fichier /etc/fstab de la 1ère distrib

Et oui, tu peux partager la même partition swap, puisque elle n'est censée contenir quelque chose qu'entre le démarrage et l'extinction, et être vide à l'arrêt du PC (sauf si tu utilises l'hibernation, qui met le contenu de la RAM dans la swap pour le prochain démarrage)

Pour savoir si la swap est utilisée par les 2, ouvre le fichier /etc/fstab des deux distribs, elles doivent comporter la même ligne concernant swap.

Un doute subsiste quand à la partition "swap", comment être certain que cette dernière est utilisée pas Fedora et Ubuntu ?

Pour savoir si la swap est utilisée par les 2, ouvre le fichier /etc/fstab des deux distribs, elles doivent comporter la même ligne concernant swap.

1.2.4 Utilidad de la partición boot

Certains ordinateurs n'arrivent pas à lire les fichiers de démarrage s'ils sont situés trop loin (>100Go) du début du disque. Dans ce cas, il est généralement nécessaire de créer une partition /boot en début de disque5). Mais cette partition /boot séparée n'est généralement pas utile sur un ordi récent (achat après 2007) et elle peut même générer des problèmes, aussi il vaut mieux ne créer cette partition /boot que sur avis des experts du forum en cas où elle est réellement indispensable. https://doc.ubuntu-fr.org/tutoriel/partitionner_manuellement_avec_installateur_ubuntu

1.2.5 Utilidad de la partición home

Lorsque vous disposez d'un disque dur suffisamment grand, un dossier home séparé permet d'isoler les paramètres personnels et les dossiers personnels des utilisateurs du reste du système. Par défaut, ce dossier fait partie de la partition racine. Un /home séparé est généralement superflu, voire gênant (notamment sur de petits disques) si vous débutez avec Ubuntu. Consulter ce comparatif pour savoir si un home séparé peut vous être utile. Important: un /home séparé ne sert pas à partager des données avec Windows ou MacOS (voir le paragraphe précédent). https://doc.ubuntu-fr.org/tutoriel/partitionner_manuellement_avec_installateur_ubuntu

Es infinitamente más cómodo tener el /home en una partición separada a la hora de actualizar la versión de ubunto desde un disco o pendrive y ante emergencias que requieran una reinstalación del sistema. Si todo está en la partición “/” antes de reinstalar o actualizar hay que hacer una backup de la carpeta /home donde están nuestros ficheros y preferencias. Ahora bien, si /home está en una partición no será necesario realizar un respaldo. Durante el proceso de instalación debemos marcar la partición / para formateo y /home sin formateo. Despúes se crean los mismos usuarios con el mismo nombre y ya tenemos todos los datos. Es así por experiencia mucho más sencillo y rápido.

http://elblogdeliher.com/mi-recomendacion-para-hacer-las-particiones-para-instalar-ubuntu/

1.2.6 Partición para los datos

Es apropiado crear una partición para todos los datos. Esto resulta de especial interés al momento de formatear y reinstalar los sistemas operativos. De esta manera no es necesario realizar un respaldo de los datos pues esta partición no se tocaría al momento de formatear y reinstalar los SO.

Ahora bien, si queremos compartir los datos entre Linux y Windows, la partición de almacenamiento debe entonces tener formato NTFS. Lo anterior porque bien sabemos que Linux es compatible con este sistema de archivos. Windows, por el contrario, no podría acceder a un sistema de archivos Linux como EXT4.

1.2.7 Ahora, ¿Es apropiado tener todos los datos que usaré en Linux en una partición NTFS?

1.2.7.1 Chmod and chown en particiones ntfs
1.2.7.2 Error producido cuando ingreso a una partición desde Windows y luego trato de montarla en Ubuntu

https://itsfoss.com/solve-ntfs-mount-problem-ubuntu-windows-8-dual-boot/

http://askubuntu.com/questions/748163/unable-to-mount-ntfs-partition-no-hibernation

Cuando inicio el SO se produce un error que interrumpe el booting. El error es producido porque Ubuntu no puede montar la partición NTFS a la cual he accedido en Windows.

Si inicio Ubuntu en modo Upstart, el SO inicia sin montar dicha partición.

Luego si intento montar la partición, se produce el siguiente error:

adelo@adelo-laptop:~$ sudo mount /dev/sda2 1-disco_local/
[sudo] password for adelo: 
The disk contains an unclean file system (0, 0).
Metadata kept in Windows cache, refused to mount.
Failed to mount '/dev/sda2': Operation not permitted
The NTFS partition is in an unsafe state. Please resume and shutdown
Windows fully (no hibernation or fast restarting), or mount the volume
read-only with the 'ro' mount option.

El error es debido a que Microsoft introduced a new feature in Windows 8 and 10 to reduce the boot time in otherwise slow Windows OS. This feature is called Fast Startup

In normal shut down process, power is removed from all components such as CPU, RAM, CD-Rom and hard disks. But in fast start up, Windows 8 saves some system information such as caching the registry etc to a file during shutdown. Part of the metadata about the state of all mounted partitions at the time of turn-off, is among these system information. This reduces the boot time of the Windows 8 but it creates the trouble for Ubuntu.

Since the information about the NTFS partition is stored in Windows 8, this prevents Ubuntu to mount them as mounting them in Linux will alter the metadata of the partitions. This is why it is in protected mode and you cannot mount it (without being root). https://itsfoss.com/solve-ntfs-mount-problem-ubuntu-windows-8-dual-boot/


El problema se puede resuelver haciendo: http://askubuntu.com/questions/748163/unable-to-mount-ntfs-partition-no-hibernation

sudo ntfsfix /dev/sda2

Sin embargo, habría que ejecutar dicho comando cada vez que queramos iniciar Ubuntu.


Permanent Solution: Disable Fast Startup in Windows 8 and Windows 10.

Use the following path to disable fast startup:

Go to Control Panel > Hardware and Sound > Power Options > System Setting > Choose what the power buttons do and uncheck the Turn on fast startup box. https://itsfoss.com/solve-ntfs-mount-problem-ubuntu-windows-8-dual-boot/


El error descrito arriba se generó en Ubuntu 15. Ubuntu 18.04 no presentó dicho problema. Sin embargo, sí noté que luego de ingrasar a las particiones (1-disco_local, etc) desde Windows, al apagar la computadora, Windows tomaba mucho tiempo en apagar el sistema. Luego de varias pruebas pude corroborar que esto se producía sólo cuando se ingresaba a las particiones. Este problema está relacionado con el error descrito arriba y fue solucionado de la misma forma: «Disable Fast Startup».

1.2.7.3 Can't be put in the trash. Do you want to delete it immediately?

Este problema se solucionó sólo. Me imagino que luego de alguna actualización del sistema.

Luego de realizar algunos cambios en el particionamiento para instalar otros sistemas Linux (RedHat, CentOS) surgió el siguiente error: Cuando quería borrar un archivo directamente desde el escritorio (con la tecla delete) (Gnome - Nautilus) el archivo no podía ser enviado a la papelara. Se desplegaba entonces el mensaje referido arriba en el título de esta sección.

El problema que estoy teniendo es exáctamente el descrito en este Forum:

Impossible to trash files from a folder which is a symbolic link to a NTFS partition folder

http://askubuntu.com/questions/616092/impossible-to-trash-files-from-a-folder-which-is-a-symbolic-link-to-a-ntfs-parti

Since a few days, I cannot send files to trash anymore from some folders.

That worked perfectly for years :(

In my home folder, I have several symbolic links to folders on the NTFS partitions, like this one:

Desktop -> 1-disco_local/1-mis_archivos/.stockage/desktop-dis/

Si intento borrar desde: ~/Desktop, el archivo no puede ser enviado a la papelera, but in the original folder 1-disco_local/1-mis_archivos/.stockage/downloads-dis/, funciona perfecto.


Este problema es también tratado en este Forum, en donde al parecer se ha encontrado una solución para Ubuntu 16.~

https://bugs.launchpad.net/ubuntu/+source/glib2.0/+bug/1495781

https://bugs.launchpad.net/ubuntu/+source/nautilus/+bug/1449112

1.2.8 Esquema de particionamiento

Después de investigar y reflexionar llegué a la conclusión de que, en mi caso, lo mejor es crear sólo las particiones linux indispensables.

Mi disco es supuestamente de 320G. Sin embargo, al sumar los tamaños de las distintas particiones, da un total de Aprox. 300G (298,08G). Al parecer esta diferencia tiene que ver con que el tamaño de la partición depende del FileSystem. Ver nota sobre el Tamaño de la partición.

  • Me ha parecido apropiado instalar todos mis Sistemas Linux dentro de la partición Extendida y los otros SO (Windows) en particiones Primarias.
  • Todos los datos serán guardados en una partición destinada únicamente a este fin, aparte de todos los sistemas operativos intalados.
    • Esto es particularmente ventajoso a la hora de formatear un SO, pues no será necesario realizar un respaldo de los datos.
    • Como la partición de datos es ntfs, podemos entonces acceder a ella desde Linux y Windows.
    • Esta partición la he colocado al inicio del disco. Así, resulta más fácil redimencionarla porque la redimención nunca será al inicio del la partición. Aunque al parecer podemos también redimensionar al inicio de la partición, según algunas fuentes que he leído es menos seguro y toma más tiempo. La otra ventaja de colocarla al inicio del disco es que a la hora de cambiar el esquema de las particiones en donde se encuentran los SO no tendremos que tocar (formatear) la partición de datos. La única operación que podría ser necesario sería la redimención al final de la partición.


Mis particiones.png

2 Mis configuraciones

2.1 Directorios

Directorios.png
mkdir -p 1-system/{1-disco_local,2-disco_ext,3-cloud,4-windows,.1-conf-system/1-archivos_programas-ubuntu}

2.2 user-dirs.dirs: Cambiar la ruta de Desktop y Download

Cambiar la ruta de Desktop y Download y eliminar los directorios innecesarios from the Nautilus sidebar.

https://askubuntu.com/questions/79150/how-to-remove-bookmarks-from-the-nautilus-sidebar

/home/adelo/.config/user-dirs.dirs
  • Editamos el archivo de estamanera:
# Si se quiere cambiar la imagen del icono de algun directorio, en este directorios se encuentran las imagenes de los icones
# usados por el sistema
# /usr/share/icons/Humanity/places/128/user-desktop.svg
# /usr/share/icons/Humanity/places/64/folder-download.svg

XDG_DESKTOP_DIR="$HOME/1-system/desktop"
XDG_DOWNLOAD_DIR="$HOME/1-system/desktop/downloads"

# XDG_TEMPLATES_DIR="$HOME/Templates"
# XDG_PUBLICSHARE_DIR="$HOME/Public"
# XDG_DOCUMENTS_DIR="$HOME/Documents"
# XDG_MUSIC_DIR="$HOME/Music"
# XDG_PICTURES_DIR="$HOME/Pictures"
# XDG_VIDEOS_DIR="$HOME/Videos"


  • After login the file ~/.config/user-dirs.dirs gets reverted to the original set by /etc/xdg/user-dirs.defaults. To prevent that make the file "read-only" and set the option «enabled» to «False» in /etc/xdg/user-dirs.conf
chmod -w ~/.config/user-dirs.dirs
gedit /etc/xdg/user-dirs.conf  :  '''enabled=false'''


  • Luego podemos eliminar los directorios innecesarios from the Nautilus sidebar haciendo click derecho en el diretorio (en el Nautilus sidebar) > Remove.


  • Luego creé los siguientes soft links:
ln -s /home/adelo/1-system/1-disco_local/1-mis_archivos/.stockage/desktop-dis/    /home/adelo/1-system/desktop
ln -s /home/adelo/1-system/1-disco_local/1-mis_archivos/.stockage/downloads-dis/  /home/adelo/1-system/desktop/downloads


  • Luego cabié las imágenes de los íconos:
/usr/share/icons/Humanity/places/128/user-desktop.svg
/usr/share/icons/Humanity/places/64/folder-download.svg

2.3 Shortcut to hide the desktop icons in GNOME 3

https://askubuntu.com/questions/1072337/shortcut-to-hide-the-desktop-icons-in-gnome-3

La aplicación «gnome-tweaks» permite realizar algunas configuraciones en «Gnome». Entra ellas, la posibilidad de ocultar los ícones del escritorio.

sudo apt-get install gnome-tweaks

Así, usando el GUI de «gnome-tweaks», configuramos el desktop de forma tal que no mostrara los icons por defecto.

Ahora, el siguiente Script (el cual emplea gnome-tweaks) permite ocultar y mostrar los ícones del Desktop:

/home/adelo/1-system/.1-conf-system/hide_icons_on_desktop.sh
#!/bin/sh


# https://askubuntu.com/questions/1072337/shortcut-to-hide-the-desktop-icons-in-gnome-3

# La siguiente l'inea la tuve que adicionar porque el script no estaba funcionando. Esta soluci'on la encontr'e aqu'i:
# https://stackoverflow.com/questions/44934641/glib-gio-message-using-the-memory-gsettings-backend-your-settings-will-not-b
export GIO_EXTRA_MODULES=/usr/lib/x86_64-linux-gnu/gio/modules/

if $(gsettings get org.gnome.desktop.background show-desktop-icons);
then new="false";
else new="true";
fi
gsettings set org.gnome.desktop.background show-desktop-icons $new

gsettings set org.gnome.shell.extensions.dash-to-dock show-running $new
gsettings set org.gnome.shell.extensions.dash-to-dock show-favorites $new
gsettings set org.gnome.shell.extensions.dash-to-dock show-show-apps-button $new

Luego adicionamos el Script al «keyboardsettings» an entry:

Settings > Devices > Keyboard

https://linuxconfig.org/how-to-automatically-execute-shell-script-at-startup-boot-on-systemd-linux

https://askubuntu.com/questions/919054/how-do-i-run-a-single-command-at-startup-using-systemd

https://opensource.com/life/16/11/running-commands-shutdown-linux

https://unix.stackexchange.com/questions/48973/execute-a-command-before-shutdown



2.3.1 Shortcut to hide the dock

De forma similar a como se hizo con los desktop icons. Utilizando el siguiente script. Le dimos el shortcut Ctrl+Alt+B

#!/bin/sh


# https://askubuntu.com/questions/1072337/shortcut-to-hide-the-desktop-icons-in-gnome-3

# La siguiente l'inea la tuve que adicionar porque el script no estaba funcionando. Esta soluci'on la encontr'e aqu'i:
# https://stackoverflow.com/questions/44934641/glib-gio-message-using-the-memory-gsettings-backend-your-settings-will-not-b
export GIO_EXTRA_MODULES=/usr/lib/x86_64-linux-gnu/gio/modules/

if $(gsettings get org.gnome.shell.extensions.dash-to-dock show-running);
then new="false";
else new="true";
fi

gsettings set org.gnome.shell.extensions.dash-to-dock show-running $new
gsettings set org.gnome.shell.extensions.dash-to-dock show-favorites $new
gsettings set org.gnome.shell.extensions.dash-to-dock show-show-apps-button $new



2.4 Algunos links

2.4.1 Link hacia webdevelopment codes

ln -s /home/adelo/1-system/1-disco_local/1-mis_archivos/1-pe/1-ciencia/1-computacion/1-programacion/1-webdevelopment/1-semestre3-php/1-webdevelopment-codes/   /var/www/html/webdevelopment_codes

2.4.2 Links en el escritorio

ln -s /home/adelo/1-system/1-disco_local/1-mis_archivos/1-pe/1-ciencia/1-computacion/1-programacion/2-python/   /home/adelo/1-system/desktop/python

ln -s /home/adelo/1-system/1-disco_local/1-mis_archivos/1-pe/1-ciencia/1-computacion/1-programacion/3-java/   /home/adelo/1-system/desktop/java

ln -s /home/adelo/1-system/1-disco_local/1-mis_archivos/1-pe/1-ciencia/1-computacion/1-programacion/1-webdevelopment/   /home/adelo/1-system/desktop/webdevelopment

ln -s /home/adelo/1-system/1-disco_local/1-mis_archivos/1-pe/1-ciencia/1-computacion/3-linux   /home/adelo/1-system/desktop/linux

ln -s /home/adelo/1-system/1-disco_local/1-mis_archivos/1-pe/1-ciencia/1-computacion/2-system_analysis_and_design   /home/adelo/1-system/desktop/system_analysis

ln -s /home/adelo/1-system/1-disco_local/1-mis_archivos/2-carrera/2-trabajo/   /home/adelo/1-system/desktop/trabajo

2.5 Permisologia de archivos y directorios

2.5.1 Ajustar la permisologia de todos los archivos y directorios

No es para nada apropiado, reajustar la permisología de los directorios/archivos de programas. Esto podría generar problemas en la ejecución de archivos. Por tanto; si queremos reajustar la permisología de archivos, sólo se podría hacer en nuestros archivos personales. NUNCA EN ARCHIVOS DE PROGRAMAS.

Ver:

Linux#Ajustar permisologia recursivamente en traitant de facon differentiee les repertoires et les fichiers

Linux#A través del comando find

permisologia.sh
#! /bin/bash

# Para los directorios:
find 1-system -type d -exec chmod 755 {} +

# Para los archivos:
find 1-system -type f -exec chmod 644 {} +

2.5.2 Ajustar la permisologia por defecto al crear un archivo o directorio

También es muy importante resaltar que no se debemos reajustar la permisología por defecto de nuevos archivos/directorios creados por la misma razón explicada arriba. Cuando los programas se instalan, crean directoris y archivos que serán entonces creados con la permisología que hayamos ajustado. Esto no es para nada apropiado. Hacer esto me trajo problemas con el programa LibreOffice por ejemmplo. Dicho programa no abría cuando se ejecutaba en la sesión de ususario porque una de las carpetas de configuraciones en /usr/lib/libreoffice/.... se había creado con permisos que impedían que un usuario accediera a ella y por tanto el probrama no funcionaba. Espero que este error no me traiga más problemas con los programas que instalé luego de modificar la permisología por defecto de nuevos directorios/archivos creados.

Ver Linux#Permisología por defecto

Añadir la siguiente línea a .bashrc

umask u=rwx,g=rx,o=rx

Debido a que la mayoría de los sistemas Unix no permiten que nuevos archivos (directorios sí) sean creados con permisos de ejecución activados, independientemente de la máscara; con la «umask» anterior los directorios y archivos serán creados con permisología:

drwxr-xr-x  (755)
-rw-r--r--  (644)

2.6 fstab: Montar discos automáticamete

/etc/fstab
#===========================
# Cambios realizados por mi
#===========================
# Disco_local:
UUID=761657CB1CD1E939			/home/adelo/1-system/1-disco_local	ntfs	auto,users,exec,permissions	0	0

# Disco_externo - TOSHIBA EXT:
UUID=3C9A5D379A5CEF40			/home/adelo/1-system/2-disco_ext	ntfs	auto,nofail,users,permissions	0	0

Para saber el UUID de la partición:

sudo blkid

Ver Linux#Para discos externos

2.7 .bashrc (home)

/home/adelo/.bashrc
#===========================
# Cambios realizados por mi
#===========================

# Ajustar la permisología por defecto (base) de los archivos y directorios creados.
# Debido a que la mayoría de los sistemas Unix no permiten que nuevos archivos (directorios sí) sean creados con permisos de ejecución activados, independientemente de la máscara; con la siguiente «umask» los directorios y archivos serán creados con permisología:
# -rw-r--r-- (644)
# drwxr-xr-x (755)
# He llegado a la conclusión de que esto no es para nada apropiado. Ver explicación en http://perso.sinfronteras.ws/index.php/Linux#Permisologia_de_archivos_y_directorios
# umask u=rwx,g=rx,o=rx


# -X : sort alphabetically by entry extension
# -A : do not list implied . and ..
# Se puede realizar este alias para que el comando "la" ordene los archivos ocultos de último y no liste los directorios . y ..
alias la='ls -AX'


# -v : sort num'ericamente. Es necesario porque cuando se hace alphabetically el 10 es colocado primero que el 1. El problema es que la opci'on -ve no es compatible con ordenamiento alfab'etico. Si se usa esta opci'on los archivos que no comiencen por n'umeros no ser'an ordenados alfab'eticamente. -v tampoco es compatible con el alias realizado arriba (la='ls -AX'):
alias ls='ls -v --color=auto'


# He hecho el siguiente alias para crear el comando "del", ya que escribir «gio trash» cada vez que vamos a mover un archivo a la papelera resulta tedioso.
alias del="gio trash"


# He creado los comandos cdd y cdp para facilitar el acceso a 1-system y 1-pe:
function cds() {
  cd ~/1-system
}
cds

function cdp() {
  cd ~/1-system/1-disco_local/1-mis_archivos/1-pe
}


# Para cambiar el nombre desplegado en la esquina superior derecha del la gnome-ventana del terminal:
# La siguiente función is to rename terminal tab title in gnome-terminal:
# Si queremos cambiar el title in gnome-germinal ejecutamos esta funci'on en el terminal de la siguiente forma:
# # set-title my new tab title
function set-title() {
  if [[ -z "$ORIG" ]]; then
    ORIG=$PS1
  fi
  TITLE="\[\e]2;$*\a\]"
  PS1=${ORIG}${TITLE}
}


# Después de la instalación de Eclipse, para adicionar el ejecutable a la lista de comandos:
PATH=$PATH:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/eclipse/java-photon/eclipse:


# Después de la instalación de NetBeans, para adicionar el ejecutable a la lista de comandos:
PATH=$PATH:/usr/local/netbeans-8.2/bin:
# Otra forma de hacerlo es a trav'es de un soft link
# ln -s /usr/local/netbeans-8.2/bin/netbeans /usr/local/bin/netbeans8.2


# Después de la instalación de pycharm, para adicionar el ejecutable a la lista de comandos:
PATH=$PATH:/home/adelo/.local/share/umake/ide/pycharm/bin:


# Después de la instalación de Visual Paradigm, para adicionar el ejecutable a la lista de comandos:
# ln -s /home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/Visual_Paradigm_CE_15.1/bin/Visual_Paradigm /usr/local/bin/visualparadigm
# Para hacerlo de esta forma, debemos ejecutar la creación del softlink directamente sobre el terminal porque debe ejecutarse como root. Si no queremos hacerlo así, debemos adicionar el path del ejecutable a la variabla PATH como lo hemos hecho con otros programas.


# added by Anaconda3 installer (la siguiente l'inea fue adicionada autom'aticamente durante la instalaci'on de anaconda):
export PATH="/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/anaconda3/bin:$PATH"


# # # #


# # Para la instalación del Seismic Unix:
# export CWPROOT=/home/adelo/1-disco_local/1-mis_archivos/1-pe/1-ciencia/1-geofisica-procesamiento-modelado_sismico/seismic_unix/instalacion_seismic_unix
# PATH=$PATH:$CWPROOT/bin
# export PATH

Ver Mover archivos a la papelera desde el terminal para más detalles del por qué se ha realizado la siguiente configuración: alias del=gvfs-trash

2.8 .bashrc (root)

/root/.bashrc
#===========================
# Cambios realizados por mi
#===========================

# Ajustar la permisología por defecto (base) de los archivos y directorios creados: ---------- (000) d--------- (000)
# He llegado a la conclusión de que esto no es para nada apropiado. Ver explicación en http://perso.sinfronteras.ws/index.php/Linux#Permisologia_de_archivos_y_directorios
# umask u=,g=,o=


# -X : sort alphabetically by entry extension
# -A : do not list implied . and ..
# Se puede realizar este alias para que el comando "la" ordene los archivos ocultos de último y no liste los directorios . y ..
alias la='ls -AX'


# -v : sort num'ericamente. Es necesario porque cuando se hace alphabetically el 10 es colocado primero que el 1. El problema es que la opci'on -ve no es compatible con ordenamiento alfab'etico. Si se usa esta opci'on los archivos que no comiencen por n'umeros no ser'an ordenados alfab'eticamente. -v tampoco es compatible con el alias realizado arriba (la='ls -AX'):
alias ls='ls -v --color=auto'


# He hecho el siguiente alias para crear el comando "del", ya que escribir gvfs-trash cada vez que vamos a mover un archivo a la papelera resulta tedioso.
alias del="gio trash"


/etc/bash.bashrc
#===========================
# Cambios realizados por mi
#===========================

# -X : sort alphabetically by entry extension
# -A : do not list implied . and ..
# He realizado este alias para que el comando "la" ordene los archivos ocultos de último y no liste los directorios . y ..
alias 'la=ls -AX'

2.9 .profile

/home/adelo/.profile
#===========================
# Cambios realizados por mi
#===========================


# hide icons on desktop and dock
export GIO_EXTRA_MODULES=/usr/lib/x86_64-linux-gnu/gio/modules/
gsettings set org.gnome.desktop.background show-desktop-icons false
gsettings set org.gnome.shell.extensions.dash-to-dock show-running false
gsettings set org.gnome.shell.extensions.dash-to-dock show-favorites false
gsettings set org.gnome.shell.extensions.dash-to-dock show-show-apps-button false



2.10 Keyboard shortcuts modified

  • Close window: Alt + F4 --> Alt + AudioMicMute



3 Things to do after installing Ubuntu 18.04

https://itsfoss.com/things-to-do-after-installing-ubuntu-18-04/

3.1 Update

3.2 Enable additional repositories

3.3 Algunas configuraciones en Gnome and Nautilus

3.4 Instalar paquetes para xfs support

3.5 Install media codecs

Permite reproducir videos en el web browser (en facebook por ejemplo):

sudo apt install ubuntu-restricted-extras

3.6 Si se instala Windows

3.7 Instalar

  • apache2
  • nginx
  • MySQL
  • mycli
  • PostgreSQL
  • PHP
  • nodejs
  • typescript
  • Oracle JDK
  • Eclipse
  • NetBeans
  • Sublime Text
  • VirtualBox
  • PacketTracer
  • Virtual Paradigm
  • ------
  • imagemagick
Contiene «convert» which is required by MediaWiki
  • sshfs
  • gvfs-bin
  • Google Cloud SDK
  • Gparted
  • Google Chrome
  • LaTeX
    • kile
  • kate
  • gimp
  • shutter
  • pdftk
  • gnome-tweaks
  • Para el respaldo:
    • rsync (debería estar by default)
    • sshpass
    • pv
  • LVM and xfs support for Ubuntu:
    • lvm2
    • xfsprogs
    • xfsdump



4 Red Hat

Mi página de estudio para la certificación RHCSA: Study points for the RHCSA exam

He creado una cuenta for the Red Hat Developer Program (email y clave habitual) lo cual me permite descargar una versión gratis de Red Hat:

http://developers.redhat.com/

http://developers.redhat.com/products/rhel/download/

http://developers.redhat.com/products/rhel/get-started/

%%%%%%%%

Al crear la cuenta Red Hat Developer Program me han enviado el siguiente correo:

Hi Adelo,

I saw that you joined Red Hat Developers and I have the privilege of welcoming you on behalf of the Red Hat Developers team. So, welcome! We are happy to have you join us and to get you started we thought some quick highlights would be helpful:

  • Product downloads: Many of Red Hat’s solutions including JBoss EAP and Red Hat Enterprise Linux for developers are available free to you as a member and can be found here.
  • Highlighted and new content: For ease we will have that on our homepage and will be adding material multiple times a week.
  • You can contribute: We welcome content contributions from our members around the globe. Three easy ways to contribute can be found here. And did I mention contributing gets you swag?

Again, welcome to Red Hat Developers.

Andréa

%%%%%%%%

Si no se crea una cuenta en Red Hat Developer Program, se puede descargar una versión de prueba gratis de 30días de Red Hat https://access.redhat.com/products/red-hat-enterprise-linux/evaluation

Para crear el bootable usb: https://access.redhat.com/articles/142303

4.1 All certifications and exams

https://www.redhat.com/en/services/all-certifications-exams

https://en.wikipedia.org/wiki/Red_Hat_Certification_Program#Examination_required_for_each_certification

4.1.1 Red Hat Certified System Administrator (RHCSA) exam

https://www.redhat.com/en/services/training/ex200-red-hat-certified-system-administrator-rhcsa-exam

4.2 All training courses and exams

https://www.redhat.com/en/services/training/all-courses-exams

4.3 Documentación gratis

Creo que esta guía para RedHad está bastante buena: https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/

En esta página se encuentra una excelente documentación de Red Hat. Parte del contenido está basado en los putos a evaluar en los exámenes de certifiación Red Hat. Everything you need to pass your RHCSA, RHCE, LFCS, LFCE and much more: https://www.certdepot.net/

4.4 Instalación

Short guide: https://developers.redhat.com/products/rhel/hello-world/

Instalation guide: https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide/index.html

Red hat-installation summary.jpg

4.4.1 System Requirements

The requirements for your physical system are:

a 64-bit x86 machine.

4 GB of RAM

20 GB of available disk space.

For more detailed minimum hardware requirements and compatibility information, see https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide/chap-installation-planning-x86.html

4.4.2 Software selection

The Red Hat Enterprise Linux Server .iso can be used to install a system with a full graphical desktop. You will select Server with a GUI under Software Selection during installation. By default, Red Hat Enterprise Linux Server will not install a graphical desktop.

  • Click Software selection.
  • On the next screen, under Software selection, in the Base environment list on the left, select Server with GUI.
  • In the list Add-ons for selected environment on the right, select Development tools.
Configuración que elegí en la última instalación de RHEL 7.5
Configuración que elegí en la última instalación de RHEL 7.5

4.4.3 Installation destination

Installation Destination section of the the Red Hat Enterprise Linux Installation Guide: https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide/sect-disk-partitioning-setup-x86.html

En la guía de instalación de Red hat se encuentra la siguiente nota: «An installation of Red Hat Enterprise Linux requires a minimum of one partition but Red Hat recommends using at least the following partitions or volumes:

  • /
  • /home
  • /boot
  • swap»,

Sin embargo, más adelante veremos que el instalador de Red hat presenta una opción que genera las particiones automáticamente a partir de espacio «unallocated» en el disco. Esta opción genera sólo particiones para /, /boot y swap (no genera la partición /home). Creo que la partición /home no es necesaria en mi caso, así que seguiré dicho esquema de particiones sin incluir la /home.

4.4.3.1 Particionamiento

Para seleccionar o realizar cambios en las particiones donde será instalado el SO debemos: From the Installation Summary:

  • Installation destination > Seleccionar la option «I will configure particioning». Lo cual nos llevará a la ventana «Manual Particioning»
  • El programa de instalación de Red Hat permite intalar el SO en particiones previamente creadas, o crear nuevas particiones a partir de espacio «unallocated» en el disco.
  • Crear nuevas particiones a partir de espacio «unallocated». Hay dos posibilidades:
  • 1- Click here to create them automatically: Crea automáticamete el esquema de particiones recomendado a partir de todo el espacio «unallocated» restante. Por ejemplo, si en nuestro disco quedan 40G de espacio «unallocated», esta opción creará el siguiente esquema:
  • /boot
  • 1024 MB
  • Device type: Standar Partition (esta partición no puede ser LVM)
  • File System: xfs
  • /
  • 35.12 Gb
  • Device type: LVM
  • File System: xfs
  • /swap
  • 3968 Mb
  • Device type: LVM
  • File System: swap
  • 2- Crear cada partición por separado haciendo click en el ícono «+» que se encuentra en la parte de abajo del menú. Si no queremos tomar todo el espacio «unallocated» restante, debemos usar esta opción.
  • Asignar «Mount points» a particiones previamente creadas antes de iniciar el instalador de Red Hat (creadas a través de Gparted por ejemplo).
El problema de esta opción es que Red hat propone como estadart, la creación de todos las particiones que queramos implementar «/ /swap /home etc» (excepto la /boot) dentro de una partición (o Device type) LVM. Ahora, el problema es que Gparted (que es el programa que he venido usando para la creación de esquemas de particiones complejos) no propone la opción para cración de LVM. Además, si lo hacemos a través de particiones previamente creadas, el instalador de Red Hat no permite formatear la partición sino sólo asignarle un «Mount point»; y me ha parecido que es apropiado (no sólo surante la intalación de Red Had, sino durante la instalación de cualquier SO) que el programa de instalación formetee la partición antes de realizar la instalación.
  • Recomiendo la creación de particiones manuales a partir de espacio «unallocated». Construir el esquema de particionamiento propuesto por «Click here to create them automatically».
Click here to create them automatically.
Esquema de particiones generado automáticamente a partir de todo el espacio «unallocated» restante en el disco.
Particiones creadas manualmente haciendo click en «+»
Particiones creadas manualmente haciendo click en «+»
Particiones creadas manualmente haciendo click en «+»
4.4.3.2 LVM and xfs

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/installation_guide/sect-disk-partitioning-setup-x86

LVM (Logical Volume Management): https://wiki.ubuntu.com/Lvm

Por lo que he leido, LVM (Logical Volume Management) es similar a crear una partición extendida y dentro de ella particiones lógicas.

What is LVM: LVM stands for Logical Volume Management. It is a system of managing logical volumes, or filesystems, that is much more advanced and flexible than the traditional method of partitioning a disk into one or more segments and formatting that partition with a filesystem.

Why use LVM? For a long time I wondered why anyone would want to use LVM when you can use gparted to resize and move partitions just fine. The answer is that lvm can do these things better, and some nifty new things that you just can't do otherwise. I will explain several tasks that lvm can do and why it does so better than other tools, then how to do them. First you should understand the basics of lvm.

XFS is a highly scalable, high-performance file system that supports file systems up to 16 EiB (approximately 16 billion GiB), files up to 8 EiB (approximately 8 billion GiB), and directory structures containing tens of millions of entries. XFS supports metadata journaling, which facilitates quicker crash recovery.

4.4.3.2.1 LVM and xfs support for Ubuntu

Para poder leer particiones LVM y xfs en Utuntu (y para que sean detectadas correctametne por Gparted) debemos instalar algunos paquetes.

sudo apt-get install lvm2
sudo apt-get install xfsprogs xfsdump
Advertencia generada en Gparted when LVM suport for Ubuntu is missing
Advertencia generada en Gparted when XFS file system suppor for Ubuntu is missing

5 CentOS

https://www.centos.org/

https://en.wikipedia.org/wiki/CentOS

CentOS (Community Enterprise Operating System) is a Linux distribution that provides a free, enterprise-class, community-supported computing platform functionally compatible with its upstream source, Red Hat Enterprise Linux (RHEL). In January 2014, CentOS announced the official joining with Red Hat while staying independent from RHEL, under a new CentOS governing board.

  • Parece ser que no hay versiones separadas para Desktop o Server:
  • CentOS es en esencia a Server distribution, aunque también puede ser usado en Desktop or Workstations.
  • Most distros don't have Server or Desktop versions. Centos is generally used as Server. There are no roles. Everything depends on what packages you install, how you configure it, which repos you use.
  • Agreed. I would say that CentOS is the open source version of Red Hat Enterprise Linux thus they are both a server distro. The desktop version would essentially be Fedora.
  • Fedora is not the Desktop version... although it's often viewed that way. It's more the development/unstable version -- it races years ahead of a stabilized rhel/cent, which brings in the latest and ostensibly greatest features of whatever desktop environment you're following.
  • Sin embargo, there is a «minimal» version that's command line only and great for servers.

5.1 Install Gnome GUI on CentOS 7 or RHEL 7

https://www.itzgeek.com/how-tos/linux/centos-how-tos/install-gnome-gui-on-centos-7-rhel-7.html

6 Filesystem Hierarchy Standard

https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard

Directory Description
/
Primary hierarchy root and root directory of the entire file system hierarchy.
/bin
Essential command binaries that need to be available in single user mode; for all users, e.g., cat, ls, cp.
/boot
Boot loader files, e.g., kernels, initrd.
/dev
Essential device files, e.g., /dev/null.
/etc
Host-specific system-wide configuration files

There has been controversy over the meaning of the name itself. In early versions of the UNIX Implementation Document from Bell labs, /etc is referred to as the etcetera directory,[3] as this directory historically held everything that did not belong elsewhere (however, the FHS restricts /etc to static configuration files and may not contain binaries).[4] Since the publication of early documentation, the directory name has been re-explained in various ways. Recent interpretations include backronyms such as "Editable Text Configuration" or "Extended Tool Chest".

/home
Users' home directories, containing saved files, personal settings, etc.
/lib
Libraries essential for the binaries in /bin/ and /sbin/.
/media
Mount points for removable media such as CD-ROMs (appeared in FHS-2.3).
/mnt
Temporarily mounted filesystems.
/opt
Optional application software packages.
/proc
Virtual filesystem providing process and kernel information as files. In Linux, corresponds to a procfs mount.
/root
Home directory for the root user.
/run
Run-time variable data: Information about the running system since last boot, e.g., currently logged-in users and running daemons.
/sbin
Essential system binaries, e.g., fsck, init, route.
/srv
Site-specific data served by this system, such as data and scripts for web servers, data offered by FTP servers, and repositories for version control systems.
/sys
Contains information about the devices connected to the computer.
/tmp
Temporary files (see also /var/tmp). Often not preserved between system reboots, and may be severely size restricted.
/usr
Secondary hierarchy for read-only user data; contains the majority of (multi-)user utilities and applications.
/var
Variable files—files whose content is expected to continually change during normal operation of the system—such as logs, spool files, and temporary e-mail files.

7 Upgrade the system

https://docs.ovh.com/gb/en/dedicated/updating-kernel-dedicated-server

https://tutorials.ubuntu.com/tutorial/tutorial-upgrading-ubuntu-desktop#0

https://help.ubuntu.com/community/UpgradeNotes?_ga=2.166774206.1403639924.1537856764-959153226.1536526077

An upgrade is the process of going from an earlier version of Ubuntu to a newer version of Ubuntu with an installed system. An example of this would be going from Ubuntu 17.10 to Ubuntu 18.04 LTS. To avoid damaging your running system, upgrading should only be done from one release to the next release (e.g. Ubuntu 16.04 to Ubuntu 16.10) or from one LTS release to the next (e.g. Ubuntu 16.04 LTS to Ubuntu 18.04 LTS). If you wish to 'skip' a version, you can back up your data and do a fresh installation, or progressively upgrade to each successive version. For example, to upgrade from Ubuntu 16.10 to Ubuntu 17.10, first upgrade to 17.04, then upgrade 17.04 to 17.10.

8 Update the system

To update Ubuntu 18.04, press Super Key (Windows Key) to launch the Activity Overview and look for Software Updater. Run it to check for updates.

Alternatively:

sudo apt update && sudo apt upgrade

9 Enable additional repositories for more software

https://itsfoss.com/things-to-do-after-installing-ubuntu-18-04/

Ubuntu has several repositories from where it provides software for your system. Enabling all these repositories will give you access to more software and proprietary drivers.

Go to Activity Overview by pressing Super Key (Windows key), and search for Software & Updates:

  • Under the Ubuntu Software tab, make sure you have checked all of the Main, Universe, Restricted and Multiverse repository checked.
  • Now move to the Other Software tab, check the option of Canonical Partners.

Once it completes, you’ll find more applications to install in the Software Center.

10 Apt-get

10.1 Update System Packages

The «update» command is used to resynchronize the package index files from the their sources specified in /etc/apt/sources.list file. The update command fetched the packages from their locations and update the packages to newer version.

sudo apt-get update

10.2 Upgrade Software Packages

The «upgrade» command is used to upgrade all the currently installed software packages on the system. Under any circumstances currently installed packages are not removed or packages which are not already installed neither retrieved and installed to satisfy upgrade dependencies.

sudo apt-get upgrade

10.3 How to check the version before install packages using apt get

https://stackoverflow.com/questions/18885820/how-to-check-the-version-before-install-packages-using-apt-get

apt-cache policy <package name> will show the version details.

It also shows which version is currently installed and which versions are available to install.

For example:

apt-cache policy hylafax+

También:

apt-cache show <package name>


Por ejemplo, podemos ver las versiones disponibles de r-base con:

sudo apt policy r-base
r-base:
 Installed: 3.5.2-1bionic
 Candidate: 3.6.0-2bionic
 Version table:
    3.6.0-2bionic 500
       500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages
    3.6.0-1bionic 500
       500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages
    3.5.3-1bionic 500
       500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages
*** 3.5.2-1bionic 500
       500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages
       100 /var/lib/dpkg/status
    3.5.1-2bionic 500
      500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages
    3.5.1-1bionic 500


10.4 Installing a specific Version of a package

En general, si queremos installar una versión específica de un paquete:

sudo apt install r-base=3.5.1-2bionic

Sin embargo, en muchos casos no es tan fácil así. Cuando los paquetes tienen dependencias, la ejecución del comando anterior no resuelve las dependencias automáticamente. Si el paquete tiene muchas dependencia (como es el caso de r-base) la instalación se torna un poco complicada.

Al tratar de instalar «r-base» veremos que la única dependencia es el paquete «r-recommended». Entonces, antes de instalar la «r-base» tenemos que instalar «r-recommended=3.5.1-2bionic». Sin embargo, «r-recommended» tiene muchas dependencias; y aunque la ejecución de «sudo apt install r-recommended=3.5.1-2bionic» resulve las dependencias e instala el paquete, luego se presentan problemas. Lo que pasó cuando lo hice de esta forma fue que aparentemente se había instalado la versión deseada; pero cuando desplegaba la versión del R con «sudo R --version» o en el terminal del R «version» se mostraba la versión más reciente disponible en la Version table. Esto pasa porque al ejecutar «sudo apt install r-recommended=3.5.1-2bionic» se instala la versión deseada de «r-recommended=3.5.1-2bionic» pero con respecto a las dependencias, podría instalarse la versión más reciente disponible en la Version table.

Fui capaz de instalar una versión específica de la siguiente forma:

sudo apt-get install r-recommended=3.5.3-1bionic r-base-core=3.5.3-1bionic r-base-core-dbg=3.5.3-1bionic r-base-dev=3.5.3-1bionic r-cran-mgcv r-doc-html=3.5.3-1bionic r-cran-nlme=3.1.137-1cranBionic0
sudo apt-get install r-base=3.5.3-1bionic r-base-html=3.5.3-1bionic

Se debe notar que se debe ejecutar el comando apt-get con todas las dependencias en una sóla orden, sino se hace de esta manera, apt-get podría resolver dependencias e instalar versiones incorrectas de algunos paquetes.

Note que hemos especificado la versión «=3.5.3-1bionic» para todos los paquetes excepto para «r-cran-nlme=3.1.137-1cranBionic0». Las versiones de «r-cran-nlme» no siguen el mismo orden que «r-base» pero tuvimos también que indicar una versión específica de «r-cran-nlme» porque la versión más reciente de este paquete dependía de versiones más reciente de «r-base».

10.5 Desinstalar un programa

Uninstall the program and all configuration files:

sudo apt-get --purge remove <programa> (podría ser necesario colocar <programa>*) 

También se podría:

sudo apt-get autoremove eclipse*

Lo anterior will uninstall the dependencies and related packages that were installed along with eclipse. This should do the trick.

También podría ser necesario:

rm -r ~/.<programa>/ (en caso de que el programa instale una carpeta en el directorio ~)

Uninstall just the program. If you’d like to remove the program but keep the configuration files, enter the following command:

sudo apt-get remove <programname>

10.6 Repositorios - List and Remove Repositories

List repositories:

apt policy

Si agregamos un repositorio incorrecto (que no existe o lo que sea), al ejecutar «apt update» se generará un error como el siguiente:

Err:14 http://ppa.launchpad.net/webupd8team/gnome3/ubuntu bionic Release
  404  Not Found [IP: 91.189.95.83 80]

E: The repository 'http://ppa.launchpad.net/webupd8team/gnome3/ubuntu bionic Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

esto trae algunos probleminas. Por ejemplo, al abrir el GUI «Software Updater» (tecla SO: escribir "software updater"), la aplicacion generará el error: https://itsfoss.com/failed-to-download-repository-information-ubuntu-13-04/

Failed to download repository information. Check your internet connection.

La solución es eliminar el repositorio incorrecto. Esto lo podemos hacer en línea de comando por supuesto. También puede realizarse fácilmente (como se muestra aquí: https://itsfoss.com/failed-to-download-repository-information-ubuntu-13-04/) a través del GUI «Software & Updates» > go to «other Software» and look for the software source that is causing this problem. Uncheck the box before it to exclude it from future updates.


How to list and remove PPA repository by command line:

https://www.powercms.in/blog/how-remove-ppas-ubuntu-1404141015041510-and-linux-mint

https://linuxconfig.org/how-to-list-and-remove-ppa-repository-on-ubuntu-18-04-bionic-beaver-linux

https://askubuntu.com/questions/307/how-can-ppas-be-removed

En los links anteriores se esplica como eliminar PPA. Sin embargo ese método me ha funcionado sólo cuando el repositorio inicia con 'ppa'. Por ejemplo:

500 http://ppa.launchpad.net/videolan/master-daily/ubuntu bionic/main

puede ser eliminado con:

sudo add-apt-repository --remove ppa:PPA_REPOSITORY_NAME/PPA
$ sudo add-apt-repository --remove ppa:videolan/master-daily

Sin embargo, con un repositorio que no inicia con 'ppa' el comando no puede ser ejecutado de dicha forma. Por ejemplo:

500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages

El repositorio anterior pudo ser borrado a través del siguiente comando:

sudo add-apt-repository --remove 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'

En dicha ocasión fue ejecutado con el «deb» porque dicho repositorio fue incluido de la siguiente forma:

sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'


Sin embargo, luego intenté eliminar este repositorio:

500 http://cran.rstudio.com/bin/linux/ubuntu xenial/ Packages

y no pude hacerlo a través de ninguno de los siguientes comandos:

sudo add-apt-repository 'deb http://cran.rstudio.com/bin/linux/ubuntu xenial/'
sudo add-apt-repository 'http://cran.rstudio.com/bin/linux/ubuntu xenial/'

No encontré forma de eliminar dicho repositorio...


11 Para saber las características del hardware y del SO


11.1 Procesador - nucleos - velocidad - fabricante - arquitectura - 32 o 64bit

lscpu


The next file display las características de cada procesador:

more /proc/cpuinfo

Si queremos, por ejemplo contar el número de CPUs / Cores:

cat /proc/cpuinfo | grep processor | wc -l
cat /proc/cpuinfo | grep 'core id'
nproc



11.2 Para saber la memoria RAM y Swap - total y en uso

free -m

O graficamente en System > Administration > System monitor

Hay también otros comandos detallados aquí http://www.cyberciti.biz/faq/check-ram-in-ubuntu/



11.3 Para ver las particiones y dispositivos montados

Muestra las particiones o dispositivos montados en el orden en el que se encuentran en el disco duro. Es el único comando que conozco que las muestra en el orden correcto. Además da muestra el tamaño exacto de la partición (el tamaño ajustado al momento del particionamiento. Los otros comandos no muestran este tamaño exacto; claro no sé cual es el tamaño correcto) Ver nota sobre el Tamaño de la partición. Tambíen dice si la partición es de tipo Primaria, extendida o lógica y el File system. Muestra también las características del disco duro (tamaño, fabricante, modelo):

sudo parted /dev/sda then type print
sudo parted -l


Muestra todas las particiones en el disco y los dispositivos montados. Muestra también el tamaño de la partición y el File system:

lsblk -fm
lsblk -fm /dev/sda


Muestra todas las particiones en el disco y los dispositivos montados. Da información, aunque no tan precisa, del filesystem type de cada partición o dispositivo. Muestra también algunas características del disco duro (tamaño, modelo):

sudo fdisk -l


A través del comando mount podemos saber el tipo de sistemas de archivos de particiones/dispositivos montados (check filesystem type):

 mount

Al parecer el tipo fuseblk se refiere a una partición ntfs ver http://ubuntuforums.org/showthread.php?t=1096841


Para saber el UUID de una partición:

sudo blkid


Muestra información sólo de particiones/dispositivos montados:

df -h



11.3.1 Partition size - Different partition sizes reported by df and parted

http://ubuntuforums.org/showthread.php?t=1575190

http://linux.derkeiler.com/Mailing-Lists/Fedora/2009-04/msg01901.html



11.4 Desplegar el SO instalado - detallando la version

lsb_release -a

http://askubuntu.com/questions/55609/how-do-i-check-system-specifications



11.5 Para saber si el SO instalado es 32 o 64bit

uname -a

Result for 32-bit Ubuntu:

   Linux discworld 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 i686 i686 i386 GNU/Linux

whereas the 64-bit Ubuntu will show:

   Linux discworld 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux


O a través del comando:

getconf LONG_BIT




11.6 dmidecode

sudo dmidecode | more

Este comando despliega las características detalladas de todos los componentes del hardware:

  • System Information,
  • BIOS Information,
  • Processor Information, etc.

Por ejemplo si se quieren saber las carecterísticas de la computadora (Modelo, Fabricante, Serial etc):

sudo dmidecode | grep -A 9 "System Information"

También se puede utilizar este comando empleando ciertos String a través de la opción -s:

sudo dmidecode -s String_keyword
sudo dmidecode -s system-product-name
sudo dmidecode -s bios-release-date
sudo dmidecode -s baseboard-product-name
sudo dmidecode -s baseboard-manufacturer



11.7 sysinfo - lshw

sudo apt-get install sysinfo

Para crear un archivo html con todas las características del hardware:

sudo lshw -html > mySpecs.html

then check the html file.



11.8 Startup Menu

Al iniciar la computadora podemos ver todas estas características en el Startup Menu. En mi caso F1 me lleva a System Information en donde se despliega esta información. También se puede verificar en el BIOS Setup.



12 Algunas funciones del shell - terminal


12.1 Historique

  • Flecha hacia arriba: remonter,
  • Flecha hacia abajo: redescendre dans l'historique;
  • Ctrl + R <chaine>: Chercher une commande dans l'historique contenant <chaine> ;
    • A nouveau Ctrl + R: cherche la commande précédente ;

Ctrl + G: interrompt la recherche.



13 Some networking commands

https://askubuntu.com/questions/461825/how-to-connect-to-wifi-from-the-command-line

To see list of saved connections, use (<SavedWiFiConn>):

nmcli c

To see list of available WiFi hotspots (<WiFiSSID>):

nmcli d wifi list

or:

sudo iwlist wlan0 scanning

Para conectarse a una red:

nmcli c up <SavedWiFiConn>
nmcli c up iptime

Para conectarse nmcli c down <SavedWiFiConn>

14 Grub2

The main GRUB 2 folder locations include /boot/grub/ and /etc/grub.d/. User preferences are stored in the /etc/default/grub file. The GRUB 2 menu is built by information contained in /boot/grub/grub.cfg.

En este video se explica como configurar grub2: https://www.youtube.com/watch?v=bIH-1hDvZb0

14.1 Installing - Reinstalling Grub2

https://help.ubuntu.com/community/Grub2/Installing

14.1.1 Reinstalling GRUB 2 from a Working System

If Ubuntu is operating normally, boot into the working installation and run the following command from a terminal:

«a» is the drive (letter) on which you want GRUB to write the boot information. Normally users should not include a partition number, which would produce an error message as the command would attempt to write the information to a partition.

sudo grub-install /dev/sda
sudo grub-install --recheck /dev/sda   (éste no es indispensable.. no sé realmente la utilidad)
sudo update-grub

This will rewrite the MBR information to point to the current installation and rewrite some GRUB 2 files (which are already working). Since it isn't done during execution of the previous command, running «sudo update-grub» after the install will ensure GRUB 2's menu is up-to-date.

14.1.2 If a system has become unbootable

There are various methods for reinstalling GRUB 2:

14.1.2.1 Restore or Reinstall Grub 2 from a Ubuntu Live CD or USB

https://help.ubuntu.com/community/Grub2/Installing

http://howtoubuntu.org/how-to-repair-restore-reinstall-grub-2-with-a-ubuntu-live-cd

Grub 2 typically gets overridden when you install Windows or another Operating System. To make Ubuntu control the boot process, you need Reinstall (Repair/Restore) Grub using a Ubuntu Live CD.

Warning: Using the sudo command, especially from a Live CD can do serious damage to your system. Read all instructions and confirm you understand before executing any commands.


  • Mount the partition your Ubuntu Installation is on. If you are not sure which it is, launch GParted (included in the Live CD) and find out. It is usually a EXT4 Partition. Replace the «a6» with your drive letter, and partition number:
sudo mount /dev/sda6 /mnt


  • Now bind the directories that grub needs access to to detect other operating systems, like so:
sudo mount --bind /dev /mnt/dev &&
sudo mount --bind /dev/pts /mnt/dev/pts &&
sudo mount --bind /proc /mnt/proc &&
sudo mount --bind /sys /mnt/sys


  • Now we jump into that using chroot:
sudo chroot /mnt


  • Now install, check, and update grub. This time you only need to add the drive letter (usually a):
grub-install /dev/sda
grub-install --recheck /dev/sda
update-grub


  • Now grub is back, all that is left is to exit the chrooted system and unmount everything:
exit &&
sudo umount /mnt/sys &&
sudo umount /mnt/proc &&
sudo umount /mnt/dev/pts &&
sudo umount /mnt/dev &&
sudo umount /mnt


  • Shut down and turn your computer back on, and you will be met with the default Grub2 screen.
14.1.2.2 Via Boot-Repair Graphical Tool

https://help.ubuntu.com/community/Boot-Repair

14.1.2.3 Via GRUB2 Rescue mode

GRUB 2 provides a rescue mode which allows the user to attempt to repair GRUB 2 from a special GRUB terminal during boot. https://help.ubuntu.com/community/Grub2#Command_Line_and_Rescue_Mode

14.2 Grub no detecta alguno de los SO instalados

La última vez instalé Red Hat cuando ya se encontraban Ubuntu y Windows instalados en mi disco. Como era de esperarse, Red Hat reinstaló el grub. Sin embargo, al reiniciar la computadora, el menú del grub sólo mostraba Ubuntu y Red Hat, dejando inbootable a Windows. Lo mismo pasó al instalé CentOS cuando ya se encontraban Ubuntu, Red Hat y Windows instalados. El grub que instaló CentOS dejó unbootable a Windows.

Esto ya me había pasado en una ocasión anterior y lo había resolvido reinstalando grub2 desde Ubuntu como se muestra en Linux#Reinstalling GRUB 2 from a Working System

Sin embargo, la última vez que formetée la computadora, al tratar de solucionar este problema reinstalando GRUB 2 from Ubuntu, no funcionó, el grub se reinstalaba e incluía a Windows pero esta vez dejaba por fuera a Red Hat.

From my researches, al parecer este problema está relacionado con la configuración de particiones que realicé en Red Hat. En dicha configuración incluí una partición para el /boot (XFS) y dentro de un LVM, la partición / y swap. Entonces, como se ha dicho en otras secciones, es necesario instalar algunos paquetes que adicionan soporte para este tipo de particinoes.

Para solucionar este problema, en Ubuntu: https://askubuntu.com/questions/351002/triple-boot-ubuntu-windows-showing-up-but-not-red-hat

  1. Instalé los paquetes de soporte para particiones: Linux#LVM and xfs support for Ubuntu
  2. Monté la partición /boot de Red Hat (NO tuve que montar la partición LVM de Red Hat, solo la /boot que es standard (xfs) partition)
  3. Reinstalé grub2 como se muestra en Linux#Reinstalling GRUB 2 from a Working System
  • Luego de eso, el comando «update-grub» detectó la instalación de Red Hat, y éste fue incluido en el Grub.

15 SSH

La instalación base de SSH se hace a través de dos paquetes:

openssh-client   permite conectarse a otra computadora
openssh-server   permite que otra computadora se conecte


Hay dos approach para la autentificación al usar SSH:

  • Using the password de la «cuenta linux»
  • SSH Keys

When using a password, ssh pedirá el password de la «cuenta linux» a la que nos estemos conectando al momento de realizar la conexión.

15.1 SSH Keys

https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2

Al usar este método, debemos crear un par de keys: a public and a private key (SSH puede comprobar cuando estas dos keys (public and private) match. La «private key» estará siempre en la computadora a la cual corresponda (donde fue creada) y la «public key» será copiada en las computadoras a las que nos queremos conectar. De esta forma, al momento de realizar la conección, SSH verifica si la «public key» de la computadora que trata de acceder a la otra, se encuentra el la computadora a la cual se quiere acceder. Esta verificación se hace verificando que la «private key» corresponda con algunas de las «public key» que se encuentran en la computadora a la cual se quiere acceder.

A través de este método no es necesario que SSH solicite un password al momento de realizar la conexión. SSH keys provide a more secure way of logging into a server with SSH than using a password alone. While a password can eventually be cracked with a brute force attack, SSH keys are nearly impossible to decipher by brute force alone.

15.1.1 Create the RSA Key Pair

The first step is to create the key pair on the client machine:

ssh-keygen -t rsa

El comando ssh-keygen puede también ejecutarse de la siguiente forma: https://confluence.atlassian.com/bitbucketserver/creating-ssh-keys-776639788.html

ssh-keygen -t rsa -C "adeloaleman@gmail.com"

Associating the key with your email address helps you to identify the key later on.


Once you have entered the Gen Key command, you will get a few more questions:

Enter file in which to save the key (/home/adelo/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):

It's up to you whether you want to use a passphrase. Entering a passphrase does have its benefits: the security of a key, no matter how encrypted, still depends on the fact that it is not visible to anyone else. Should a passphrase-protected private key fall into an unauthorized users possession, they will be unable to log in to its associated accounts until they figure out the passphrase, buying the hacked user some extra time. The only downside, of course, to having a passphrase, is then having to type it in each time you use the key pair.

Luego de ejecutar el comando ssh-keygen, the private and public keys will be located in:

/home/demo/.ssh/id_rsa
/home/demo/.ssh/id_rsa.pub

Una «public key» es algo así:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7eJzkbD+DdE9X8qk/GRD7dhYF8KVTpjNzRg5qCU5NkpeBiIKMZh8UTY41DWKPGTxh0KhMGYQ+LKxMluQGGrOKJE1uEcgnyI2ljbCDZEbpJWvVVngctmJfrm8gubt1djMPRZkwXJK8OaOHsX4UYbrxAW2R3u4gkez13uB0EJAF6l/SifYZzZbdySKoOWoXrtDsuNtQ1OxSMOsdc1PPmQh2lHNtdUiHkEA/PBiwo9lRBFjeVzBsc7EEMITOK1VGDKTtAoOkxJnvpXbm6FjOuTME3j2cEXlWWcyeX9jtkrRDVcDge8G+HpY+5Le4gQBrNYRIVh9ohs72+dOU8n+6CV adeloaleman@gmail.com

note que la key está asociada al email «adeloaleman@gmail.com» ya que fue creada a través de:

ssh-keygen -t rsa -C "adeloaleman@gmail.com"

Si ejecutamos el comando sin palabra asociada:

ssh-keygen -t rsa -C

la «public key» será asociada a: user@computerName. En mi caso «adelo@adelo-laptop»

15.1.2 Copy the Public Key en la computadora a la cual nos vamos a conectar

Once the key pair is generated, it's time to place the public key on the server that we want to use.

La «public key» se debe copiar into the «authorized_keys» file de la computadora a la cual nos vamos a conectar:

~/.ssh/authorized_keys

You can copy the public key into the «authorized_keys» file with the ssh-copy-id command:

ssh-copy-id demo@198.51.100.0

Se debe notar que para poder ejecutar el comando anterior debemos ser capaces de autentificar la conexión (ssh trafic hacia la computadora a la cual nos queremos conectar). Lo anterior es más que lógico porque si no fuera así, seríamos entonces capaces de copiar nuestra «public key» en cualquier computadora y conectarnos luego a ella; lo cual no tiene sentido. Por tanto, cuando ejecutemos el comando anterior, SSH debe solicitar el password de la cuenta@computadora a la que nos estemos conectando. Luego de que la «public key» sea copiada en la computadora a la cual vamos a acceder, podremos realizar la conección «ssh adelo@159.20.10.1» sin necesidad de ingresar el password de la cuenta@computadora.

Generalmente la opción de «solicitar el password de la cuenta@computadora» está activada en uno de los archivos de configuraciones de SSH:

/etc/ssh/sshd_config
    PasswordAuthentication yes

«PasswordAuthentication yes» permite que SSH solicite el password de la cuenta@computadora al momento de realizar la conexión.

«PasswordAuthentication no» impide que la autentificación se realice a través del password de la cuenta@computadora. Así, la utentificación debe ajuro realizarse con SSH Keys.


Por tanto, si intentamos compiar nuestra «public key» a través de «ssh-copy-id demo@198.51.100.0» en una computadora que impide la autentificación a través del password de la cuenta@computadora («PasswordAuthentication no») la autentificación no podrá realizarse y no podremos por tanto copiar la «public key» en la computadora destino. Éste es el caso de VM Instance creadas en la Google Cloud Platform. Entonces, para ser capaces de estableser la conexión con SSH, debemos primero conectarnos a la computadora destino (con algún otro método pues con SSH no hemos todavía sido capaces de autentificar y estableser la conexion) y: https://www.digitalocean.com/community/questions/ssh-copy-id-not-working-permission-denied-publickey

Edit ssh config:

sudo nano /etc/ssh/sshd_config

Change this line:

«PasswordAuthentication no»   to   «PasswordAuthentication yes»

Restart daemon:

sudo systemctl restart sshd



15.2 SSH timeout due to inactivity

http://cdb.systems/blog-in-neque-arcu-vulputate/214-amazon-ec2-ssh-timeout-due-inactivity.html

1 way: you local computer: Esta es la solución que he implementado y funciona perfectametne. Es general para todas las instance a las que te conectes.

You can set a keep alive option in your ~/.ssh/config file on your computer's home dir:

ServerAliveInterval 50

Amazon AWS usually drops your connection after only 60 seconds of inactivity, so this option will ping the server every 50 seconds and keep you connected indefinitely.


2 way: your instance settings:

http://cdb.systems/blog-in-neque-arcu-vulputate/214-amazon-ec2-ssh-timeout-due-inactivity.html



16 Mount discs

Montar discos o particiones

sudo mount /dev/nvme0n1p3 /home/adelo/1-system/4-windows/
sudo umount /dev/nvme0n1p3

16.1 Montar discos permanentemente

http://doc.ubuntu-fr.org/mount_fstab

Para montar permanentemente mi disco_local y mi disco_ext, tuve que agregar las siguientes líneas en el archivo /etc/fstab

# Disco_local:
# Actualmente *(Ver notas abajo)
UUID=2368f4a6-993f-4cfa-8ed4-de39f3b35c7c   /home/adelo/1-system/1-disco_local  ext4  defaults                     0  0
# Configuracion en mi previa computadora:
# UUID=0B8D61386C315368                     /home/adelo/1-system/1-disco_local  ntfs  auto,users,exec,permissions  0  0

# Disco externo - TOSHIBA EXT:
UUID=3C9A5D379A5CEF40                       /home/adelo/1-system/2-disco_ext    ntfs  auto,nofail,users,permissions  0  0

*La configuración que tenía en mi previa computadora no funcionó; se generaba un error al momento del booting. De hecho, la primera vez que intenté montar el disco a través de la configuración del antigua, se generaron errores que no pude solucionar al cambiar las opciones a «defaults». Cuando intentaba montar la partición con «mount /dev/nvme0n1p5 /home/adelo/1-system/», y se generaba el error «Structure Needs Cleaning». No pude solucionar esos problemas y lo que hice fue volver a formatear la partición; luego de eso fui capaz de montarla normalmente con un «mount ..» y a través de «defaults» en el fstab. El único detalle fue que luego de montar la partición con «defaults» tuve que hacer un «chown adelo:adelo 1-disco_local».


16.1.1 chmod y chown en particiones ntfs

Al iniciar la recherche sobre la permisología (chmod) en particiones ntfs, encontré muchos foros en los que se afirmaba que no se podían cambiar los permisos en particiones ntfs. Se planteaba como única solución, la asignación de los permisos deseados al punto de montaje de la partición; lo cual hacía que todos los archivos dentro de la partición tuvieran los mismos permisos que fueron asignados al punto de montaje. A continuación muestro algunas de las páginas en donde encontré dicha información:

Tu ne peux pas changer les droits sur les fichiers d'une partition NTFS pour la bonne raison qu'ils ne sont pas gérés commes sous UNIX. En revanche tu peux changer les droits ou attribuer la propriété sur toute la partition. Pour cela il te suffit de changer les options de montage, soit en option de mount soit directement dans le fstab. Pour plus d'infos sur la procédure voir la documentation mount_fstab


Sin embargo, al final encontré que actualmente sí existe una solución para modificar la permisología de archivos en particiones ntfs.

En los siguientes posts, aunque al inicio de la conversación se decía que no era posible por las mismas razones antes explicadas, al final se encuentra una solución para poder cambiar los permisos en particiones ntfs:

Lo único que tuve que hacer fue adicionar la siguiente línea al archivo /etc/fstab:

Para particiones internas:

# <file system>          <mount point>                 <type>    <options>                           <dump>  <pass>
UUID=0B8D61386C315368    /home/adelo/1-mis_archivos    ntfs      auto,users,exec,permissions         0       0
16.1.1.1 Para discos externos

http://askubuntu.com/questions/14365/mount-an-external-drive-at-boot-time-only-if-it-is-plugged-in

https://wiki.archlinux.org/index.php/Fstab#External_devices

En disco duros externos debemos utilizar la opción <nofail>. Esto porque cuando el disco no está conectado al iniciar la computadora (boot), el sistema buscará la partición (si no se usa <nofail>), al no encontrarla generará un error y el sitema no iniciará correctamente. Con <nofail> el sistema monta la partición durante el boot si el disco se encuentra conectado, y omite este proceso cuando el disco no está conectado. En este caso, el disco será montado luego de conectarlo mientras la computadora está funcionando.

The only inconvenience with <nofail> is that if you connect the device while the system is running, depending on configuration (too many variables to test), the device may not mount immediately. This can be remedied with a simple mount -a or mount /specific_device or a reboot. http://askubuntu.com/questions/14365/mount-an-external-drive-at-boot-time-only-if-it-is-plugged-in

En mi caso, aunque no lo monta inmediatamente, el ínoco de la unidad es desplegado en el Launcher, y haciendo clic en él, el disco se monta normalmente. A través de "sudo mount -a" también se monta correctamente; pero cuando queramos desmontarlo habrá que hacerlo como root porque fue montado como root.

UUID=3C9A5D379A5CEF40    /home/adelo/toshiba_ext       ntfs      auto,nofail,users,exec,permissions	0       0

Para saber el UUID de la partición: sudo blkid

auto: will automatically mount the partition when you boot.

users: allows users to mount and umount.

exec: permite ejecutar archivos. Esta opción se debe colocar luego de la opción <users>. Si no se usa esta opción, podremos modificar los derechos y pertenencias de los archivos. Sin embargo, aún dándole permisos de ejecución a un archivo, éste no podrá ser ejecutado. Ver http://askubuntu.com/questions/30243/why-does-ubuntu-refuse-to-execute-files-from-an-ntfs-partition

nofail: external devices that are to be mounted when present but ignored if absent. https://wiki.archlinux.org/index.php/Fstab#External_devices

permissions: es justamente la opción que permite la modificación de los permisos y pertenencia de los archivos.

dump est utilisé pour les sauvegardes. (Ver mount_fstab)

pass pour l'ordre de vérification au démarrage: (Ver mount_fstab)

  • 1 pour la racine
  • 2 pour les autres partitions Linux
  • 0 pour le swap et les partitions windows: Une valeur de <pass> à 0 signifie qu'il n'y aura pas de vérification au démarrage (Déconseillé dans la plupart des cas).

Otras opciones y una explicación más detallada del uso del archivo etc/fstab se encuentra en mount_fstab

No hay ni siquiera que crear antes el directorio /home/adelo/1-mis_archivos. Éste se creará y la partición será montada automáticamente luego de reiniciar la computadora; y podremos modificar la permisología (chmod) de la pertenencia (chown) de los archivos que se encuentre en tal partición ntfs.

Ahora bien, para modificar la pertenencia y los derechos de la partición y de todos los archivos que se encuentran en ella:

chown -R adelo:adelo /home/adelo/1-mis_archivos

Para modificar los permisos de todos los archivos en la partición ver aquí


En el siguiente post también se encuentra una vía similar (haciendo uso de otras opciones en el archivo /etc/fstab) para poder cambiar los permisos en particiones ntfs. Sin embargo este método no lo he corroborado:

16.2 Mount a remote filesystem in your local machine

Conozco dos formas:

16.2.1 Using the SSH File Transfer Protocol

https://www.digitalocean.com/community/tutorials/how-to-use-sshfs-to-mount-remote-file-systems-over-ssh

Debemos instalar el paquete sshfs:

sudo apt-get install sshfs

Luego, para montar el remote filesystem:

sshfs root@sinfronteras.ws:/ /home/adelo/1-system/3-cloud

Ahora, de la forma anterior, se presenta un problema cuando se pierde la conexión por instantes. Se presentan los problemas explicados en estos forums:

https://serverfault.com/questions/306796/sshfs-problem-when-losing-connection: sshfs problem when losing connection: «When I lost the connection the shell become frozen, if I open another shell and I try to access to the mounting point also this new shell froze»

https://askubuntu.com/questions/358906/sshfs-messes-up-everything-if-i-lose-connection: SSHFS messes up everything if i lose connection: «When I say everything is messe up i mean: My console stops working if i do something as simple as 'ls'. I can't unmount either through the console or the File Browser. Consequently, i can't mount it again, therefore i can't work.

Como se sugiere en los dos forums anteriores, la solución es utilizar la opción «reconnect» del comando sshfs. El siguiente forum explica bien como utilizar esta opción: https://askubuntu.com/questions/716612/sshfs-auto-reconnect

Por tanto, debemos usar el comando sshfs de la siguiente forma:

sshfs -o reconnect,ServerAliveInterval=5,ServerAliveCountMax=3 root@sinfronteras.ws:/ /home/adelo/1-system/3-cloud

sshfs -o reconnect,ServerAliveInterval=5,ServerAliveCountMax=3 visitor@sinfronteras.ws:/root/1-system-cloud/2-mis_archivos_cloud/remote_projects /home/adelo/1-system/3-cloud

The ServerAliveInterval=15 option asked sshfs to check if the server is alive every 15 seconds. ServerAliveCountMax=3 allows the server to not respond for up to three alive checks. The result is that if the server is unavailable for 1 minute, sshfs will reconnect to the server.

16.2.2 Using the Network File System protocol NFS

https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nfs-mount-on-ubuntu-18-04

En este link se encuentra la página de Google Cloud que explica como Mounting Fileshares on Compute Engine Clients a través de NFS: https://cloud.google.com/filestore/docs/mounting-fileshares

Como ya mencionamos, NFS no encripta los datos, lo cual supone problemas de seguridad, pero por la misma razón es más rápido que SSH: https://superuser.com/questions/344255/faster-way-to-mount-a-remote-file-system-than-sshfs

No he podido montar un remote filesystem con NFS entre dististas networks (a través the Internet). Al parecer, por las razones de seguridad que ya hemos explicado, NFS mount se usa dentro de la misma Network; debería, sin embargo, ser posible establecer la conexión entre distintas Networs, pero no he podido hacerlo.

De la única forma que he logrado montar un remote filesystem con NFS fue entre dos Google Cloud VM Instances creadas en el mismo proyecto (se encuentran la misma direct Network). Para hacerlo tuve que usar los Internal IP's. Con los External IP's no pude realizar la conexión. Cuando traté de realizar la conexión con los External IP's, al ejecutar el «mount» se generaba el error «NFS mount timeout» luego de varios minutos. A continuación muestro algunos links que utilicé para trata de solventar este error: https://serverfault.com/questions/894881/mounting-nfs-server-running-in-vm-connection-timed-out https://access.redhat.com/solutions/1751813


https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nfs-mount-on-ubuntu-18-04:

Instalación:

On the Host:

sudo apt install nfs-kernel-server

On the Client:

udo apt install nfs-common


Creating the Share Directories on the Host:

sudo mkdir /var/nfs/general -p

Since we’re creating it with sudo, the directory is owned by the root user on the host. NFS will translate any root operations on the client to the nobody:nogroup credentials as a security measure. Therefore, we need to change the directory ownership to match those credentials:

sudo chown nobody:nogroup /var/nfs/general


Configuring the NFS Exports on the Host Server:

Next, we’ll dive into the NFS configuration file to set up the sharing of these resources.

Open the /etc/exports file in your text editor with root privileges:

/etc/exports:

directory_to_share    client(share_option1,...,share_optionN)

We’ll need to create a line for each of the directories that we plan to share. Since our example client has an IP of 203.0.113.24, our lines will look like the following. Be sure to change the IP address shown here to that of your client:

/etc/exports:

/var/nfs/general    203.0.113.24(rw,sync,no_subtree_check)
/home               203.0.113.24(rw,sync,no_root_squash,no_subtree_check)

When you are finished making your changes, save and close the file. Then, to make the shares available to the clients that you configured, restart the NFS server with the following command:

sudo systemctl restart nfs-kernel-server

También es necesario: https://unix.stackexchange.com/questions/106122/mount-nfs-access-denied-by-server-while-mounting-on-ubuntu-machines

sudo exportfs -a

Sin «exportfs -a» he encontrado el error: «mount.nfs: access denied by server while mounting on Ubuntu machines»


Adjusting the Firewall on the Host:

Si hemos ajustado reglas en el firewall, puede también ser necesario realizar las configuraciones necesarias para permitir el tráfico NFS. Ver https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nfs-mount-on-ubuntu-18-04


Creating Mount Points and Mounting Directories on the Client:

Now that the host server is configured and serving its shares, we'll prepare our client.

We'll create a directories for our mount:

sudo mkdir -p /nfs/general

Finally, to mount the remote filesystem:

sudo mount 203.0.113.0:/var/nfs/general /nfs/general

16.2.3 Mount a remote filesystem in Windows 10

https://stackoverflow.com/questions/443732/how-do-i-mount-a-remote-linux-folder-in-windows-through-ssh

https://www.nsoftware.com/sftp/netdrive/

16.3 Mount an URL

Montar, por ejemplo: http://www.es.sinfronteras.ws

https://blog.amarkulo.com/mount-web-dav-folder/

https://github.com/maxogden/mount-url

https://superuser.com/questions/181351/can-i-use-fstab-to-mount-http-shares

16.4 Mount LVK partitions

https://askubuntu.com/questions/766048/mount-unknown-filesystem-type-lvm2-member



16.5 Mounting windows partition

  • Why do I get «wrong fs type, bad option, bad superblock» error?
Puede ser necesario instalar algunos paquetes para ser capaces de montar la partición Windows: https://askubuntu.com/questions/525243/why-do-i-get-wrong-fs-type-bad-option-bad-superblock-error



16.5.1 Remove BitLocker

Nuevas particiones windows vienen con una encryption option called BitLocker. Si esta opción está activada, no podremos montar la partición Windows en ubuntu. Para desactivarla se pueden seguir estas indicaciones: http://users.isr.ist.utl.pt/~mbayat/hacks/how-to-remove-bitlocker-encryption-in-windows-10/



17 Chown

chown command changes the user and/or group ownership of for given file. The syntax is:

chown owner-user file
chown options owner-user:owner-group file
chown adelo:adelo prueba.txt
chown -R adelo:adelo directorio

18 Chmod

https://doc.ubuntu-fr.org/permissions

18.1 En gerant chaque droit separement

À qui s'applique le changement:

  • u (user, utilisateur) représente la catégorie "propriétaire" ;
  • g (group, groupe) représente la catégorie "groupe propriétaire" ;
  • o (others, autres) représente la catégorie "reste du monde" ;
  • a (all, tous) représente l'ensemble des trois catégories.

La modification que l'on veut faire:

  • + : ajouter
  • - : supprimer
  • = : affectation

Le droit que l'on veut modifier

  • r : read ⇒ lecture
  • w : write ⇒ écriture
  • x : execute ⇒ exécution
  • X : eXecute ⇒ exécution, concerne uniquement les répertoires (qu'ils aient déjà une autorisation d'exécution ou pas) et les fichiers qui ont déjà une autorisation d'exécution pour l'une des catégories d'utilisateurs. Nous allons voir plus bas dans la partie des traitements récursifs l'intérêt du X.
chmod <options> u+rwx,g+rx-w,o+r-wx fichier3
chmod <options> ug+rw fichier3
chmod <options> a-rx fichier3
chmod -R a-rX directorio

18.2 En octal

  • r = 4
  • w = 2
  • x = 1
  • - = 0

Par exemple:

  • Pour rwx, on aura : 4+2+1 = 7
  • Pour rw-, on aura : 4+2+0 = 6
  • Pour r--, on aura : 4+0+0 = 4
  rwx        r-x        ---
7(4+2+1)   5(4+0+1)   0(0+0+0)

18.3 Ajustar permisología recursivamente

chmod -R 750 Documents

18.3.1 Ajustar permisologia recursivamente en traitant de facon differentiee les repertoires et les fichiers

18.3.1.1 A traves del permiso X

X representa el permiso de ejecución en repertorios y en fichiers qui ont un x quelque part. Esto permite tratar separadamente el permiso de ejecución en directorios y en archivos. Veamos algunos ejemplos:

Application 1 :

Soit un répertoire monrep, contenant des sous-répertoires et des fichiers. Les droits sont drwx------ (700) pour les répertoires et -rw------- (600) pour les fichiers.

On veut ajouter récursivement les mêmes droits (resp. rwx et rw) pour le groupe. C'est à dire que veut aboutir à la situation suivante : drwxrwx--- (770) pour les répertoires et -rw-rw---- (660) pour les fichiers.

Si on lance chmod -R 770 monrep : les fichiers vont avoir les droits d'exécution → mauvais :-(

Si on lance chmod -R 660 monrep : les répertoires n'auront plus les droits d'exécution → catastrophique :-(

Si on lance chmod -R g+rwx monrep : les fichiers vont avoir les droits d'exécution → mauvais :-(

Si on lance chmod -R g+rwX monrep : seuls les répertoires (et les fichiers déjà exécutables) auront les droits d'exécution → bon :-)


Application 2 :

Imaginons que précédemment on ait lancé la commande chmod -R 770 monrep. La situation est la suivante : les droits sont drwxrwx--- (770) pour les répertoires et -rwxrwx--- (770) pour les fichiers.

On désire supprimer les droits d'exécution uniquement sur les fichiers. C'est à dire que veut aboutir à la situation suivante : drwxrwx--- (770) pour les répertoires et -rw-rw---- (660) pour les fichiers.

Comme chmod s'applique à la fois aux fichiers et répertoires, nous allons jongler avec x et X. Il faut enlever x puis ajouter X.

Si on lance chmod -R u-x+X,g-x+X monrep cela n'aura aucun effet car X concerne à la fois les répertoires ET les fichiers qui ont un x quelque part. Donc si u-x enlève le premier x (ce qui donne -rw-rwx---), la suite +X va aussitôt remettre un x car il reste un x (celui du groupe !).

Donc il faut d'abord enlever tous les x : u-x,g-x avant de les remettre (sera fait uniquement pour les répertoires cette fois) ce qui donne finalement :

chmod -R u-x,g-x,u+X,g+X monrep
18.3.1.2 A través del comando find

Como vimos, X permite tratar separadamente el permiso de ejecución en directorios y en archivos. Ahora, si queremos asignar una configuración de derechos a los directorios y otra muy distinta a los archivos, lo podemos hacer a través del comando find de la siguiente forma:

http://askubuntu.com/questions/58467/chmod-files-only-in-all-subdirectories/58470

Para los directorios:

find <directorio> -type d -exec chmod 755 {} +

Para los archivos:

find <directorio> -type f -exec chmod 664 {} +

18.4 Permisología por defecto

En Ubuntu, al crear un directorio, la configuración de los permisos por defecto será:

drwxrwxr-x  (775)
Me parece mejor la permisología:
drwxr-xr-x  (755)   (umask u=rwx,g=rx,o=rx) (Ver aquí)
Grupo y otros podrán acceder (x) a los directorio y ver (r) su contenido (listar todos los archivos que en él se encuentran); pero no podrán realizar cambios en el directorio (w) (no se podrán crear archivos en el directorio).

Y para los archivos:

-rw-rw-r--  (664)
Para los archivos podría ser más conveniente de esta forma:
-rw-r--r--  (644)   (umask u=rwx,g=rx,o=rx) (Ver aquí)
O incluso así:
-rw-r-----  (640)

18.4.1 Cambiar la permisologia por defecto

Cambiar la permisologia base/por defecto (umask)

https://es.wikipedia.org/wiki/Umask

umask (abreviatura de user mask, máscara de usuario) es una orden y una función en entornos POSIX que establece los permisos por defecto para los nuevos archivos y directorios creados por el proceso actual.

Los sistemas Unix modernos permiten que las máscaras se especifiquen de dos modos:

  • Un permiso por defecto, también llamado máscara simbólica. Por ejemplo, u=rwx,g=rwx,o=
  • Un número en octal que controla qué permisos se enmascararán (no se establecerán) para cualquier nuevo archivo, por ejemplo, 007.

En ambos casos debe tenerse en cuenta que la mayoría de los sistemas Unix no permiten que nuevos archivos (directorios sí) sean creados con permisos de ejecución activados, independientemente de la máscara.

Ejemplo de máscara simbólica:

 $ umask u=rwx,g=rwx,o=
 $ mkdir foo
 $ touch bar
 $ ls -l
 drwxrwx--- 2 dave 512 Sep  1 20:59 foo
 -rw-rw---- 1 dave   0 Sep  1 20:59 bar


Ejemplos de máscara en octal:

 $ umask 0174
 $ mkdir foo
 $ touch bar
 $ ls -l
 drw-----wx 2 dave 512 Sep  1 20:59 foo
 -rw-----w- 1 dave   0 Sep  1 20:59 bar

Configurar el valor de umask permanentemente: para un usuario en concreto hay que añadir en el fichero .bashrc el comando umask u=rwx,g=rx,o=rx. También se puede modificar el valor de umask en el fichero global /etc/profile para que el cambio sea efectivo para todos los usuarios. http://www.websecurity.es/como-utilizar-umask-establecer-los-permisos-predeterminados


Ahora, a través del umask no se pueden ajustar separadamente los permisos de los directorios y de los archivos, debido a que umash afecta tanto a los archivos como a los directorio. No he encontrado una orden que permita hacer distinción entre los permisos bases de los directorios y los de los archivos. Sin embargo, en el siguiente post se propone una forma de hacer esto:

http://stackoverflow.com/questions/12445527/set-different-umask-for-files-and-folders

Interesting requirement. Currently (at least in bash), umask is a global setting and you cannot set it based on object type.

One solution that comes to mind would be to set the umask to the file variant and then intercept calls to mkdir (such as with a user-created mkdir script earlier in the path) to do:

umask 0701 ; /path/to/real/mkdir $1 ; umask 0604

That way, assuming all your directory creations are done with mkdir, you can ensure they use a different umask setting.

Note that the script should probably be a little more robust such as restoring the previous umask rather than forcing it to 0604, and adding some better error checking and possibly the ability to handle multiple arguments.

But that's all detail, the framework above should be enough to get you started.

19 Hard and symbolic (soft) links

http://stackoverflow.com/questions/185899/what-is-the-difference-between-a-symbolic-link-and-a-hard-link

Underneath the file system files are represented by inodes (or is it multiple inodes not sure)

A file in the file system is basically a link to an inode. A hard link then just creates another file with a link to the same underlying inode.

When you delete a file it removes one link to the underlying inode. The inode is only deleted (or deletable/over-writable) when all links to the inode have been deleted.

A symbolic link is a link to another name in the file system. The soft link points to the name of a file, and not to the contents.

Once a hard link has been made the link is to the inode. deleting renaming or moving the original file will not affect the hard link as it links to the underlying inode. Any changes to the data on the inode is reflected in all files that refer to that inode.

Note: Hard links are only valid within the same File System. Symbolic links can span file systems as they are simply the name of another file.


Let's create hard and soft links:

Al crear links es apropiado colocar las rutas absolutas de la fuente y la destinación:

ln blah1 blah1-hard   (hard link not allowed for directory)
ln -s blah2 blah2-soft

Si blah2 es renombrado, the contents of the file blah2-soft could not be found because the soft link points to the name of the other file (that was changed) and not to the contents.

If blah1 is deleted, blah1-hard still holds the contents.

If blah2 is deleted, blah2-soft is just a link to a non-existing file.

19.1 What's the difference between a hard link and a copy?

https://bbs.archlinux.org/viewtopic.php?id=53484

Hay que internalizar que si se edita un archivo hardlink (siendo éste otro nombre para un mismo archivo) el cambio será reflejado en el archivo original (pues en realidad es el mismo archivo).

Si se hace una copia de un hard link, la copia no será un hard link sino un archivo normal. Es decir, es idéntico hacer una copia del archivo original o del hard link.

No se puede crear un hard link entre dos particiones; sólo soft links son posibles en este caso.

Aunque no se pude hacer un hardlink de un directorio, a través de la orden "cp -rlp", el comand cp copia todo el arbol de directorios y crea hardlinks de todos los archivos en el directorio:

cp -rlp : copy directories *R*ecursively + *L*ink files instead of copying + *P*reserve mode, ownership and timestamps (for non-hardlinked content such as directories)

Si se quieren preservar los softlinks debemos entonces usar también la opción -d

 cp -rlpd

20 Buscar una cadena de caracteres archivos recursivamente - Convinación de find y grep

find . -type f -print | xargs grep "palabra"


Y para buscar una linea que contenga dos palabras especificas:

find . -type f -print | xargs grep "palabra1" | grep "palabra2"


O también:

find . -exec egrep palagra '{}' +


Otra forma:

egrep -r palabra *

21 ls

21.1 Listar sólo archivos o sólo directorios

Listar solo directorios:

ls -lah | grep -v "^-"

Listar solo archivos:

ls -lah | grep -v "^d"

22 Listar archivos con su ruta absoluta

List files with their absolute path in linux:

readlink -f *

23 Listar archivos modificados antes, después, o en una cierta fecha

https://techjourney.net/find-files-that-are-modified-today-or-since-certain-time-ago-in-unix-linux/

To find all files modified in the last 24 hours (last full day) in current directory and its sub-directories:

find . -mtime -1 -print

To find all files with regular file types only, and modified in the last 24 hours (last full day) in current directory and its sub-directories:

find /directory_path -type f -mtime -1 -print

To find all files that are modified today only (since start of day only, i.e. 12 am), in current directory and its sub-directories:

touch -t `date +%m%d0000` /tmp/$$
find /tmefndr/oravl01 -type f -newer /tmp/$$
rm /tmp/$$

24 Contar archivos en un directorio

https://www.pedroventura.com/linux/contar-todos-los-archivos-existente-en-un-directorio-en-linux/

Con find

La cuenta es mas exacta con find, por ejemplo:

find . -maxdepth 2 -type f | wc -l #Contar los archivos pero solo en carpetas dos niveles por debajo

find . -type f | wc -l # Contar archivos de forma recursiva ilimitada

find . -type d | wc -l # Contar directorios de forma recursiva ilimitada

find . -type l | wc -l # Contar enlaces de forma recursiva ilimitada

find . | wc -l #Contar archivos y carpetas de forma recursiva

find . -type f -iname “*.php” | wc -l # Contar archivos con una extensión determinada


Con ls

Con ls es también apropiado para contar los archivos en un sólo directorio. Sin embargo, la forma recursiva (ls -R) no resulta muy apropiada porque se incluye una línea en blanco al finalizar el directorio; además que no se puede diferenciar entre archivos y directorios.

ls | wc -l

Para incluir los archivos ocultos:

ls -A | wc -l

El parámetro -A lista todos los archivos excepto la ruta de carpetas . y ..

25 Crear y borrar usuarios

How to Add (create) and Delete Users on Ubuntu 16.04 https://www.digitalocean.com/community/tutorials/how-to-add-and-delete-users-on-ubuntu-16-04

adduser newuser

You can delete the user itself, without deleting any of their files, by typing this as root:

deluser newuser

If, instead, you want to delete the user's home directory when the user is deleted, you can issue the following command as root:

deluser --remove-home newuser

26 Which

Retorna la ruta de un ejecutable. Por ejemplo si queremos saber donde se encuentra el ejecutable para el comando python, ejecutamos:

adelo@adelo-laptop:~$ which python
/usr/bin/python

27 Source

The source command can be used to load any functions file into the current shell script or a command prompt.

The source command can be abbreviated as just a dot (.) in Bash and similar POSIX-ish shells. However, this is not acceptable in C shell, where the command first appeared.

Uno de los usos más comunes es para reload your .bashrc without re-login or restart.

source .bashrc
. .bashrc

28 du

Para incluir archivos ocultos:

  • La opción -a incluye los archivos ocultos, pero no se puede utilizar con la opción -s, --summarize. La cual permite desplegar el tamaño de un directorio y no de cada archivo por separado. Entonces para poder utilizar la opción --sumarize y desplegar también los archivos ocultos, debemos:
  • Para listar sólo los archivos ocultos:
du -hs .[^.]*
  • Si queremos listar ocultos y normales:
du -hs $(ls -A)
  • Si queremos ordenar los archivos por tamaño:
du -s $(ls -A) | sort -rn  

Note que en el caso anterior, no se debe usar la opción -h para así asegurarse de que la unidad de tamaño sea siempre la misma. Porque el comando sort no distingue entre tamaños sino sólo por los números. Es decir, si colocamos la opción -h, sort colocará un archivo de 50M antes de un archivo de 5G porque 50 es mayor que 5 y no hará distinción de la unidad.

  • Ahora si queremos listar en una unidad en particular:
sudo du -csh --block-size=1M $(ls -A) | sort -rn   (--block-size=1G)

Note que en este caso, un archivo cuyo tamaño sea menor al block-size será listado con un tamaño igual al block-size. Por ejemplo si colocamos --block-size=1G, un archivo de 1k será listado con tamaño 1, que en este caso se refiere a 1G.

  • Si queremos excluir algún archivo o directorio:
du -s --exclude=Directorio $(ls -A) | sort -rn 

29 Tar and Zip

29.1 tar

De esta forma el archivo tar.gz se creará en el mismo lugar donde se ejecuta el comando y dentro del tar.gz se creará el full-path del directorio que se está comprimiendo. Es decir, cuando descomprimamos el archivo obtendremos el directorio /var/www/sinfronteras_ws/perso/

tar cvzf archivo.tar.gz /var/www/sinfronteras_ws/perso/1-archivos

De esta forma el full-path no es generado en el .tar.gz. Cuando descomprimamos el .tar.gz obtendremos sólo los archivos que están en 1-archivos (sin la ruta completa /var/www/sinfronteras_ws/perso/)

tar -czpvf ruta/destino/archivo.tar.gz -C /var/www/sinfronteras_ws/perso/1-archivos .

29.2 zip

Syntax for Creating a zip file:

zip myfile.zip filename.txt
unzip file.zi
unzip file.zip -d destination_folder

30 GnuPG

gpg

GnuPG (gpg) decryption not asking for passphrase: https://security.stackexchange.com/questions/103034/gnupg-decryption-not-asking-for-passphrase



31 La papelera - Trash

En ubuntu 15 el directorio Trash se localiza en la ruta: ~/.local/share/Trash

31.1 Mover archivos a la papelera desde el terminal

http://askubuntu.com/questions/213533/command-to-move-a-file-to-trash-via-terminal

You can use gvfs-trash command from the package gvfs-bin which is installed by default in Ubuntu. Si no está instalado:

sudo apt-get install gvfs-bin

Move file to trash:

gio trash
gvfs-trash filename

According to man gvfs-trash it is deprecated in favour of «gio trash», see man gio: https://askubuntu.com/questions/213533/command-to-move-a-file-to-trash-via-terminal

See the content of the trash:

gvfs-ls trash://

Empty the trash:

gvfs-trash --empty


http://unix.stackexchange.com/questions/42757/make-rm-move-to-trash

As far as using any program as replacement/alias for rm is concerned, there are good reasons not to do that. Most important for me are:

  • The program would need to understand/handle all of rm's options and act accordingly
  • It has the risk of getting used to the semantics of your "new rm" and performing commands with fatal consequences when working on other people's systems


# He hecho el siguiente alias para crear el comando "del", ya que escribir gvfs-trash cada vez que vamos a mover un archivo a la papelera resulta tedioso.
alias del=gvfs-trash


32 Free Up Space On Ubuntu

Liberar espacio

32.1 Clean up APT cache in Ubuntu

You can see the size of this cache with the command below:

sudo du -sh /var/cache/apt

Now, you have two options to handle the cache. Either remove only the outdated packages, like those superseded by a recent update, making them completely unnecessary.

sudo apt-get autoclean

Or clean out the cache in its entirety (frees more disk space):

sudo apt-get clean

32.2 Clean the thumbnail cache

As user and root:

du -sh ~/.cache/thumbnails
rm -rf ~/.cache/thumbnails/*

32.3 Empty the Trash

Vaciar papeleras

Los directorios Trash* pueden ser borrados sin ningún problemas puesto que se crean automáticamente.

  • Papeleras en la partición donde se encuentra instalado Ubuntu:
/home/adelo/.local/share/Trash  (Estas rutas creo que deben ser comprobada como usuario y como root. Ver nota abajo)
/home/adelo/.Trash-*
/root/.local/share/Trash
link del ícono de la papelera

Nota: Por alguna razón que aún desconozco, al comparar los archivos en las dos rutas mostradas arriba con los archivos que se encueentran en la papelera al abrila a través del link del ícono de la papelera, se encuentran discrepancias. Es decir, hay archivos que se observan a través del link de la papelera que no se encuentran en las dos rutas mostradas arriba y viceversa. Por esta razón, debo también vaciar la papelera a través del link de la papelera.

  • Papeleras en disco_local (comprobar como usuario y como root):
/home/adelo/1-system/1-disco_local/.Trash-0
/home/adelo/1-system/1-disco_local/.Trash-1000
  • Papeleras en disco_ext (comprobar como usuario y como root):
/home/adelo/1-system/2-disco_ext/.Trash-0
/home/adelo/1-system/2-disco_ext/.Trash-1000
  • Papeleras en el cloud:
/root/.local/share/Trash
/root/.Trash-*

33 GParted

A la hora de redimensionar una partición, el programa GParted permite reducir tanto al inicio como al final de la partición. Ahora, es seguro redimensionar al inicio del disco? http://unix.stackexchange.com/questions/63258/can-i-safely-resize-my-partition-from-its-beginning

Cuando el programa GParted carga la tabla de particiones, la partición Swap se activa (o monta: no sé si se usa este término en este caso) automáticamente. Es por ello que a primera instancia la opción de redimensionar editar (redimensionar, borrar, etc.) esta partición estará desactivada. También, si dicha partición Swap se encuentra dentro de una partición Extendida, tampoco podremos editar la partición Extendida. Para poder realizar cambios en estas particiones debemos desactivar la partición Swap. Para esto tenemos que seleccionar la partición Swap y luego usar la opción "Swapoff" en el menú "Partition" para desactivarla.

A través del programa de particionamiento prupuesto durante la instalación de Ubuntu, no se pueden realizar redimensiones al inicio de la partición. Tampoco se pueden rediminsionar particiones Extendidas o Swap.

Ahora bien, la redimensión es un proceso que puede tomar mucho tiempo.

34 Fdisk

n => Create new Partition (Then create what you need)

t => Specify type (NTFS is 07 I think, but you can take a look at the list with L)

w => Write the changes to disk and exit

34.1 Crear una partición con fdisk

sudo fdisk /dev/sdb 
Welcome to fdisk (util-linux 2.27.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.
Command (m for help): n
Partition type
  p   primary (0 primary, 0 extended, 4 free)
  e   extended (container for logical partitions)
Select (default p): p
Partition number (1-4, default 1): 1
First sector (2048-4028415, default 2048): 
Last sector, +sectors or +size{K,M,G,T,P} (2048-4028415, default 4028415): 
Created a new partition 1 of type 'Linux' and of size 1,9 GiB.
Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

35 Mostrar barra de progreso al Copiar, mover y borrar archivos

35.1 gcp

Comando para copiar mostrando una barra de progreso y velocidad.

gcp -r origen/archivo /destino

36 Alias

http://www.computerhope.com/unix/ualias.htm

Aliases are used to customize the shell session interface:

alias ls='ls --color=auto'
alias ll='ls -la'
alias .....='cd ../../../../'
Éste lo he adicionado a mi .bashrc:
alias 'la=ls -AX'

37 Formatear una unidad Flash USB

https://askubuntu.com/questions/198065/how-to-format-a-usb-drive

37.1 Usando el terminal

Para mostrar los distintos dispositivos y particiones en el sistema:

lsblk -fm

Antes de formatear una device debemos desmontarla:

umount /dev/sdb*

Par usar el comando mkfs.* sobre una entire device (sdb por ejemplo) y no sobre una partición dentro de esta (sdb1 por ejemplo), debemos usar la opción -I. Ver Nota sdb

$ sudo mkfs.vfat -I /dev/sdb

http://tecadmin.net/format-usb-in-linux/#

https://ksearch.wordpress.com/2010/09/29/format-usb-in-linux/

$ sudo umount /dev/sdc1
$ sudo umount /dev/sdb*

Format with vFat FileSystem

$ sudo mkfs.vfat /dev/sdc1

Format with NTFS FileSystem. En este caso la opción -I no me ha funcionado. Cuando intento formatear en formato NTFS sobre la entire device, obtengo un error:

/dev/sdb is entire device, not just one partition.
Refusing to make a filesystem here!

Por eso tuve que crear una partición en la device antes de formatear --> Crear una partición con fdisk

$ sudo mkfs.ntfs /dev/sdc1

Format with EXT4 FileSystem

$ sudo mkfs.ext4 /dev/sdc1

37.2 Interfaz gráfica

https://askubuntu.com/questions/198065/how-to-format-a-usb-drive

38 Programas para realizar respaldos (Backup)

38.1 rsync

http://www.thegeekstuff.com/2010/09/rsync-command-examples/

http://www.thegeekstuff.com/2011/01/rsync-exclude-files-and-folders/

One of the main feature of rsync is that it transfers only the changed block to the destination, instead of sending the whole file. De hecho, si jamás se ha realizado un proceso rsync entre dos directorios, rsync comprobará las diferencias entre los dos directorios antes de transferir cualquier archivo. Por tanto (aún durante la primera sincronización entre dos directorios) serán transferidos sólo los bloques distintos.

rsync -azvu --delete --progress Source/ Destination/

Si colocamos "Source/" (con el slash al final) todo el contenido del directorio Source será copiado dentro del directorio Destination. Si destination no existe, éste será creado. Ahora bien, si colocamos "Source" (sin el slash) será copiado el directorio "Source" como tal dentro del directorio Destination.

rsync -azvu --delete --progress --exclude 'Figuras' --exclude 'ejercicios' --exclude 'TP_Processus/processus_files' Source/ Destination/
-a, --archive, archive mode; equals -rlptgoD (no -H,-A,-X). This option does the following:
-l, --links copy symlinks as symlinks (Preserves symbolic links)
-p, --perms preserve permissions
-t, --times preserve modification times (Preserves timestamp)
-g, --group preserve group
-o, --owner preserve owner (super-user only)
-D same as --devices --specials
--devices preserve device files (super-user only)
--specials preserve special files
-r, --recursive (ayuda from man rsync)
This tells rsync to copy directories recursively. See also --dirs (-d).
Beginning with rsync 3.0.0, the recursive algorithm used is now an incremental scan that uses much less memory than before and begins the transfer after the scanning of the first few directories have been completed. This incremental scan only affects our recursion algorithm, and does not change a non-recursive transfer. It is also only possible when both ends of the transfer are at least version 3.0.0.
Some options require rsync to know the full file list, so these options disable the incremental recursion mode. These include: --delete-before, --delete-after, --prune-empty-dirs, and --delay-updates. Because of this, the default delete mode when you specify --delete is now --delete-during when both ends of the connection are at least 3.0.0 (use --del or --delete-during to request this improved deletion mode explicitly). See also the --delete-delay option that is a better choice than using --delete-after.
Incremental recursion can be disabled using the --no-inc-recursive option or its shorter --no-i-r alias.
-z is to enable compression
-v verbose
-u : Do not overwrite the modified files at the destination (desde la última sincronización). In a typical sync situation, if a file is modified at the destination, we might not want to overwrite the file with the old file from the source.
--delete it to delete the Files Created at the Target: If a file is not present at the source, but present at the target, you might want to delete the file at the target during rsync. Si el archivo fue modificado en la destinación, éste no será sobre-escrito. Ahora bien, en la siguiente sincronización, si el archivo no vuelto a ser modificado, será sobre-escrito.
--progress : View the rsync Progress during Transfer. Displays detailed progress, i.e how many files are copies, at what rate it is copying the file, etc)
--exclude is to exclude files or directories while doing synchronization. Ver 6 rsync Examples to Exclude Multiple Files and Directories
--delete-after : No entiendo bien cual podría ser la ventaja de borrar después y no antes. Pero he visto en varios foros que usan esta opción en lugar de --delete. En este foro explican cual es la razón, aunque no entendí: Par défaut rsync avec l'option --delete supprime les fichiers qui ont disparus de la source avant tout transfert. Lorsque le fichier a été tout simplement supprimé de la source ça ne pose pas de problème. Par contre si le fichier a été déplacé à un autre endroit c'est plus embêtant car il y a un moment où le fichier n'est plus dupliqué sur le serveur de backup. Pour éviter ce petit soucis il faut ajouter l'option --delete-after pour que les fichiers soit supprimés après la copie et plus avant. http://raphastronome.astro5000.com/?post/Option-delete-after-de-rsync
-H, --hard-links (ayuda from man rsync)
This tells rsync to look for hard-linked files in the source and link together the corresponding files on the destination. Without this option, hard-linked files in the source are treated as though they were separate files.
This option does NOT necessarily ensure that the pattern of hard links on the destination exactly matches that on the source. Cases in which the destination may end up with extra hard links include the following:
  • If the destination contains extraneous hard-links (more linking than what is present in the source file list), the copying algorithm will not break them explicitly. However, if one or more of the paths have content differences, the normal file-update process will break those extra links (unless you are using the --inplace option).
  • If you specify a --link-dest directory that contains hard links, the linking of the destination files against the --link-dest files can cause some paths in the destination to become linked together due to the --link-dest associations.
Note that rsync can only detect hard links between files that are inside the transfer set. If rsync updates a file that has extra hard-link connections to files outside the transfer, that linkage will be broken. If you are tempted to use the --inplace option to avoid this breakage, be very careful that you know how your files are being updated so that you are certain that no unintended changes happen due to lingering hard links (and see the --inplace option for more caveats).
If incremental recursion is active (see --recursive), rsync may transfer a missing hard-linked file before it finds that another link for that contents exists elsewhere in the hierarchy. This does not affect the accuracy of the transfer (i.e. which files are hard-linked together), just its efficiency (i.e. copying the data for a new, early copy of a hard-linked file that could have been found later in the transfer in another member of the hard-linked set of files). One way to avoid this inefficiency is to disable incremental recursion using the --no-inc-recursive option.
--partial (ayuda from man rsync)
By default, rsync will delete any partially transferred file if the transfer is interrupted. In some circumstances it is more desirable to keep partially transferred files. Using the --partial option tells rsync to keep the partial file which should make a subsequent transfer of the rest of the file much faster.
--partial-dir=DIR
A better way to keep partial files than the --partial option is to specify a DIR that will be used to hold the partial data (instead of writing it out to the destination file). On the next transfer, rsync will use a file found in this dir as data to speed up the resumption of the transfer and then delete it after it has served its purpose.
Note that if --whole-file is specified (or implied), any partial-dir file that is found for a file that is being updated will simply be removed (since rsync is sending files without using rsync’s delta-transfer algorithm).
Rsync will create the DIR if it is missing (just the last dir -- not the whole path). This makes it easy to use a relative path (such as "--partial-dir=.rsync-partial") to have rsync create the partial-directory in the destination file’s directory when needed, and then remove it again when the partial file is deleted.
If the partial-dir value is not an absolute path, rsync will add an exclude rule at the end of all your existing excludes. This will prevent the sending of any partial-dir files that may exist on the sending side, and will also prevent the untimely deletion of partial-dir items on the receiving side. An example: the above --partial-dir option would add the equivalent of "-f '-p .rsync-partial/'" at the end of any other filter rules.
If you are supplying your own exclude rules, you may need to add your own exclude/hide/protect rule for the partial-dir because (1) the auto-added rule may be ineffective at the end of your other rules, or (2) you may wish to override rsync’s exclude choice. For instance, if you want to make rsync clean-up any left-over partial-dirs that may be lying around, you should specify --delete-after and add a "risk" filter rule, e.g. -f 'R .rsync-partial/'. (Avoid using --delete-before or --delete-during unless you don’t need rsync to use any of the left-over partial-dir data during the current run.)
IMPORTANT: the --partial-dir should not be writable by other users or it is a security risk. E.g. AVOID "/tmp".
You can also set the partial-dir value the RSYNC_PARTIAL_DIR environment variable. Setting this in the environment does not force --partial to be enabled, but rather it affects where partial files go when --partial is specified. For instance, instead of using --partial-dir=.rsync-tmp along with --progress, you could set RSYNC_PARTIAL_DIR=.rsync-tmp in your environment and then just use the -P option to turn on the use of the .rsync-tmp dirfor partial transfers. The only times that the --partial option does not look for this environment value are (1)when --inplace was specified (since --inplace conflicts with --partial-dir), and (2) when --delay-updates was specified (see below).
For the purposes of the daemon-config’s "refuse options" setting, --partial-dir does not imply --partial. This is so that a refusal of the --partial option can be used to disallow the overwriting of destination files with a partial transfer, while still allowing the safer idiom provided by --partial-dir.
-P : same as --partial --progress.
--no-inc-recursive : Ver comentarios en las opciones -r y -H.


Hasta ahora lo único que no he podido solucionar es que cuando muevo un archivo en la Source, la sincronización no entiende que éste ha sido movido y así moverlo también en la destinación (lo cual disminuiría bastante el tiempo de sincronización). Por el contrario, cuando el... Al parecer, la solución a este problema se encuentra explicada aquí: https://lincolnloop.com/blog/detecting-file-moves-renames-rsync/

http://moderncaveman.org/projects/modern/rsync-detect-renamed/patching-rsync-for-renamed.html

http://javier.io/blog/en/2014/08/06/rsync-rename-move.html

  • Me gustaría que le comando imprimiera en pantalla durante la ejecución, los archivos que no fueron sincronizados porque fueron modificados en la destinación (esto por usar la opción -u). Es decir me gustaría saber cuales fueron los archivos modificados en la destinación.

38.1.1 Mis sincronizaciones

rsync -azvu --delete-after --progress /home/adelo/1-mis_archivos/ /home/adelo/toshiba_ext/1-mis_archivos-dde/
rsync -azvu --delete --progress --exclude '/home/adelo/toshiba_ext/1-mis_archivos/stockage' /home/adelo/1-mis_archivos/ /home/adelo/toshiba_ext/1-mis_archivos/

38.2

http://askubuntu.com/questions/2596/comparison-of-backup-tools

http://www.thegeekstuff.com/2012/05/backup-ubuntu-desktop/

deja-dup

39 Three ways to hide Files and Directories in Linux

Archivos ocultos

http://www.dailygyan.com/2008/01/3-ways-to-hide-files-and-directories-in.html

  1. Make a file named .hidden: We add the name of the file/directory to be hidden into the .hidden file, one name in each line.
  2. Just rename the file/directory and prefix the name with a ' . ' (a dot). Files starting with a ' . ' are considered to be hidden files by linux.
  3. Rename the file and add a '~' to the end. Linux considers files ending in ~ as backup files and hence hides them. En Ubuntu este método funciona sólo en el administrador de archivos (en nautilus por ejemplo) y con archivos normales, no con directorios.

40 Convert

40.1 Convinar o unir imágenes

http://imagemagick.org/Usage/layers/#append

Horizontal:

convert seleccion_categoria1.png +append seleccion_categoria2.png +append -background none -append seleccion_categoria.png

Vertical:

convert seleccion_categoria1.png seleccion_categoria2.png -background none -append seleccion_categoria.png
convert   -background none -append .png

41 Convertir pdf en svg

http://manpages.ubuntu.com/manpages/cosmic/man1/pdf2svg.1.html

pdf2svg pdffile svgfile [page number]

42 Redimensionar imagen - PDF

[redimensionar / resize | comprimir / compress]

sudo apt-get install imagemagick

Si queremos por ejemplo reducir todas las imágenes en un 50% ejecutamos:

mogrify -resize 50% *.jpg

Si queremos darle un tamaño determinado:

mogrify -resize 1024x768 imagen.jpg

42.1 Comprimir un PDF

Paso 1: Trasformar pdf a ps

pdf2ps Original.pdf Medio.ps

Paso 2: Trasformar ps a pdf

ps2pdf Medio.ps Salida.pdf

43 Cortar pdf

https://askubuntu.com/questions/124692/command-line-tool-to-crop-pdf-files

pdfcrop --margins '0 0 0 0' input.pdf output.pdf

Con 0 0 0 0 debería cortar la imagen a margen cero. También se pueden usar valores negativos

pdfcrop --margins '-5 -5 -5 -5' input.pdf output.pdf


El siguiente script toma un archivo pdf con varias páginas, extrae cada página en un archivo separado y recorta cada página a márgenes cero:

#!/bin/bash

for i in {1..11}
do
        pdftk library.pdf cat $i output pag$i.pdf
        pdfcrop --margins '-3 -3 -3 0' pag$i.pdf pag$i.pdf
        echo "$i "
done

Este ejemplo se puede probar con este archivo: Media:Library.pdf

44 Best way to convert svg to png

https://stackoverflow.com/questions/9853325/how-to-convert-a-svg-to-a-png-with-image-magick

inkscape -z -e test.png -w 3000 test.svg

inkscape -z -e test.png -w 1024 -h 1024 test.svg


45 Convert image to grayscale - black and white

https://linuxconfig.org/convert-image-to-grayscale-with-imagemagick

convert linuxcareer-color.png -colorspace gray linuxcareer-color-grayscale.png

46 Gnome and Nautilus

46.1 Save your eyes with Nightlight

https://itsfoss.com/things-to-do-after-installing-ubuntu-18-04/

Nightlight is my favorite feature in GNOME desktop. Keeping your eyes safe at night from the computer screen is very important. Reducing blue light helps reducing eye strain at night.

GNOME provides a built-in Night Light option, which you can activate in the System Settings.

  • Settings-> Devices-> Displays: and turn on the «Night Light» option.

46.2 Configurar el touchpad

  • Settings > Devices > Mouse & Touchpad
    • Edge scrolling
    • Touchpad speed
    • etc...

46.3 How to Move the Unity Desktop’s Launcher

https://www.howtogeek.com/349697/how-to-move-ubuntu%E2%80%99s-launcher-bar-to-the-bottom-or-right/

Cambiar la posición de la barra en donde se encuentran los programas:

  • Settings > Dock

46.4 Choose or disable the alert sound

Desactivar los sonidos de alerta.

https://help.ubuntu.com/stable/ubuntu-help/sound-alert.html.en

  • Settings > Sound > Sound Effects: Alert Volume - Off

46.5 Cambiar el icono de una carpeta

https://ubuntulife.wordpress.com/2010/02/10/tip-cambiar-el-icono-de-una-carpeta/

46.6 Folder color: cambia el color de todas tus carpetas en Ubuntu

https://hipertextual.com/archivo/2014/04/cambiar-color-carpetas-ubuntu/

Folder Color Folder Color es una aplicación muy sencilla que podemos instalar en Ubuntu para cambiar el color de los iconos de las carpetas en Nautilus.

sudo add-apt-repository ppa:costales/folder-color
sudo apt-get update
sudo apt-get install folder-color

46.7 How can I create launchers for an application

Para crear un icon que permita ejecutar la aplicación:

https://askubuntu.com/questions/64222/how-can-i-create-launchers-on-my-desktop

gnome-desktop-item-edit --create-new ~/Desktop

https://www.linuxquestions.org/questions/linux-desktop-74/adding-a-custom-desktop-icon-to-the-dock-panel-in-ubuntu-18-04-a-4175641299/

  • Para adicionar el ícono (icon) a las aplicaciones (que se liste cuando buscamos las aplicaciones en Activities (Windows Tecla), tenemos que colocar el ícono creado en /home/anapaula/.local/share/applications
  • Si luego queremos colocar el ícono (icon) en el Dock (side bar / favorites) lo único que hay que hacer es listar el ícono en Activities y desde ahí hacer right-click > Add to Favorities

47 Screenshot Tool in Ubuntu

Aplicación para imprimir pantalla

47.1 Gnome Screenshot

https://doc.ubuntu-fr.org/gnome-screenshot

Gnome Screenshot est déjà installé par défaut sur Ubuntu

Lancer l'interface depuis le tableau de bord d'Unity à l'aide des mots-clés "capture d'écran" ou pour les menus classiques, Applications → Accessoires → Capture d'écran. Ou encore depuis un terminal avec la commande suivante:

gnome-screenshot -i

À l'aide de raccourcis: La convinación de tecla normal no me funciona, la siguiente sí:

[ALT]+[FN]+[IMPR] → Capturer la fenêtre active.

En la página Web se pueden ver las otras convinaciones de tecla disponibles

47.2 Shutter

https://askubuntu.com/questions/3578/tool-to-add-shapes-annotations-and-text-using-templates-to-images

Shutter es un buen programa para imprimir pantallas.

También permite editar imágenes: crear flechas y etiquetas de una forma fácil.

48 Recording scren - Screencast

Hacer un video de la pantalla.

En esta página se muestran varias opciones. Byzanz permite hacer gif: https://wiki.ubuntu.com/CreatingScreencasts

sudo add-apt-repository ppa:fossfreedom/byzanz
sudo apt-get update && sudo apt-get install byzanz

Para hacer un video .avi podemos usar:

avconv -f alsa -i pulse -f x11grab -r 10 -s 1024x800 -i :0.0 -vcodec wmv1 -acodec pcm_s16le -q 7 b4.avi
Si queremos desactivar el audio agregamos la opción: -an

49 Latex

sudo apt-get install texlive-full (texlive-full ocupa casi 5G de memoria)

49.1 Kile

50 LibreOffice/OpenOffice

50.1 Instalar corrector ortográfico y gramatical en LibreOffice/OpenOffice

http://blog.desdelinux.net/instalar-corrector-ortografico-y-gramatical-en-libreofficeopenoffice/

sudo apt-get install myspell-es
sudo apt-get install myspell-fr myspell-fr-gut
sudo apt-get install myspell-*

50.2 No mostrar número de página y nombre de la página en Excel LibreOffice

How NOT to print sheet name and page number in OpenOffice.org Calc: https://superuser.com/questions/200056/how-not-to-print-sheet-name-and-page-number-in-openoffice-org-calc

Go to: Format > Page: Header/Footer y desactivar ambos

51 Adobe Reader (Acroread)

https://linuxconfig.org/how-to-install-adobe-acrobat-reader-on-ubuntu-18-04-bionic-beaver-linux

Please note that Adobe no longer supports Acrobat Reader for Linux. The latest native Linux version is 9.5.5 dated from 26/04/2013. From this reason you should refrain using/installing Adobe Acrobat Reader if possible to avoid potential vulnerabilities and hacker exploits.

apt install libxml2:i386 gdebi-core
wget ftp://ftp.adobe.com/pub/adobe/reader/unix/9.x/9.5.5/enu/AdbeRdr9.5.5-1_i386linux_enu.deb
sudo gdebi AdbeRdr9.5.5-1_i386linux_enu.deb
acroread

52 pdftk

https://askubuntu.com/questions/1028522/how-can-i-install-pdftk-in-ubuntu-18-04-bionic

The pdftk package in Ubuntu (and its upstream Debian package) was dropped due to its dependency on the now deprecated GCJ runtime. I found a fork that depends on OpenJDK or similar instead.

Install from PPA:

I built a Deb package (for Bionic only) with suitable dependencies:

sudo add-apt-repository ppa:malteworld/ppa
sudo apt update
sudo apt install pdftk

The package contains a wrapper script placed in /usr/bin, so you can invoke it as normally:

pdftk <arguments> ...

53 Vim

«vi» puede ser muy complicado de utilizar. Vale la pena, por lo tanto, instalar «vim»

sudo apt-get install vim

Guardar y cerrar:

:qw

Cerrar sin guardar los cambios:

:q!

Undo:

u

54 GIMP

54.1 How can I put multiple images side by side to make one image

https://gimper.net/threads/re-how-can-i-put-multiple-pics-side-by-side-to-make-one-picture.1042/

Unir/Conbinar varias imágenes:

  • Open one of the pictures in GIMP
  • Go to File > Open As Layers and select the other two pictures
  • Go to Image > Canvas Size and make the canvas a lot bigger, it doesn't have to be exact, just big enough to fit the three pictures
  • Select the different layers one at a time and move them to where you want:
Crl PgUp / PgDn to change layer.
  • Finally go to Image > Fit Canvas to Layers

55 Scilab

sudo apt-get install scilab

56 Skype

sudo apt-get install skype

57 Instalar emulador de Android en Ubuntu / ejecutar aplicaciones de Android en Ubuntu

57.1 Install Genymotion Android Emulator in Ubuntu 14.04

https://www.youtube.com/watch?v=MHmMDEzsJEY

57.1.1 Instalar VirtualBox

Ver Virtualization#Instalación de VirtualBox

57.1.2 Instalar GenyMotion

bash genymotion-2.2...bin
  • Luego entramos en el directorio genymotion e iniciamos el programa:
./genymotion
  • Agregamos una Virtual device:
    • Connect to Genymotion Cloud y agregar un usuario y su contraseña y creamos la Virtual Divice que querramos seleccionando entre las que se encuentran disponibles.
    • Iniciamos la Virtual device creada: en este punto se presentó un problema. Error: Unable to start the virtual device. The virtual device got no IP adress. En el forum http://askubuntu.com/questions/545687/genymotion-virtual-device-got-no-ip-adress alguien publicó: I'm using Ubuntu 14.04 and I got the same error. I reduced the memory below 50% of the total memory. And now it works.
Para hacer esto, ejecuté VirtualBox desde la terminal (como root) y en Settings > System reduje la Memoria. Luego de hacer este cambio genymotion inició correctamente. Sin embargo, en ocasiones se sigue presentando el mismo error.

57.1.3 Instalar WhatsApp

Iniciamos el navegador Web, descargamos WhatsApp de la página oficial y lo instalamos: https://www.whatsapp.com/android/

Si no se inicia el instalador luego de la descarga, nos vamos al directorio de descarga y lo iniciamos desde allí. Cuando el instalador se inicie aparecerá un mensaje diciendo: For security, your tablet is set to block installations of apps obtained from unknown sources. Debemos entoces permitirlo y esto se hace en Settings. Luego de hacer este ajuste en Setting la instalación debería poder completarse

57.2 Las aplicaciones Android llegan a Chrome vía extensión

58 Importar música a un Ipod

https://help.ubuntu.com/community/PortableDevices/iPod

For this you can use Rhythmbox, Banshee, Amarok or gtkpod. Banshee and Amarok are full music management applications that work with the iPod (much like iTunes), whereas gtkpod is a simpler application used only to sync with the iPod.

59 Linux System administration

59.1 Basic configurations

59.1.1 Set the Hostname

Please follow our instructions for setting your hostname. You can use the following commands to make sure it is set properly:

hostname
hostname -f

The first command should show your short hostname, and the second should show your fully qualified domain name (FQDN). https://www.linode.com/docs/tools-reference/linux-system-administration-basics#protect-files-on-a-remote-server

59.1.2 Set the Time Zone

https://www.linode.com/docs/tools-reference/linux-system-administration-basics#protect-files-on-a-remote-server

When setting the time zone of your server, it may be best to use the time zone of the majority of your users. If you’re not sure which time zone would be best, consider using Universal Coordinated Time or UTC (i.e., Greenwich Mean Time).

By default, Linodes are set to UTC. Many operating systems provide built-in, interactive methods for changing time zones:

59.1.2.1 Set the Time Zone in Debian or Ubuntu

Issue the following command and answer the questions as prompted on the screen:

dpkg-reconfigure tzdata
59.1.2.2 Set the Time Zone in CentOS 7 or Arch Linux

View the list of available time zones:

timedatectl list-timezones

Use the Up, Down, Page Up and Page Down keys to navigate to the correct zone. Remember it, write it down or copy it as a mouse selection. Then press q to exit the list.

Set the time zone (change America/New_York to the correct zone):

timedatectl set-timezone 'America/New_York'
59.1.2.3 Set the Time Zone Manually on a Linux System

Find the appropriate zone file in /usr/share/zoneinfo/ and link that file to /etc/localtime. See the examples below for possibilities:

Universal Coordinated Time:

ln -sf /usr/share/zoneinfo/UTC /etc/localtime

Eastern Standard Time:

ln -sf /usr/share/zoneinfo/EST /etc/localtime

American Central Time (including Daylight Savings Time):

ln -sf /usr/share/zoneinfo/US/Central /etc/localtime

American Eastern Time (including Daylight Savings Time):

ln -sf /usr/share/zoneinfo/US/Eastern /etc/localtime

59.2 System Diagnostics

59.2.1 Check Current Memory Usage

59.2.2 Monitor I/O Usage with vmstat

59.2.3 Monitor Processes, Memory, and CPU Usage with htop

60 Linux network administration


60.1 Restart the WiFi-Wireless Network Adapter

service network-manager stop
service network-manager start
service network-manager restart


60.2 Connect to a particular WiFi Network

https://askubuntu.com/questions/833905/how-can-i-connect-to-a-specific-bssid

The command nmcli allows to display the WiFi networks with all their details

nmcli c
nmcli d wifi
nmcli -f in-use,ssid,bssid,chan,rate,mode,signal,bars   dev wifi

To connect to a particular network we can spedify the SSID:

nmcli d wifi connect «the_SSID» password «the_password»

Now, if we want to connect to a particular Access Point, we must specify the Access Point ID (bssid) istead:

nmcli d wifi connect «the_BSSID» password «the_password»

When I tried to run this command as root I got an error, so we have to do it as a standard user.

If we don't find the network or Access Point we are looking for, a good idea is to restart the WiFi-wireless Network Adapter:

service network-manager stop
service network-manager start
service network-manager restart

Then, with «nmcli» we can check if we can see the Network or Access Point we are looking for.


The problem that I got in CCT for a long time that avoid me to successfully connect to the CCT network was that CCT has many access points that use different channels. For some reason, my network adaptor wasn't working well in some chanels (I was able to connect to these chanels but the internet connection was too sllow, sometime it doesn't work at all). Actually, I just was able to sucessfully connect using chanel 11. So when I choose an Access Point that was using chanell 11, I was able to get a fast internet connection.



60.3 Request - Renew the IP address from DHCP

Release the current lease and stop the running DHCP client:

dhclient -r


Request a new IP address:

dhclient



60.4 Network Diagnostics

https://www.linode.com/docs/tools-reference/linux-system-administration-basics#network-diagnostics

60.4.1 The ping Command

The ping command tests the connection between the local machine and a remote address or machine. The following commands "ping" google.com and 216.58.217.110:

ping google.com
ping 216.58.217.110

These commands send a small amount of data (an ICMP packet) to the remote host and wait for a response. If the system is able to make a connection, it will report on the “round trip time” for every packet. Here is the sample output of four pings to google.com:

PING google.com (216.58.217.110): 56 data bytes
64 bytes from 216.58.217.110: icmp_seq=0 ttl=54 time=14.852 ms
64 bytes from 216.58.217.110: icmp_seq=1 ttl=54 time=16.574 ms
64 bytes from 216.58.217.110: icmp_seq=2 ttl=54 time=16.558 ms

The time field specifies in milliseconds the duration of the round trip for an individual packet.

You’ll be presented with some statistics once the process is stopped. This will resemble:

--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3007ms 
rtt min/avg/max/mdev = 33.890/40.175/53.280/7.679 ms

There are several important data points to notice:

   Packet Loss, or the discrepancy between the number of packets sent and the number of packets that return successfully. This number shows the percentage of packets that are dropped.
   Round Trip Time (rtt) statistics on the final line report information about all the ping responses. For this ping we see that the fastest packet round trip (min) took 33.89 milliseconds. The average round trip (avg) took 40.175 milliseconds. The longest packet (max) took 53.28 milliseconds. A single standard deviation unit (mdev) for these four packets is 7.67 milliseconds.

The ping command is useful as an informal diagnostic tool to measure point-to-point network latency, and as a tool to simply ensure you are able to make a connection to a remote server.

60.4.2 The traceroute Command

The traceroute command expands on the functionality of the ping command. It provides a report on the path that the packets take to get from the local machine to the remote machine. Each step (intermediate server) in the path is called a hop. Route information is useful when troubleshooting a networking issue: if there is packet loss in one of the first few hops the problem is often related to the user’s local area network (LAN) or Internet service provider (ISP). By contrast, if there is packet loss near the end of the route, the problem may be caused by an issue with the server’s connection.

Here is an example of output from a traceroute command:

$ traceroute 216.58.217.110
traceroute to 216.58.217.110 (216.58.217.110), 30 hops max, 60 byte packets
1  192.168.10.5 (192.168.10.5)  1.355 ms  1.936 ms  3.195 ms
2  192.168.1.1 (192.168.1.1)  3.858 ms  10.273 ms  13.211 ms
3  * * *
4  109.255.255.254 (109.255.255.254)  18.469 ms  20.636 ms  22.270 ms
5  ie-dub01a-ra4-ae31-0.aorta.net (84.116.238.42)  22.525 ms  22.865 ms  22.922 ms
6  ie-dub01a-ri1-ae52-0.aorta.net (84.116.130.117)  22.550 ms  6.635 ms  15.125 ms
7  213.46.165.18 (213.46.165.18)  15.287 ms  16.058 ms  19.209 ms
8  209.85.252.198 (209.85.252.198)  19.466 ms  19.886 ms 209.85.252.196 (209.85.252.196)  18.892 ms
9  209.85.255.221 (209.85.255.221)  28.838 ms  29.073 ms  31.281 ms

10 209.85.254.245 (209.85.254.245) 126.529 ms 209.85.254.251 (209.85.254.251) 109.405 ms 109.747 ms 11 209.85.143.211 (209.85.143.211) 94.186 ms 72.14.236.99 (72.14.236.99) 96.027 ms 96.982 ms 12 209.85.143.255 (209.85.143.255) 94.640 ms 95.372 ms 98.093 ms 13 iad23s42-in-f14.1e100.net (216.58.217.110) 97.375 ms 94.635 ms 94.856 ms

Often the hostnames and IP addresses on either side of a failed jump are useful in determining who operates the machine where the routing error occurs. Failed jumps are designated by lines with three asterisks (* * *).

Adding traceroute output to Linode support tickets is sometimes useful when trying to diagnose network issues. You may also want to forward traceroute information to your Internet Service Provider (ISP) if you suspect that the connectivity issue is with your ISP’s network. Recording traceroute information is particularly useful if you are experiencing an intermittent issue.


60.4.3 The mtr Command

The mtr command, like the traceroute tool, provides information about the route that internet traffic takes between the local system and a remote host. However, mtr provides additional information about the round trip time for the packet. In a way, you can think of mtr as a combination of traceroute and ping.

Here is an example of output from an mtr command:

$ mtr -r 216.58.217.110
Start: Tue Nov 15 03:27:45 2016
HOST: adelo-laptop                Loss%   Snt   Last   Avg  Best  Wrst StDev
 1.|-- 192.168.10.5               0.0%    10    1.0   1.3   0.9   2.8   0.3
 2.|-- 192.168.1.1               10.0%    10    1.5   1.7   1.0   3.5   0.6
 3.|-- 10.253.152.1               0.0%    10   10.1   8.9   7.3  10.7   1.2
 4.|-- 109.255.255.254           10.0%    10    8.6   7.7   5.7   9.8   1.1
 5.|-- ie-dub01a-ra4-ae31-0.aort 30.0%    10    8.4   9.2   7.6  11.0   1.2
 6.|-- de-fra01a-ri2-xe-4-1-0.ao 30.0%    10   12.5   8.9   6.6  12.5   2.4
 7.|-- 213.46.165.18              0.0%    10    7.5  11.8   6.5  41.0  10.3
 8.|-- 209.85.252.198            20.0%    10   11.0   8.6   6.2  11.0   1.8
 9.|-- 209.85.248.57              0.0%    10   17.0  20.8  16.9  26.6   3.8
10.|-- 209.85.254.245            10.0%    10  105.5  96.8  93.0 105.5   4.6
11.|-- 72.14.236.99              10.0%    10   91.8  97.6  91.8 106.9   5.2
12.|-- 209.85.143.255            30.0%    10   93.1  94.2  93.1  96.1   0.8
13.|-- iad23s42-in-f14.1e100.net 30.0%    10   94.9  93.7  92.7  95.2   0.7

Like the ping command, mtr tracks the speed of the connection in real time until you exit the program with CONTROL+C. To have mtr stop automatically and generate a report after ten packets, use the --report flag:

mtr --report

Be aware that mtr will pause for a few moments while generating output. For more information regarding mtr consider our diagnosing network issues with mtr guide.

60.5 Network File System (NFS)

http://www.learnlinux.org.za/courses/build/net-admin/net-admin-all.html#nfs