Recopilación de comandos de consola Linux

Sergi Rodríguez  
20-10-2016 21:15  
14 minutos de lectura  

[ Editado por última vez: 05/06/2022 ]

Con los años he ido acumulando una lista creciente de comandos Linux para hacer cosas de todo tipo, como administración del servidor apache, manipulación de imágenes, y un largo etcétera. Normalmente lo tengo guardado en un correo que tengo en la bandeja de "Borradores", pero hoy he creído que era mejor tenerlo publicado en línea y así tal vez ser útil a otros.

Iré actualizando este artículo a medida que descubra nuevos comandos.

FILE MANAGEMENT

file list

ls -la /path/containing/files

You can paginate results adding | pg or | less to the end.

count files in a directory

find /path/containing/files -maxdepth 1 -type f | wc -l

More info about symbolic files, subdirectories, etc... here.

Find files not matching a regex query

Enable the use of regex pattern list:

shopt -s extglob

Use extglob to list/remove/etc the files who don't match a list of regex pattern:

ls -la !(*190802*|*zip)
rm -la !(*190802*|*zip)

Disable extglob OPTNAME:

shopt -u extglob

find any file by name

sudo find / -name mediatomb

space occupied by a whole directory

du -sh /directory/path

remove a directory including subdirectories and files inside

rm -rf /path/to/be/deleted

create symbolic link

ln -s /usr/local/apache/logs ./logs

rsync

rsync -avz rsyncjob@www.suntransfers.com:/var/www/vhosts/suntransfers.com/protected/messages/  protected/messages

creating/editing/assigning GROUPS of users

groupadd gitwww
sudo usermod -a -G gitwww sergi
sudo usermod -a -G gitwww www-data
sudo usermod -a -G gitwww root
sudo usermod -a -G gitwww apache
sudo chgrp -R gitwww /var/www/suntransfers-new
sudo chgrp -R gitwww .

To compress the current directory, including all subdirectories into the archive file

zip -r myfile.zip .

To compress a directory excluding a list of files/directories:

zip myfile.zip my/directory/to/zip -r -x "*dir1/to/exclude*" "*dir2/to/exclude*"

To unzip in the current directory

unzip archivefile1

recursively find the last 500 modified files, sorted by change-time

find * -type f -printf "%C@ %p\n" | sort -rn | head -n 500

to list store drives and their available space

df -h (output a list of "devices" and its free/used space)

full emptied of the user trash (Ubuntu)

We only need install the first time:

sudo apt-get install trash-cli (only the first time ;)

Afterwards we use this command:

sudo trash-empty

To empty System logs (because problem of space)

sudo su
cat /dev/null > /var/log/syslog
cat /dev/null > /var/log/kern.log

calculate de SHA sum of a file

sha1sum file_name.iso

copy all the content of a directory

Recursive copy of all the directories and files, even the hidden ones:

cp -r /dir/to/be/copied/. .

delete only files in a directory & subdirectories

find /path/directory -type f -exec rm -fv {} \;

change permissions of only some subdirectories

In this example we filter the subdirectories inside /path beginning with "some_" and not recursively searching inside subdirectories:

find /path/some_* -maxdepth 0 -type d | xargs chmod 777

[2020-dic] easy encrypt/decrypt with symmetric key

To encrypt:

gpg -o encrypted_file.gpg -c decrypted_file_pathname

To decrypt:

gpg -o decrypted_file_pathname -d encrypted_file.gpg

In both tasks (encrypt/decrypt) the prompt will ask you for the symmetric key.

[2022-jun] reduce size of a PDF of several pages

Problem: some users upload to server a PDF containing one or more innecesary big images. Solution: to convert first each page to an optimized JPG image, and then build a new PDF file with those JPG images.

Firs we need install Poppler-utils and ImageMagick:

sudo apt install poppler-utils
sudo apt install imagemagick

You probably will need modify Imagemagick security policies:

sudo nano /etc/ImageMagick-6/policy.xml

Replace this:

<policy domain="coder" rights="none" pattern="PDF" />

with this:

<policy domain="coder" rights="read|write" pattern="PDF" />

Finally, this will generate a JPG file for each page on the PDF:

pdftoppm -jpeg -r 120 big.pdf pg

this will join JPG pages in a new PDF:

convert pg-01.jpg pg-02.jpg pg-03.jpg small.pdf

