Herramientas de usuario

Herramientas del sitio


wiki2:linux_howto

¡Esta es una revisión vieja del documento!


Linux how tos

Find concrete files

Find lasts changes files in folder

To find all files that file status was last changed N minutes ago: find -cmin -N.

For example: find -cmin -5

Find those files with contain "X"

grep -rnw '/path/to/somewhere/' -e 'pattern'
  • -r or -R is recursive,
  • -n is line number, and
  • -w stands for match the whole word.
  • -l (lower-case L) can be added to just give the file name of matching files.

Others:

  • -i for ignore the case
grep -Ril "text-to-find-here" /

# This will only search through those files which have .c or .h extensions:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"

# This will exclude searching all the files ending with .o extension:
grep --exclude=\*.o -rnw '/path/to/somewhere/' -e "pattern"

# This will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"

Environment variables

Puedes definirlas en el .profile para toda la sesión o en el .bashrc. Una definicións será:

export PRUEVAR=PRUEBA

Luego para usarla:

echo ${USER}
ls /home/${USER}

Para borrarla:

unset PRUEVAR

Otra forma:

set NAME=Value
setenv NAME=Value

Para usarla para un comando:

export PGPASSWORD=mysecretpassword && psql -h 127.0.0.1 -U postgres

Puedes ejecutar un comando con variables de entorno temporales:

env NAME=Value echo $NAME

Por ejemplo un a.sh que podrías ejecutar como env PT=123 PP=33 ./a.sh

echo $PT
echo $PP

printenv es otro comando que permite mostrar el valor de una variable de entorno.

printenv WATCHEXEC_META_CHANGED_PATH

env también te sirve para listar las variables de entorno definidas en esta sesión.

<fast> How to's...

Understand free output

  • Free memory is the amount of memory which is currently not used for anything. This number should be small, because memory which is not used is simply wasted.
  • Available memory is the amount of memory which is available for allocation to a new process or to existing processes.

Available does include free and buff/cache columns. These (free and buff/cache) can be reused for current needs immediately.

How to enable root

So, rirst execute in a terminal: sudo passwd root. you will prompted for a new Unix password. Write it twice(second for confirmation). Then execute: sudo passwd -u root . to unlock the account.

If you want to disable root account in Ubuntu you need to lock the root account by using the following command sudo passwd -l root

Change kernel variables

Kernel variables are changed with sysctl.

Set a serie of variables:

sysctl net.ipv4.ip_forward=1
sysctl net.ipv4.conf.all.accept_redirects=0
sysctl net.ipv4.conf.all.send_redirects=0

You can watch set variables currently in memory with sysctl -p

Or all of them with: sysctl -a

To make permanent those values write them at /etc/sysctl.conf.

Detect which process is using which ports

All open network connections:

sudo netstat -nlp

List of processes using tcp port 43796:

lsof -i tcp:43796
# or
lsof -i :9200

List of pids using tcp port 43796:

sudo fuser 43796/tcp

Know info about the system

