## Look at linux distro information. cat /etc/lsb-release --- ## Run a bash script using Cygwin in Windows (runs also in Windows Task Scheduler): C:\cygwin64\bin\mintty.exe /bin/bash -c -l "E://AudioTemplate_Temp/scripts/download.sh" --- ## Running a python command in a headless way within a conda environment in Linux using task spooler: #!/bin/bash source /home/jsperez/miniconda3/etc/profile.d/conda.sh conda activate tsp python -u '.py' --- ## Descargar una pagina web completa. # The options are: # --recursive: download the entire Web site. # --domains website.org: don't follow links outside website.org. # --no-parent: don't follow links outside the directory tutorials/html/. # --page-requisites: get all the elements that compose the page (images, CSS and so on). # --html-extension: save files with the .html extension. # --convert-links: convert links so that they work locally, off-line. # --restrict-file-names=windows: modify filenames so that they will work in Windows as well. # --no-clobber: don't overwrite any existing files (used in case the download is interrupted and # resumed). wget -m \ --no-parent \ www.website.org/tutorials/html/ --- ## Instalar Java 8 sudo apt-get install default-jdk sudo add-apt-repository ppa:webupd8team/java sudo apt-get update sudo apt-get install oracle-java8-installer --- ## Usar screen. # Crear nueva sesion. screen -S # Hacer un dettach. [CRTL+SHIFT+A+D] # Revisar screens existentes. screen -ls # Recuperar un screen y continuar la sesion. screen -r --- ## Agregar descarga a Transmission (cliente bittorrent) env DISPLAY=:1.0 transmission -m [link] & --- ## Revisar el almacenamiento y las particiones. # Espacio en disco de particiones montadas. df -H # Tamano de carpeta y archivos du -sh .[^.]* * --exclude=foldername # Particiones. sudo fdisk -l cat /proc/partitions --- ## Montar particiones de disco compartido. # Temporal. sudo mount -t cifs //127.0.0.1/Server_Seagate_Drive/ /media/STORAGE2/ -o username=guest,port=445,vers=1.0 # Perdurable (en /etc/fstab) //servername/sharename /media/windowsshare cifs guest,uid=1000,iocharset=utf8 0 0 #Recordar correr sudo mount -a, sino reboot. --- ## Controlar inicializacion de servicios. # Deshabilitar servicio en el proceso de booteo. sudo update-rc.d disable # Habilitar servicio en el proceso de booteo. sudo update-rc.d enable --- ## Gestion de usuarios. # Crear usuario incluyendo directorio en /home y password sudo adduser brmon # Agregar un usuario a un grupo. usermod -a -G examplegroup exampleusername # Permitir comandos sudo a un usuario al agregarlo al grupo de sudoers: usermod -aG sudo brmon # Crear usuario sin mas detalles sudo useradd --- ## Interfaces de red. # Observar los IP flows. iptraf # Listar las conexiones salientes. sudo netstat -nputw # Procesos escuchando: sudo netstat -puntal --- ## Bucle infinito (loop) # Varias lineas. #!/bin/bash while : do [Comando_a_ejecutar] sleep 1 done # Una linea. while true; do ~/comandoaejecutar.sh; sleep 1200 ; done & --- ## Bucle hasta que se cumpla una tarea until ./runme do sleep 10 done --- ## Test if a certain process is already running to avoid duplication. # Testing for an ongoing session. CURRENT_PID=$$ pgrep -a 'pattern_process_name' | grep -v $CURRENT_PID running_process=$? #echo "Current PID $CURRENT_PID" #echo "$running_process" if [ "$running_process" -eq 0 ]; then echo "Previous Text Similarity Process is still ongoing at `date '+%Y%m%d_%H%M'`." else echo "Ready to run new instance." fi ## Agregar timestamp a pings ping google.in | xargs -n1 -i bash -c 'echo `date +"%Y-%m-%d %H:%M:%S"`" {}"' --- ## Escuchar las comunicaciones en un puerto con netcat. nc -kl [-u udp] [puerto] --- ## Configurar servidor VNC para solo vista sin password. vnc4server -AcceptPointerEvents=0 -AcceptKeyEvents=0 -AcceptCutText=0 -SecurityTypes="None" --- ## Deshabilitar el servicio de apache. update-rc.d apache2 disable --- ## Gestion de procesos. # Mostrar los procesos activos. ps [aux] top [-u user] # Reiniciar daemons. service daemon restart # Eliminar procesos. kill [pid] # Revisar si hay un proceso activo. pgrep -fl sshpass --- ## Organizacion de datos en archivos de texto plano. cat access_log | awk '{print $1 }' | sort | uniq -c --- ## Remove last four characters from a name in Bash Linux. `echo "${1::-4}_adjusted.wav.txt"` --- ## Conversion de archivos multimedia. # Convertir un archivo de audio a mp3. lame -V 2 [input.wav] [output.mp3] # Convertir un archivo de video a mp3. ffmpeg -i [input.mp4] -f wav - | lame -V 2 - [output.mp3] # Convertir todos los archivos que esten en un folder de mp3 a wav. for song in *.mp3; do lame --decode "$song"; done --- ## Ejecutar comandos sobre un listado de archivos. find . -iname "*.mp3" | sed 's/.*/"&"/' | xargs cp -t /home/jspr-z/Downloads/jdownloader/ ls | xargs -I{} command {} ## Encontrar archivos de tamano cero bytes. find . -size 0c ## Borrar archivos de tamano cero bytes. find . -size 0c -delete ## Borrar los archivos que sobrepasen un tiempo de creacion (i.e., 30 dias). find . -mtime +30 -exec rm {} \; ## Usar logrotate para eliminar archivos cada cierto periodo. # Referencia (https://www.tutorialspoint.com/unix_commands/logrotate.htm) # Contenido de archivo /etc/logrotate.d/psacct: /var/account/pacct { #prerotate loses accounting records, let's no # prerotate # /usr/sbin/accton # endscript compress delaycompress notifempty daily rotate 31 create 0600 root root postrotate /var/account/pacct endscript } --- ## Delete first line of file using sed. sed -i '1d' books.csv --- ## Backup y transferencia de archivos de usuario. # Usar rsync para alta velocidad y fiabilidad. rsync -zavh --progress /home/user/local_directory user@site.org:/home/user/remote_directory/ # Usar lftp lftp ftp://10.7.3.4 -u username,password -e "set ssl:verify-certificate no; mget -c *string*;quit" # Resumir transferencias en sftp sftp corotbvj@tbvj.org <<< "reget directory/*" sftp corotbvj@tbvj.org <<< "reput directory/*" ## Backup de paquetes de software y archivos de configuracion sistema Linux. # Estimacion del tamano del archivo. tar -cf - /directory/to/archive/ | wc -c # Ejecucion del archivado manteniendo las propiedades originales de los archivos. Incluye verificacion del archivo final. tar cvpWf /tmp/system_backup_`date '+%Y%m%d_%H%M'`.tar /home /var /etc /boot /usr/local # Agregar directorios a un archivo .tar existente. tar rvf archive_name.tar newdir/ # Aplicable al jspr-z.server: sudo ufw status > /home/jspr-z/Documents/ufw_rules_`date '+%Y%m%d_%H%M'`.txt; sudo tar cvpf /media/STORAGE2/Linux_Systems_Monthly_Backup/`date '+%Y%m'`/jspr-z_backup_`date '+%Y%m%d_%H%M'`.tar /home/jspr-z /var /etc /boot /usr/local --exclude=home/jspr-z/Downloads --exclude=home/jspr-z/Music --exclude=home/jspr-z/Pictures --exclude=home/jspr-z/Videos --exclude='home/jspr-z/VisualBoy Advance' 2>&1 | tee /media/STORAGE2/Linux_Systems_Monthly_Backup/`date '+%Y%m'`/jspr-z_backup_`date '+%Y%m%d_%H%M'`.log & # Aplicable al jspr-pi.server(1): sudo tar cvpf /home/Monthly_backup/jspr-pi_backup_`date '+%Y%m%d_%H%M'`.tar /home/pi /var /etc /boot /usr/local --exclude=var/swap 2>&1 | tee /home/Monthly_backup/jspr-pi_backup_`date '+%Y%m%d_%H%M'`.log & # Aplicable al jspr-pi.server(2): sudo tar cvpf /home/Monthly_backup/jspr-pi-academic_backup_`date '+%Y%m%d_%H%M'`.tar /home/pi /var /etc /boot /usr/local --exclude=var/swap 2>&1 | tee /home/Monthly_backup/jspr-pi-academic_backup_`date '+%Y%m%d_%H%M'`.log & # Aplicable al tbvj.org.server como superuser: ufw status > /home/backup/ufw_rules_`date '+%Y%m%d_%H%M'`.txt; tar cvpf /home/backup/tbvj.org_backup_`date '+%Y%m%d_%H%M'`.tar /home /var /etc /boot /usr/local /usr/share --exclude=var/swap --exclude=home/backup 2>&1 | tee /home/backup/tbvj.org_backup_`date '+%Y%m%d_%H%M'`.log & # Aplicable a Aptilo Wifi, como usuario root: cd /home/admin/; tar cvpf /home/admin/aptilo_ac_backup_`date '+%Y%m%d_%H%M'`.tar / 2>&1 | tee /home/admin/aptilo_ac_backup_`date '+%Y%m%d_%H%M'`.log # Aplicable al pserver: sudo ufw status > /home/Monthly_backup/ufw_rules_`date '+%Y%m%d_%H%M'`.txt; sudo tar cvpf /home/Monthly_backup/pserver_backup_`date '+%Y%m%d_%H%M'`.tar /home/pi /var /etc /boot /usr/local /opt --exclude=var/swap --exclude=var/lib/dpkg 2>&1 | tee /home/Monthly_backup/pserver_backup_`date '+%Y%m%d_%H%M'`.log --- ## Restaurar un Backup de un sistema Linux. # Usar expresiones regulares para extraer archivos especificos. tar xvf archive_file.tar --wildcards '*.pl' # Extraer archivos especificos. tar xvf archive_file.tar /path/to/file # Extraer archivos especificos a destinos especificos. tar xvf archive_file.tar -C /destination/directory /path/to/file --- ## Envio de emails desde consola. # Solo texto: /bin/echo -e "To:$EMAILID \nFrom:test@gmail.com \nSubject:Asunto \n\n'Mensaje de texto en $(date)"' | ssmtp $EMAILID # Con adjuntos (solamente legibles por equipos que decodifiquen uuencode): /bin/echo -e "To:$EMAILID \nFrom:test@gmail.com \nSubject:Asunto \n\n'Mensaje de texto en $(date)"' | (cat - && uuencode /home/jspr-z/Thunderbirds.jpg Thunderbirds.jpg) | ssmtp $EMAILID --- ## Ejecucion de playlists desde consola en MPD/GMPC/MPC # Enlistar canciones del queue mpc -p 6601 ls # Enlistar playlists mpc -p 6601 lsplaylists # Reproducir el playlist mpc -p 6601 clear && mpc -p 6601 load 'Prueba' && mpc -p 6601 play --- ## Monitoreo de temperatura de CPU. # Ejecutar el comando de reconocimiento de sensores, para determinar # los modulos a agregar a '/etc/modules'. sudo sensors-detect # Sensar la temperatura del CPU con timestamp. echo "$(date)\t $(sensors | grep Core | tr '\n' ' ')" --- ## Instalacion de servicios. tasksel --- ## Run Chromium browser with little cache usage and incognito mode. chromium-browser --maximized --incognito --disk-cache-size=1048576 & --- ## Modificar la fecha del sistema. # Donde MM = month, dd = day, hh = hour, mm = minutes, yyyy = year, ss = seconds. sudo date MMddhhmmyyyy.ss --- ## Instalar el modulo necesario para agregar repositorios ppa desde linea de comandos. sudo apt-get install python-software-properties --- # Buscar un archivo o texto contenido. sudo find . -iname *wireless* >> ~/search.txt; #Encuentra el texto en el nombre de un archivo. grep -a -E -i wireless * >> ~/search.txt; #Encuentra el texto dentro de un archivo de texto plano o binario. grep -F -i wireless * >> ~/search.txt; #Encuentra el texto dentro de un archivo de texto plano o binario. Usa menos memoria al usar -F. pdfgrep -ir --include "*.pdf" 8266 . #Encuentra el texto dentro de un archivo PDF. --- # Converting text from UTF-8 to ASCII. cat textfileinUTF8encoding.txt | iconv -f UTF-8 -t ASCII//TRANSLIT//IGNORE > textfileinASCIIencoding.txt --- ## C # Compilando un archivo en C. gcc program.c -o program-output # Compilando un archivo en C++. g++ program.c -o program-output --- ## Python # Instalando manejador de paquetes individuales de Python. sudo apt-get install python-pip python3-pip # Actualizando el manejador de paquetes individuales de Python. pip install --upgrade pip # Instalando paquetes de Python. pip3 install package_name pip install package_name # Iniciando Jupyter (Python) Notebook usando Anaconda2: cd ~/anaconda2/ && source bin/activate ~/anaconda2/ && jupyter notebook --- ## Reading a Json file. jq . file.json --- # Actualizar tiempo del sistema (especialmente util en Raspberry Pi): ntpd -gq --- ## Crear symbolic link. ln -s [archivo_destino_ruta_completa] [nombre_symlic] --- ## Usando pdftk #Removiendo la pagina 13 de un archivo pdf pdftk in.pdf cat 1-12 14-end output out1.pdf # Uniendo dos archivos pdf. pdftk in1.pdf in2.pdf cat output out1.pdf # Encriptando un archivo pdf (128-bit) y permitiendo imprimir y commentarios. pdftk input_file.pdf output output_file.pdf owner_pw password1 user_pw password2 allow printing allow modifyannotations --- ## Disminuyendo el tamano de un archivo pdf. ps2pdf in.pdf out.pdf --- ## Finding duplicate files. rdfind -outputname duplicate_files__rdfind.txt 'directory1' 'directory2' cat duplicate_files__rdfind.txt | sort -k 4 -n -r #Analyze them sorted by size. cat duplicate_files__rdfind.txt | awk '{print $2 }' | tr -d - | sort -n | uniq -c | sort -n -r | head | awk '{print $2 }' | grep -f - duplicate_files__rdfind.txt | sort -k 2 -g | less # Analyze them sorted by amount of repetitions. --- ## Using rclone to mount Google Drive to linux as partition. rclone mount --vfs-cache-mode=full --daemon --allow-other --drive-use-trash=false GDrive: /home/user/GDrive/ # Unmounting the partition fusermount -uz /home/user/GDrive/ # When fusermount -u does not work because resource is busy... use a lazy mount: sudo umount -l /home/user/GDrive/ # Automatic remounting of rclone connection. df | grep '/home/user/GDrive' || fusermount -u /home/user/GDrive && sleep 30 && rclone mount --vfs-cache-mode=full --daemon --allow-other --drive-use-trash=false GDrive: /home/user/GDrive/ ## Fast copy files using rclone (more transactions but less memory usage without --fast-list): rclone copy --fast-list --progress --max-age 24h --no-traverse /home/sourcedirectory/ GDrive:radio_output_temp/ ## Fast move (including server-side processing) using rclone: rclone move --fast-list --include "*202401*.ogg" --update --check-first --max-depth 1 --verbose GDrive:/sourcedirectory/ GDrive:/radio_output_history/202401/ ## Serving directory using HTTP with rclone: rclone serve http -v --addr 0.0.0.0:8081 GDrive:/output/shareddirectory/ --dir-cache-time 1h0m --poll-interval 0h59m --- ## Downloading a Coursera Course (using a root account). pip install --upgrade coursera-dl coursera-dl -ca --download-quizzes --download-notebooks --video-resolution 720p --- ## Using Docker # Useful lightweight docker images. REPOSITORY TAG IMAGE ID CREATED SIZE busybox latest af2c3e96bcf1 6 days ago 4.86MB bash latest 9f2ecf9a6a14 8 days ago 13.9MB ubuntu latest 3b418d7b466a 3 weeks ago 77.8MB python 3.8-slim 015fc0fe8ec7 5 weeks ago 124MB frolvlad/alpine-miniconda3 python3.7 # Import Docker image from tarball. docker load --input Docker/streamlit_1_1_speech.tar --- ## Observe a directory for new files being created. Useful for pipelines. Put inside a bash script. inotifywait -m /home/corotbvj/GDrive_Radio/input -e close_write -r | while read dir action file; do #cat ${dir}/${file} echo "File ${file} finished writing!" done --- ## Queue-based task scheduling for resource intensive sequential tasks. #list jobs in task-spooler tsp #Add task to the queue. tsp ./command #Check the output of a task tsp -c 1 #Check detailed information for a task tsp -i 1 #Clear all finished jobs. tsp -C #Run multiple jobs at the same time (using CPU parallelization) tsp -S 4 #Remove task from the queue. tsp -r --- Servidores Activos Puerto LAN Puerto WAN Subred ------------------ ---------- ---------- ------ Samba Icecast (http) 8000 8000 - lighttpd (http) 8080 49737 - OpenVPN (privileged) 21 21,49738 192.168.252.0/24 OpenVPN (pi_central) 80 80 10.255.0.0/24 iodined (DNS tunnel) 53 53 10.0.0.0/29 mpd 6600,6601 49739,49730 - motion 8081,8082,8083 8081 - OpenSSH (SSH & SFTP) 22 443,65000 - VNC 5901-5906 - - netcat (nc) 65001 65001 - --- Programas utiles: tcpdump screen netcat(nc) ntfs-3g sshpass tightvncserver (and autocutsel) Filezilla noip2 pdftk Wolfram Mathematica GCC/G++ Eclipse CDT (C/C++) Python (Anaconda2) apcupsd(and apcaccess) samba usbip tightvncserver fluxbox (Window Manager) pdftk Remmina