MULTIMEDIA

Config the miniDLNA for read to an auto-mount partition (usually external)

Create the folder /media/sergi/hp from root user:

sudo mkdir /media/sergi/hp

Create a bash file (minidlna_autostart) for mount & restart minidlna:

#!/bin/bash
mount -t ntfs-3g /dev/sda6 /media/hp
service minidlna restart force-reload

Execute this bash file from the autostart of the Preferences/LXSession

gksudo sh /home/sergi/minidlna_autostart

Edit this config file:

sudo leafpad /etc/minidlna.conf

and set:

user=minidlna
media_dir=V,/media/hp/__PELIS__

cat /var/log/minidlna.log

add a subtitle stream to an mp4 movie

mencoder Moon.mp4 -sub Moon.srt -ovc copy -oac copy -fafmttag 0x706d -o Moon2.mp4

FFMPEG

Convert an audio file from OGG to MP3:

ffmpeg -i audio.ogg -acodec libmp3lame audio.mp3

Convert an audio file from MP3 to WAV:

ffmpeg -i audio.mp3 -acodec pcm_s16le -ar 44100 audio.wav

Accelerate the speed of a movie 1.5 times, generating a new file:

ffmpeg -i my_movie_1x_speed.mkv -vf "setpts=(PTS-STARTPTS)/1.5" -crf 18 -af atempo=1.5 my_movie_FASTER.mkv

Extract de audio (mp3) of a video file (flv, mp4, mkv...):

ffmpeg -i videofile.mp4 -q:a 10 -map a audiofile.mp3

Note: use 0-10 values on -q:a 10 to control quality (more is less).

YOUTUBE-DL

Show a list of downloable formats of a same Youtube video:

youtube-dl -F https://www.youtube.com/watch?v=cnbt7bODDHk

Download an specific format (249):

youtube-dl -f 249 https://www.youtube.com/watch?v=cnbt7bODDHk

To know the font types used in a GIMP image file (xcf)

grep -aPo 'font "(.*?)"' plantilla-1-pelicula-domingo.xcf

Webcam streaming on local LAN using VLC

Command for server machine to detect video device:

ls /dev/video*

It returns usually:

/dev/video0

Begin streaming from server machine:

vlc v4l2:// :v4l2-dev=/dev/video0 :v4l2-width=320 :v4l2-height=240 --sout="#transcode{vcodec=h264,vb=800,scale=1,acodec=mp4a,ab=128,channels=2,samplerate=44100}:rtp{sdp=rtsp://:8554/live.ts}" -I dummy

View video streaming on client machine (put your IP, instead):

vlc rtsp://192.168.1.49:8554/live.ts

Join multiple videos in a unique file MKV

Build a video-files.txt with the list of files to join:

file 'foo.mp4'
file 'bar.mp4'
file 'foo bar.mp4'

Run this simple command:

ffmpeg -f concat -safe 0 -i video-files.txt -c copy videos.mkv

How to convert MONO audio to STEREO audio from a Gnome SimpleScreenRecorder video

If the audio channel containing only SILENCE is the c0 then we use this settings to populate it with an exact copy of the audio channel c1:

ffmpeg -i input.mp4 -af "pan=stereo|c0=c1|c1=c1" output.mp4

APACHE SERVER

enable .htaccess logging (MOD_REWRITE)

Put this line inside Directory node on a virtual host configuration file (/etc/apache2/available-sites/barllo.me.conf):

LogLevel alert rewrite:trace2

Note: 2 is the level of trace... can be from 1 to 8.

301 redirection of a whole website to a new domain

RewriteEngine On
RewriteRule ^(.*)$  http://elportalweb.de/tonytambor/$1 [R=301,L]

add the "official" repository

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

install on php7 missing pieces from php5

sudo apt-get install php7.0-cli php7.0-sqlite php7.0-curl php7.0-gd php7.0-zip php7.0-imap php7.0-intl php7.0-json php7.0-mcrypt php7.0-mysql php7.0-mbstring php-memcached php-xml

PHP7, solve error "Call to undefined utf8_decode()"

sudo apt-get install php7.0-xml

solution for: Call to undefined function mcrypt_decrypt()

sudo apt-get install php5-mcrypt
sudo php5enmod mcrypt
sudo service apache2 restart

install PDO for SQLite

sudo apt-get install php5-sqlite
sudo service apache2 restart