cat /etc/*-release will give you info about the Linux distribution version.

uname -r will give you info about the kernel.

uname -a will give you info about the Unix system.

Create an iso from a folder

genisoimage -o ~/backup.iso -V BACKUP -R -J ~/Documents

Copy and paste from console

With the xclip command, adding these lines to .bashrc file:

alias pbcopy='xclip -selection clipboard'
alias pbpaste='xclip -selection clipboard -o'

You can do the next:

echo "Welcome To OSTechNix!" | pbcopy
echo `pbpaste`
pbcopy < /etc/resolv.conf

Generate random string

# Allow "tr" to process non-utf8 byte sequences
export LC_CTYPE=C

# read random bytes and keep only alphanumerics
< /dev/urandom tr -dc A-Za-z0-9 | head -c32

Install Java

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

If you want to check:

 
sudo update-alternatives --config java

Work in background

Run in background: $ command &

Pausar un programa en ejecución y ponerlo en background: CTRL + z

Volver a un comando en ejecución $ fg . Lo pone en foreground.

Seguir un programa que está en background: $ bg . Lo deja en background.

Which programs are running in background: $ jobs

Escoger qué programa continuar: # fg %<número>

Cortar la ejecución de un programa en background: kill %<número>

Disable sudo password for a user

sudo visudo, add this line at the end (change “jerome” to your username): jerome ALL=(ALL) NOPASSWD: ALL

Boot process

/var/log/boot.log  ---  System boot log
/var/log/dmesg     ---  print or control the kernel ring buffer
$ dmesg | grep -i memory

Define a proxy

System-wide proxies in CLI Ubuntu/Server must be set as environment variables.

1. Open the /etc/environment file with vi (or your favorite editor). This file stores the system-wide variables initialized upon boot.

2. Add the following lines, modifying appropriately. You must duplicate in both upper-case and lower-case because (unfortunately) some programs only look for one or the other:

    http_proxy="http://myproxy.server.com:8080/"
    https_proxy="http://myproxy.server.com:8080/"
    ftp_proxy="http://myproxy.server.com:8080/"
    no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"
    HTTP_PROXY="http://myproxy.server.com:8080/"
    HTTPS_PROXY="http://myproxy.server.com:8080/"
    FTP_PROXY="http://myproxy.server.com:8080/"
    NO_PROXY="localhost,127.0.0.1,localaddress,.localdomain.com"

apt-get, aptitude, etc. will not obey the environment variables when used normally with sudo. So separately configure them; create a file called 95proxies in /etc/apt/apt.conf.d/, and include the following:

    Acquire::http::proxy "http://myproxy.server.com:8080/";
    Acquire::ftp::proxy "ftp://myproxy.server.com:8080/";
    Acquire::https::proxy "https://myproxy.server.com:8080/";

Finally, logout and reboot to make sure the changes take effect.

Know active IPs on a network

nmap -sP 192.168.1.*
nmap -sn 192.168.1.0/24

will scan the entire .1 to .254 range

Linux console shortcuts

Just to summarise all the answers

Clean up the line: You can use Ctrl+U to clear up to the beginning.
Clean up the line: Ctrl+A Ctrl+K to wipe the current line in the terminal
Cancel the current command/line: Ctrl+C.
Recall the deleted command: Ctrl+Y (then Alt+Y)
Go at the beginning of the line: Ctrl+A
Go at the end of the line: Ctrl+E
Remove the forward words for example, if you are middle of the command: Ctrl+K
Remove characters on the left, until the beginning of the word: Ctrl+W
To clear your entire command prompt: Ctrl + L
Toggle between the start of line and current cursor position: Ctrl + XX

Linux redirection

Redirect stderr to another file:

command > out 2>error

Redirect stderr to stdout (&1), and then redirect stdout to a file:

command >out 2>&1

Redirect both to a file:

command &> out

Change timezone

You can see it with timedatectl.

$ timedatectl

If there is a Failed to create bus connection: No such file or directory problem install dbus: apt-get install dbus.

To change it go to /etc and remove the localtime file

$ cd /etc/
$ rm localtime

Then you can use a file on /usr/share/zoneinfo/ to synchronize:

ln -s /usr/share/zoneinfo/Europe/Madrid localtime

If it does not work you can also change directly the timezone editing the file /etc/timezone and storing the next value:

Europe/Madrid

Grub: Modificar opciones de inicio

1. Editar el fichero ''/etc/default/grub''
2. Modificar la línea de linux: ''GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi=off"''
3. Sobreescribir grub: ''sudo update-grub''

Install mono

$ sudo apt-get install mono-complete

Run several commands at once

$ for((i=1;i<5;i++)); do python produconsumer.py & done

Know your distribution name

alfred@ES07 ~ $ lsb_release -a
No LSB modules are available.
Distributor ID:	LinuxMint
Description:	Linux Mint 18 Sarah
Release:	18
Codename:	sarah
alfred@Y50-70:~$ cat /etc/lsb-release 
DISTRIB_ID=LinuxMint
DISTRIB_RELEASE=19
DISTRIB_CODENAME=tara
DISTRIB_DESCRIPTION="Linux Mint 19 Tara"

Keep reading a file (log) on real time

tail -f <file>

Access to the Network manager log

journalctl -u NetworkManager -r

Mount data from a NFS

sudo mount 10.10.10.10:/volume1/sir-vices ./data

Notes about Mint

Some commands for ubuntu won't work for Mint due it requests the OS distribution name, for example:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

Which lsb_release -cs is translated to sarah (Linux Mint 18 is named Sarah). The correspondent Ubuntu version is xenial so, to make it work:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable"
wiki2/linux_howto.1598372560.txt.gz · Última modificación: 2020/08/25 17:22 (editor externo)