Herramientas de usuario

Herramientas del sitio


wiki2:linux_howto

Linux how tos

Find and prepare new hard-disks

On modern udev installations, there are symbolic links to storage media in subdirectories of /dev/disk, that let you look up a disk or a partition by serial number (/dev/disk/by-id/), by UUID (/dev/disk/by-uuid), by filesystem label (/dev/disk/by-label/) or by hardware connectivity (/dev/disk/by-path/).

Linux also provides the lsblk utility which displays a nice tree view of the storage volume.

To prepare:

mkdir -p /mnt/vdb
mkfs.ext4 /dev/vdb
mount /dev/vdb /mnt/vdb

Services

List services

pstree
service --status-all

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 that 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"

Find those files that contain "X" and "Y"

# Being X = "'pending': False,"
# Being Y = "'program_id': 'sps_lease'"
grep -rl '.' -e "'pending': False," | xargs grep -l -e "'program_id': 'sps_lease'"

Search only in some files with extension...

grep -rn '/home/alfred/Workspaces' --include \*.py --include \*.pyc -e 'bcrypt'

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.

How to create a ram disk

There are two available types:

  • ramfs file systems cannot be limited in size like a disk base file system which is limited by it’s capacity. ramfs will continue using memory storage until the system runs out of RAM and likely crashes or becomes unresponsive. This is a problem if the application writing to the file system cannot be limited in total size. Another issue is you cannot see the size of the file system in df and it can only be estimated by looking at the cached entry in free.
  • tmpfs is a more recent RAM file system which overcomes many of the drawbacks with ramfs. You can specify a size limit in tmpfs which will give a ‘disk full’ error when the limit is reached. This behaviour is exactly the same as a partition of a physical disk.

To mount a disk:

mount -t tmpfs -o size=512m tmpfs /mnt/ramdisk
mount -o size=16G -t tmpfs none /mnt/tmpfs

mount -t [TYPE] -o size=[SIZE] [FSTYPE] [MOUNTPOINT]. [TYPE] is the type of RAM disk to use; either tmpfs or ramfs. [SIZE] is the size to use for the file system. Remember that ramfs does not have a physical limit and is specified as a starting size. [FSTYPE] is the type of RAM disk to use; either tmpfs, ramfs, ext4, etc.

You can also edit the fstab file:

tmpfs       /mnt/ramdisk tmpfs   nodev,nosuid,noexec,nodiratime,size=1024M   0 0
tmpfs    /home/szymon/ramdisk    tmpfs    rw,size=512M,mode=777 0    0

You can also use SquashFS. SquashFS is intended for general read-only file system use and in constrained block device/memory systems (e.g. embedded systems) where low overhead is needed. The standard version of SquashFS uses gzip compression, although there is also a project that brings LZMA compression to SquashFS. Install squasfsh tools:
sudo apt-get install squashfs-tools
Create .sqsh file:
mksquashfs /usr/lib/jvm/java-6-sun-1.6.0.21 /home/nancom/jdk6.sqsh
Unsquash:
unsquashfs [options] target [files/directories to extract] $shell > sudo mount /home/nancom/jdk6.sqsh /media/ramdisk -t squashfs -o loop sudo update-alternatives –install “/usr/bin/java” “java” “/media/ramdisk/bin/java” 1 Check install java complete sudo update-alternatives –config java
!! And choose java in ram !! !! Finish !! !! Make it permanant on startup !! Edit /etc/fstab add line: /home/nancom/jdk6.sqsh /media/ramdisk squashfs ro,defaults,loop 0 0

MessageBox

Yes and no questions

if zenity --question --text="What do you choose?"; then
    zenity --info --text="You pressed \"Yes\"!"
else
    zenity --info --text="You pressed \"No\"!"
fi

<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

Update system Certificate Authority

sudo apt-get install apt-transport-https ca-certificates -y
sudo update-ca-certificates

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.txt · Última modificación: 2022/05/09 09:41 (editor externo)