install imagick & GD

sudo apt-get install php5-imagick php5-gd

Apache css/javascript cache

sudo a2enmod expires
sudo apachectl restart

restart apache

apachectl restart  (centos)
sudo service apache2 restart (ubuntu)

vhosts in centos

ls -la /etc/httpd/vhost.d

cPanel MIME types for be compressed by Apache automatically

text/html text/plain text/xml text/javascript application/javascript application/xhtml+xml application/xml application/rss+xml application/atom_xml application/x-javascript text/css

clean RAM cache

sudo sh -c "sync; echo 3 > /proc/sys/vm/drop_caches"

use a directory on another drive or partition using a symlink

it's not enough with create a symbolic link. The magic comes curiously when we change the execution permissions

ln -s "/media/sergi/PARTITION_NAME/path_to/source_dir" "/local_path_to/target_dir"
chmod -R o+x "/media/sergi/PARTITION_NAME/path_to/source_dir"
chmod o+x "/media/sergi/PARTITION_NAME/path_to"
sudo chmod o+x "/media/sergi/PARTITION_NAME"

Create a new VHOST duplicating another one

sudo cp /etc/apache2/sites-available/example1.com.conf /etc/apache2/sites-available/example2.com.conf
sudo gedit /etc/apache2/sites-available/example2.com.conf
sudo a2ensite example.com.conf
sudo service apache2 restart
sudo gedit /etc/hosts

And add something like this:

127.0.1.1     example2.me
127.0.1.1     www.example2.me

To list loaded PHP.ini files location

php --ini

It returns something like:

/etc/php/7.1/cli
Loaded Configuration File: /etc/php/7.1/cli/php.ini
Scan for additional .ini files in: /etc/php/7.1/cli/conf.d
Additional .ini files parsed: /etc/php/7.1/cli/conf.d/10-mysqlnd.ini,
/etc/php/7.1/cli/conf.d/10-opcache.ini,
/etc/php/7.1/cli/conf.d/10-pdo.ini,
/etc/php/7.1/cli/conf.d/15-xml.ini,
/etc/php/7.1/cli/conf.d/20-calendar.ini,
/etc/php/7.1/cli/conf.d/20-ctype.ini,
...

Run Apache with your user, when using ecryptfs

I needed it when i encrypted my home dir (with ecryptfs) and i put there www directory. You need to edit this file:

sudo nano /etc/apache2/envvars

And replace the values of this:

export APACHE_RUN_USER=myusername
export APACHE_RUN_GROUP=myusername

And restart Apache:

sudo service apache2 restart

MYSQL SERVER

empty database / delete all tables from database

DROP DATABASE mydbname;
CREATE DATABASE mydbname;
CREATE DATABASE mydbname CHARACTER SET='utf8mb4' COLLATE='utf8mb4_general_ci';

download a dump of the database

mysqldump -u root travelgroup_qa > travelgroup_qa.dump (dump --- execute from server)
tar -czf travelgroup_qa.dump.tar.gz travelgroup_qa.dump (generate tar.gz --- execute from server)
rm -f -r travelgroup_qa.dump (delete dump --- execute from server)
scp root@suntransfers.com:suntransfers_2014_12_18_12_54.sql.gz . (download --- execute from local, put attention on the FINAL DOT of this command!!!)
gzip -d suntransfers_2014_12_18_12_54.sql.gz (extract sql dump from zip file --- execute from local)
mysql -u root -p travelgroup-master < travelgroup_qa.dump (import dump --- execute from local)

make duplicated of a database from linux shell

mysqldump -u username -p --routines original_db > db.dump
echo "create database `duplicated_db`" | mysql -u username -p
mysql -u username -p duplicated_db < db.dump

connect

mysql -u root -p (it then will ask the password)
use my_database_name (for select a database)

restart mysql in centos (QA server)

/sbin/service mysqld start

list of tables with a lot of columns with its properties!

SHOW TABLE STATUS FROM mydatabase;
SHOW TABLE STATUS WHERE true;
SHOW PROCESSLIST;

SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('id_trayecto','trayecto_id','id_route','route_id')
AND TABLE_SCHEMA='travelgroup';

disable temporally the check of integrity for foreign keys and be able to drop tables

SET FOREIGN_KEY_CHECKS=0;
drop table if exists `refund_reasons`;
SET FOREIGN_KEY_CHECKS=1;

make a dump

mysqldump -u root travelgroup_qa > travelgroup_qa.dump

duplicate a table and its content

CREATE TABLE new_table_name AS SELECT * FROM table_name;

Create a new user and its privileges

GRANT ALL ON mydbname.* TO 'myusername'@'localhost' IDENTIFIED BY '**passw**';
flush privileges;

List users with access to a database

SELECT USER FROM mysql.db WHERE db='mydbname';

Reset password to mysql root user

Stop the MySQL Server:

sudo /etc/init.d/mysql stop

Start the mysqld configuration:

sudo mysqld --skip-grant-tables

In some cases, you've to create the /var/run/mysqld first:

sudo mkdir -v /var/run/mysqld && sudo chown mysql /var/run/mysqld

Login to MySQL as root (maybe you need to try twice !?):

mysql -u root mysql

Execute these mysql commands:

UPDATE mysql.user SET Password = PASSWORD('YOURNEWPASSWORD') WHERE User = 'root';
FLUSH PRIVILEGES;
exit;

Note: on some versions, if password column doesn't exist, you may want to try:

UPDATE user SET authentication_string=password('YOURNEWPASSWORD') WHERE user='root';

OTHER SYSTEM TOOLS

work as root user

sudo su

Create new user

sudo useradd {username}
sudo passwd {username}

Give root privileges to this user:

sudo adduser {username} admin

network tools

ifconfig -a (typical list network interfaces)
lspci | egrep -i --color 'network|ethernet' (list network interfaces)

control brigthness in Lubuntu

xrandr --output LVDS-1 --brightness 0.8

or

xrandr --output VGA-1 --brightness 0.8

or

xrandr --output eDP1 --brightness 0.8

to send output of a command though email

ls -la | mail proyectos@imasdeweb.com

create/share a ssh-key

To generate a pair private/public key on your local:

ssh-keygen

To store this identification on your remote:

ssh-copy-id user_name@remote_host_address

show network traffic monitor on console

sudo nethogs
sudo tcptrack -i eth0

disable Teamviewer daemon

sudo teamviewer --daemon stop

to burn bootable ISO image to an USB drive

Easy command for make a bootable USB from an ISO file:

dd bs=4M if=/home/sergi/arxiu.iso of=/dev/sdb

set spanish keyboard

setxkbmap es

disable touchscreen on startup

You must add this command to the startup app list:

xinput --list | egrep -o "ouchscreen.+id=([0-9]+)" | egrep -o "[0-9]+" | xargs -L1 xinput disable

To migrate IMAP messages

Very useful command for pass ALL the email messages & folders from a server to other, usually during a server migration:

imapsync --host1 0.10.20.30 --user1 info@mydomain.com --password1 "XxXxXxX" --ssl1 --port1 993 --host2 mail.mydomain.com --user2 info@mydomain.com --port2 143 --tls2 --password2 "XxXxXxX" --automap

Note 1: add --dry --justfolders to check (without changes) the correct mapping of the folders.

Note 2: so, usually one of the hosts is an IP (note: the IP of the mail server USUALLY is not the same of the web server IP!). Sometimes the recommendation is not to set port neither ssl/tls settings. The imapsync script is enough smart to test some typical connection settings by himself if you don't specify those settings.

Clone a remote directory using FTP

To make a perfect recursively clone of a remote directory, including hidden files/directories:

wget -rm ftp://user:password@ftp.mydomain.com/public_html/

To generate a private/public key pair

ssh-keygen -t rsa

To upload a SSH key to login on server

ssh-copy-id -i ~/.ssh/id_rsa.pub username@server.com

To kill teamviewer process and avoid future auto-boot

To avoid future autoboot execution:

sudo update-rc.d teamviewerd remove

To "kill" process (to stop daemon):

sudo teamviewer --daemon stop

Basic tasks with CRONTAB

To edit crontab file for current user:

crontab -e

To add a new crontab file to a user:

echo "*/15 * * * * php -f /var/www/html/cron.php" >> cron.tmp
sudo crontab -u www-data cron.tmp
rm cron.tmp

To check the last executions of ALL crontabs:

grep CRON /var/log/syslog

Upload a local file to server using SSH

You must run a command like this from your local terminal

scp /path/to/local/file remoteuser@remoteserver.com:/destination/path

Download a remote file to local using SSH

You must run a command like this from your local terminal

scp remoteuser@remoteserver.com:/path/to/remote/file /path/to/local/dir

If you get an error related to permission denied, try this:

scp -i ~/.ssh/id_rsa remoteuser@remoteserver.com:/path/to/remote/file /path/to/local/dir

Anyway, you must be sure than the user remoteuser has read permission over that file on server.

If any of the paths contain spaces, use this:

scp -T remoteuser@remoteserver.com:"'/path/to remote/file'" /path/to/local/dir

[2020] Increase font size on terminal

On terminal run this command to edit console setup:

sudo nano /etc/default/console-setup

Once inside, change the font size:

FONTSIZE="16X32"

[2020] Disable some hardware on boot (touchscreen, built-in webcam...)

Using this command i found that my webcam (which use driver uvcvideo) is on the Bus X and Device Y:

lsusb -t

And in the output of this other command i find that the vendorID and productID of the device and those Bus X & Device Y is something like 0bda:573d:

lsusb

So now i add this new rule (file):

sudo nano /etc/udev/rules.d/40-disable-camera.rules

and i put inside this:

ATTRS{idVendor}=="0bda", ATTRS{idProduct}=="573d", RUN="/bin/sh -c 'echo 0 >/sys/\$devpath/authorized'"

[2020] Send email from terminal with subject and body

Whenever we have installed and configured an email server like exim, usually on an VM. Thern we can do it with a single terminal command line, breaking lines with \n. It's necessary to delimiter string content with single quote, not double quote:

echo $'Subject:Foo...\nThis is body line.' | sendmail recipient@mail.com

[2020-nov] Useful network/wifi CLI-tools

Info about all netowrk interfaces (IP, type,...):

nmcli

Graphical list of all wifi access points and their quality

nmcli device wifi list

Graphical list of all wifi access points and their quality

nmcli device wifi connect {SSID} {passwd}

[2020-dic] Migrate a whole server between two VM's using scp/ssh

Use the next command when you need to "move" all your server (settings, databases, mail... almost all) from a VPS to another one. You must have installed the same OS version on both machines. From the terminal connected to the origin machine run this:

sudo tar cvpf - --exclude=/etc/network/* --exclude=/etc/hosts --exclude=/proc/* --exclude=/dev/* --exclude=/lost+found --exclude=/etc/fstab --exclude=/etc/mtab --exclude=/sys/* --exclude=/boot/* --exclude=/etc/netplan/* / | ssh root@destination.machine.IP "tar xvpf - -C /"

[2021-feb] Get details of a PID process

ps -Flww -p {THE_PID}

[2021-sep] Deactivate/activate a built-in wifi device

To know the name of the network device to be deactivated:

iwconfig

To deactivate the use of a device:

sudo ip link set wlp2s0 down

To re-activate it:

sudo ip link set wlp2s0 up

[2022-apr] Run an installed flatpak app

flatpak run org.gnome.Epiphany
flatpak run org.flameshot.Flameshot gui

With this command you get the list of installed flatpak apps and its "name":

ls -la /var/lib/flatpak/app

[2022-mai] Customize keyboard map layout on X11 to add foreign symbols

In this example i want to render "ç" when pressing ALTGR+c in a latam keyboard:

sudo nano /usr/share/X11/xkb/symbols/latin

There you must edit this line, putting "ccedilla" instead of "cent" and "copyright":

key <AB03> { [ c, C, ccedilla, Ccedilla ] };

And then reload keyboard layout with:

setxkbmap -layout latam

[2022-oct] Useful keyboard shortcuts on GNOME

Open capture GUI of flameshot (installed via Flatpak):

flatpak run org.flameshot.Flameshot gui

Temporally suspend ubuntu:

systemctrl suspend

[2023-mar] Start SSH server on boot

sudo systemctl enable ssh

To check the status:

sudo service ssh status
Etiquetas : linux | consola | shell

Comentarios 0   Visitas 761  

  Comentarios


Añada su comentario:

Comentario:
Nombre:
(pregunta anti-robots)

Enviar

DÍGANOS QUÉ NECESITA

¡¡ Le respondemos antes de 24h !!
Puede dejarnos su teléfono.

Puede rellenar el formulario (pulsar botón derecha) o bien aquí tiene nuestros datos de contacto.

(pregunta anti-robots)

  Enviar

Revisar consentimientos a cookies