Files
linux/README.md
2023-09-28 21:37:16 +01:00

23 KiB
Raw Blame History

Linux

comands


# OS information
hostnamectl

#get hostname
hostname

#system update

sudo apt update && sudo apt upgrade -y && sudo apt autoremove -y

Segurança Manutenção de Utilizadores A manutenção de utilizadores é uma tarefa de administração, assim sendo deverá ser usado um utilizador administrador ou então o comando sudo.

Criar Utilizador useradd USERNAME O comando ao ser invocado o sistema terá em conta a definição do ficheiro /etc/default/useradd (o que pode variar de destribuição para destribuição).

Normalmente o sistema cria automaticamente um grupo com o mesmo nome do utilizador.

Eliminar utilizador userdel USERNAME Se for para eliminar a home directory automaticamente

useradd -r USERNAME Mudar palavra chave Do utilizador que executa o comando

passwd De outro utilizador

passwd USERNAME Manutenção de Grupos Listar Grupos groups Criar Grupo groupadd GROUPNAME Eliminar Grupo groupdel GROUPNAME Relação Utilizadores Grupos Listar Grupos do Utilizador groups USERNAME Adiciona Utilizador a um Grupo usermod -a -G GROUPNAME USERNAME Remove Utilizador de Grupo deluser USERNAME GROUPNAME Alterar Grupo Principal do Utilizador usermod -g GROUPNAME USERNAME Mudar Owner chown [-c|--changes] [-v|--verbose] [-f|--silent|--quiet] [--dereference] [-h|--no-dereference] [--preserve-root] [--from=currentowner:currentgroup] [--no-preserve-root] [-R|--recursive] [--preserve-root] [-H] [-L] [-P] {new-owner|--reference=ref-file} file ... user The name of the user to own the file. In this form, the colon (":") and the group is omitted. The owning group is not altered.

user:group The user and group to own the file, separated by a colon, with no spaces in between.

group The group to own the file. In this form, user is omitted, and the group must be preceded by a colon. user: If group is omitted, but a colon follows user, the owner is changed to user, and the owning group is changed to the login group of user.

Specifying a colon with no user or group is accepted, but ownership will not be changed. This form does not cause an error, but changes nothing. #Exemplo: sudo chown -R username:group folder sudo adicionar ao grupo sudo usermod -aG sudo nomedoutilizador Redes Mudar o nome editar o hostname

sudo nano /etc/hostname #alterar o nome sudo nano /etc/hosts #alterar o nome Static IP A configuração para um ip estático poderá ser um pouco diferente de destribuição para distribuição mas a lógica é similar

Debian sudo nano /etc/network/interfaces Exemplo de configuração

neste exemplo de configuração a place de rede tem o nome enxd0374555c1f8

This file describes the network interfaces available on your system

and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

The loopback network interface

auto lo iface lo inet loopback

The primary network interface

allow-hotplug enxd0374555c1f8 iface enxd0374555c1f8 inet static address 192.168.0.2 netmask 255.255.255.0 gateway 192.168.0.1 dns-nameservers 89.207.128.252 89.207.130.252 Reiniciar configuração sem reboot de computador

sudo /etc/init.d/networking restart Gestão de Discos Uso e Espaço disponível df -H Listar discos e partições lsblk Gestão de partições sudo fdisk /dev/NOMEDISCO(resultado do lsblk)

Exemplo:

sudo fdisk /dev/sdc e seguir o wizard

Partições como mais de 2 TB sudo parted /dev/sdc (parted) mklabel gpt #alterar para a unidade de medida que desejar (parted) unit TB #ver espaço livre (parted) print free #criar partição com espaço livre (exemplo:4 Teras) mkpart primary ext4 0 4 Formatar uma partição Ext4 mkfs.ext4 /dev/sdb1 Ext3 mkfs.ext3 /dev/sdb1 exFat sudo mkfs.exfat /dev/sdc1 NTFS sudo apt-get install ntfs-3g sudo mkntfs --fast --label Backups /dev/sdc1 Visualizar ids de partição blkid /dev/sdc1 Mount de discos no arranque sudo nano /etc/fstab #adicionar/editar linha como pretendido PARTUUID=PARTUUIDQueBlkidDevolveu DirectorioOndeMontar ext4 defaults,nofail 0 02 mount de tudo o que está no fstab mas não esteja ainda montado (util para testar o fstab sem reboot)

mount -a

Manutenção de discos Bad Sectors sudo e2fsck -cfpv /dev/sda1 O Exemplo foi com o disco sda1 mas deverá ser subsituido pelo disco desejado

Os parâmetros têm os seguintes significados:

“c” procura por blocos defeituosos e os adiciona à lista

“f” força uma verificação no sistema de arquivos

“p” repara qualquer coisa que possa ser reparada com segurança

“v” está no modo detalhado. você pode ver o progresso do comando

Esse comando pode levar muito tempo para ser executado, até várias horas em uma unidade particularmente grande.

Compressão A utilização o comando tar é uma das formas de comprimir no linux

sudo tar -cvf --exclude='.cache' --exclude='Cache' --exclude='.cache' --exclude='.tmp' --exclude='tmp' /tmp/nomedoficheiro.tar.gz /PATHPARAFICEHIROOUDIRECTORIO Caso seja necessário paralelismo

sudo tar -I pigz -cvf - /fileserver/media/music/* Se for necessário limitar o tamanho do ficheiro compresso (dividindo em multiplos ficheiros)

sudo tar -I pigz -cvf - /sourcefolder/* | split --bytes=8GB - /tmp/file.tar.gz SSH para executar comandos por ssh que usem o display do servidor, começar por executar:

export DISPLAY=:0 screen Para mais informações como manter o comando a executar mesmo que termine a sessão de ssh consultar:Screen

sem password criar chaves (publica e privada) no cliente

ssh-keygen -t ecdsa -b 521 Se for necessário controlar o nome do ficheiro

#substituir ~/.ssh/id_ecdsa/mf-key-ecdsa com o path de destino e o nome pretendido

o directório tem que existir, por isso se não existir:

mkdir ~/ssh/id_ecdsa

ssh-keygen -t ecdsa -b 521 -f ~/.ssh/mf-key-ecdsa copiar a chave para o servidor

ssh-copy-id -i ~/.ssh//mf-key-ecdsa.pub example_user@192.0.2.4 testar o ssh para ver se funcionou (ou seja não pede a password)

ssh example_user@192.0.2.4 se pedir a password e indicar algo semelhante a It is required that your private key files are NOT accessible by others. será necessario rever as permissões do ficheiro indicado na informação Exemplo:

chmod g-rwx,o-rwx ~/.ssh/mf-key-ecdsa Para adicionar o chave existente no ssh-agent (só necessario se a chave privada for copiada de outro sitio)

eval ssh-agent ssh-add pathenomedoficheiro

Caso o servidor de SSH seja em windows e necessario alterara segraunça do authorized_keys

get-acl c:\ProgramData\ssh\ssh_host_dsa_key | set-acl C:\Users[username].ssh\authorized_keys Bash Comentários #simbolo para comentário todos os scripts devem começar com #!/bin/bash Condições if Sintaxe global

if ; then fi Pode parecer estranho mas no bash a condição é avaliada no uso de uma função "test"

if test $variavel -eq 3; then echo fi outra forma de uso da função "test" através dos parenteses retos []

if [ $variavel -eq 3 ]; then echo fi #maxima atenção aos espaços (tem mesmo que existir um espaço) entre o conteúdo e os parenteses. Lógica - Negação

if [ ! $variavel -eq 3 ]; then echo fi #maxima atenção aos espaços (tem mesmo que existir um espaço) entre o conteúdo e os parenteses. Lógica - and (-a) or (-o)

if [ $variavel -eq 3 -a $variavel -eq 2 -o $variavel -eq 1]; then echo fi #maxima atenção aos espaços (tem mesmo que existir um espaço) entre o conteúdo e os parenteses. tabela de condições (rever) (copiado de linux academy)

  1. File-based conditions: Condition True if Example/explanation [ -a existingfile ] file existingfile exists. if [ -a tmp.tmp ]; then rm -f tmp.tmp # Make sure were not bothered by an old temporary file fi [ -b blockspecialfile ] file blockspecialfile exists and is block special. Block special files are special kernel files found in /dev, mainly used for ATA devices like hard disks, cd-roms and floppy disks. if [ -b /dev/fd0 ]; then dd if=floppy.img of=/dev/fd0 # Write an image to a floppy fi [ -c characterspecialfile ] file characterspecialfile exists and is character special. Character special files are special kernel files found in /dev, used for all kinds of purposes (audio hardware, ttys, but also /dev/null). if [ -c /dev/dsp ]; then cat raw.wav > /dev/dsp # This actually works for certain raw wav files fi [ -d directory ] file directory exists and is a directory. In UNIX-style, directories are a special kind of file. if [ -d ~/.kde ]; then echo “You seem to be a kde user.” fi [ -e existingfile ] file existingfile exists. (same as -a, see that entry for an example) [ -f regularfile ] file regularfile exists and is a regular file. A regular file is neither a block or character special file nor a directory. if [ -f ~/.bashrc ]; then source ~/.bashrc fi [ -g sgidfile ] file sgidfile exists and is set-group-ID. When the SGID-bit is set on a directory, all files created in that directory will inherit the group of the directory. if [ -g . ]; then echo “Created files are inheriting the group $(ls -ld . | awk { print $4 }) from the working directory.” fi [ -G fileownedbyeffectivegroup ] file fileownedbyeffectivegroup exists and is owned by the effective group ID. The effective group id is the primary group id of the executing user. if [ ! -G file ]; then # An exclamation mark inverts the outcome of the condition following it chgrp $(id -g) file # Change the group if its not the effective one fi [ -h symboliclink ] file symboliclink exists and is a symbolic link. if [ -h $pathtofile ]; then pathtofile=$(readlink -e $pathtofile) # Make sure $pathtofile contains the actual file and not a symlink to it fi [ -k stickyfile ] file stickyfile exists and has its sticky bit set. The sticky bit has got quite a history, but is now used to prevent world-writable directories from having their contents deletable by anyone. if [ ! -k /tmp ]; then # An exclamation mark inverts the outcome of the condition following it echo “Warning! Anyone can delete and/or rename your files in /tmp!” fi [ -L symboliclink ] file symboliclink exists and is a symbolic link. (same as -h, see that entry for an example) [ -N modifiedsincelastread ] file modifiedsincelastread exists and was modified after the last read. if [ -N /etc/crontab ]; then killall -HUP crond # SIGHUP makes crond reread all crontabs fi [ -O fileownedbyeffectiveuser ] file fileownedbyeffectiveuser exists and is owned by the user executing the script. if [ -O file ]; then chmod 600 file # Makes the file private, which is a bad idea if you dont own it fi [ -p namedpipe ] file namedpipe exists and is a named pipe. A named pipe is a file in /dev/fd/ that can be read just once. See my bash tutorial for a case in which its used. if [ -p $file ]; then cp $file tmp.tmp # Make sure well be able to read file=”tmp.tmp” # the file as many times as we like fi [ -r readablefile ] file readablefile exists and is readable to the script. if [-r file ]; then content=$(cat file) # Set $content to the content of the file fi [ -s nonemptyfile ] file nonemptyfile exists and has a size of more than 0 bytes. if [ -s logfile ]; then gzip logfile # Backup the old logfile touch logfile # before creating a fresh one. fi [ -S socket ] file socket exists and is a socket. A socket file is used for inter-process communication, and features an interface similar to a network connection. if [ -S /var/lib/mysql/mysql.sock ]; then mysql socket=/var/lib/mysql/mysql.sock # See this MySQL tip fi [ -t openterminal ] file descriptor openterminal exists and refers to an open terminal. Virtually everything is done using files on Linux/UNIX, and the terminal is no exception. if [ -t /dev/pts/3 ]; then echo -e “nHello there. Message from terminal $(tty) to you.” > /dev/pts/3 # Anyone using that terminal will actually see this message! fi [ -u suidfile ] file suidfile exists and is set-user-ID. Setting the suid-bit on a file causes execution of that file to be done with the credentials of the owner of the file, not of the executing user. if [ -u executable ]; then echo “Running program executable as user $(ls -l executable | awk { print $3 }).” fi [ -w writeablefile ] file writeablefile exists and is writeable to the script. if [ -w /dev/hda ]; then grub-install /dev/hda fi [ -x executablefile ] file executablefile exists and is executable for the script. Note that the execute permission on a directory means that its searchable (you can see which files it contains). if [ -x /root ]; then echo “You can view the contents of the /root directory.” fi [ newerfile -nt olderfile ] file newerfile was changed more recently than olderfile, or if newerfile exists and olderfile doesnt. if [ story.txt1 -nt story.txt ]; then echo “story.txt1 is newer than story.txt; I suggest continuing with the former.” fi [ olderfile -ot newerfile ] file olderfile was changed longer ago than newerfile, or if newerfile exists and olderfile doesnt. if [ /mnt/remote/remotefile -ot localfile ]; then cp -f localfile /mnt/remote/remotefile # Make sure the remote location has the newest version of the file, too fi [ same -ef file ] file same and file file refer to the same device/inode number. if [ /dev/cdrom -ef /dev/dvd ]; then echo “Your primary cd drive appears to read dvds, too.” fi

  2. String-based conditions: Condition True if Example/explanation [ STRING1 == STRING2 ] STRING1 is equal to STRING2. if [ “$1” == “moo” ]; then echo $cow # Ever tried executing apt-get moo? fiNote: you can also use a single “=” instead of a double one. [ STRING1 != STRING2 ] STRING1 is not equal to STRING2. if [ “$userinput” != “$password” ]; then echo “Access denied! Wrong password!” exit 1 # Stops script execution right here fi [ STRING1 > STRING2 ] STRING1 sorts after STRING2 in the current locale (lexographically). The backslash before the angle bracket is there because the bracket needs to be escaped to be interpreted correctly. As an example we have a basic bubble sort: (Dont feel ashamed if you dont understand this, it is a more complex example) array=( linux tutorial blog ) swaps=1 while (( swaps > 0 )); do swaps=0 for (( i=0; i < (( ${#array[@]} 1 )) ; i++ )); do if [ “${array[$i]}” > “${array[$(( i + 1 ))]}” ]; then # Here is the sorting condition tempstring=${array[$i]} array[$i]=${array[$(( i + 1 ))]} array[$(( i + 1 ))]=$tempstring (( swaps=swaps + 1 )) fi done done echo ${array[@]} # Returns “blog linux tutorial” [ STRING1 < STRING2 ] STRING1 sorts before STRING2 in the current locale (lexographically). [ -n NONEMPTYSTRING ] NONEMPTYSTRING has a length of more than zero. This condition only accepts valid strings, so be sure to quote anything you give to it. if [ -n “$userinput” ]; then userinput=parse($userinput) # Only parse if the user actually gave some input. fi Note that you can also omit the “-n”, as brackets with just a string in it behave the same. [ -z EMPTYSTRING ] EMPTYSTRING is an empty string. This condition also accepts non-string input, like an uninitialized variable: if [ -z $uninitializedvar ]; then uninitializedvar=”initialized” # -z returns true on an uninitialized variable, so we initialize it here. fi Double-bracket syntax only: STRING1 =~ REGEXPATTERN STRING1 matches REGEXPATTERN. If you are familiar with Regular Expressions, you can use this conditions to perform a regex match. if ; then echo “$email contains a valid e-mail address.” fi

  3. Arithmetic (number-based) conditions: Condition True if Example/explanation [ NUM1 -eq NUM2 ] NUM1 is EQual to NUM2. These conditions only accept integer numbers. Strings will be converted to integer numbers, if possible. Some random examples: if [ ? -eq 0 ]; then # ? returns the exit status of the previous command echo “Previous command ran succesfully.” fi if [ $(ps -p $pid -o ni=) -ne $(nice) ]; then echo “Process $pid is running with a non-default nice value” fi if [ $num -lt 0 ]; then echo “Negative numbers not allowed; exiting…” exit 1 fi [ NUM1 -ne NUM2 ] NUM1 is Not Equal to NUM2. [ NUM1 -gt NUM2 ] NUM1 is Greater Than NUM2. [ NUM1 -ge NUM2 ] NUM1 is Greater than or Equal to NUM2. [ NUM1 -lt NUM2 ] NUM1 is Less Than NUM2. [ NUM1 -le NUM2 ] NUM1 is Less than or Equal to NUM2. 4. Miscellaneous conditions: Condition True if Example/explanation [ -o shelloption ] shell option shelloption is enabled. Shell options modify the behaviour of bash, except a few unmodifiable ones that indicate the shell status. if [ ! -o checkwinsize ] # An exclamation mark inverts the outcome of the condition following it echo “Shell option checkwinsize is disabled; enabling it so you can resize you terminal window without problems.” shopt -s checkwinsize # This shell option is modifiable fi if [ -o login_shell ]; then echo “This a a login shell.” # This shell option is not modifiable

fi With the double-parenthesis syntax, you can use the following conditions:

  1. Double-parenthesis syntax conditions: Condition True if Example/explanation (( NUM1 == NUM2 )) NUM1 is equal to NUM2. These conditions only accept integer numbers. Strings will be converted to integer numbers, if possible. Some random examples: if (( ? == 0 )); then # ? returns the exit status of the previous command echo “Previous command ran succesfully.” fi if (( $(ps -p $pid -o ni=) != $(nice) )); then echo “Process $pid is running with a non-default nice value” fi if (( $num < 0 )); then echo “Negative numbers not allowed; exiting…” exit 1 fi (( NUM1 != NUM2 )) NUM1 is not equal to NUM2. (( NUM1 > NUM2 )) NUM1 is greater than NUM2. (( NUM1 >= NUM2 )) NUM1 is greater than or equal to NUM2. (( NUM1 < NUM2 )) NUM1 is less than NUM2. (( NUM1 <= NUM2 ))

Funções e Argumentos os argumentos numa função acedem-se por "$@" da mesma forma que os argumentos de input do script.

O exemplo seguinte demonstra o descrito. Estou a invocar a função echoArguments enviando como parâmetro os argumentos de input do script. Caso chama-se a função sem o $@ a função não iria receber parâmetros.

Conclusão: O uso do $@ é sempre relativo ao contexto do código, dentro de uma função é relativo aos parâmetros da função, fora da função relativo ao input do script

#!/bin/bash

function echoArguments(){ echo "printing ($#) arguments" for ARGUMENT in "$@" do echo $ARGUMENT done } echoArguments $@ Também é possível aceder por índice

#!/bin/bash

function echoArguments(){ echo "$0" echo "$1" } echoArguments $@ Testar se um programa está a correr if pgrep jivelite>/dev/null then echo "a correr" else echo "nao esta correr" fi verifica o numero de parametros cuidado tem que ter mesmo os espaços nos parenteses rectos

if [ "$#" -ne 2 ] then echo "wrong number of parameters($#)" echo "0 - name of processo to search" echo "1 - commando to start" exit 1 fi Parameter Expansion (rever) Parameter Expansion is the term that refers to any operation that causes a parameter to be expanded (replaced by content). In its most basic appearance, the expansion of a parameter is achieved by prefixing that parameter with a $ sign. In certain situations, additional curly braces around the parameter's name are required:

$ echo "'$USER', '$USERs', '${USER}s'" 'lhunath', , 'lhunaths' This example illustrates what basic parameter expansions (PE) look like. The second PE results in an empty string. That's because the parameter USERs is empty. We did not intend to have the s be part of the parameter name. Since there's no way Bash could know you want a literal s appended to the parameter's value, you need to use curly braces to mark the beginning and end of the parameter name. That's what we do in the third PE in our example above.

Parameter Expansion also gives us tricks to modify the string that will be expanded. These operations can be terribly convenient:

$ for file in .JPG .jpeg do mv -- "$file" "${file%.}.jpg" done The code above can be used to rename all JPEG files with a .JPG or a .jpeg extension to have a normal .jpg extension. The expression ${file%.} cuts off everything from the end starting with the last period (.). Then, in the same quotes, a new extension is appended to the expansion result.

Here's a summary of most of the PE tricks that are available:

Syntax

Description

${parameter:-word}

Use Default Value. If 'parameter' is unset or null, 'word' (which may be an expansion) is substituted. Otherwise, the value of 'parameter' is substituted.

${parameter:=word}

Assign Default Value. If 'parameter' is unset or null, 'word' (which may be an expansion) is assigned to 'parameter'. The value of 'parameter' is then substituted.

${parameter:+word}

Use Alternate Value. If 'parameter' is null or unset, nothing is substituted, otherwise 'word' (which may be an expansion) is substituted.

${parameter:offset:length}

Substring Expansion. Expands to up to 'length' characters of 'parameter' starting at the character specified by 'offset' (0-indexed). If ':length' is omitted, go all the way to the end. If 'offset' is negative (use parentheses!), count backward from the end of 'parameter' instead of forward from the beginning. If 'parameter' is @ or an indexed array name subscripted by @ or *, the result is 'length' positional parameters or members of the array, respectively, starting from 'offset'.

${#parameter}

The length in characters of the value of 'parameter' is substituted. If 'parameter' is an array name subscripted by @ or *, return the number of elements.

${parameter#pattern}

The 'pattern' is matched against the beginning of 'parameter'. The result is the expanded value of 'parameter' with the shortest match deleted. If 'parameter' is an array name subscripted by @ or *, this will be done on each element. Same for all following items.

${parameter##pattern}

As above, but the longest match is deleted.

${parameter%pattern}

The 'pattern' is matched against the end of 'parameter'. The result is the expanded value of 'parameter' with the shortest match deleted.

${parameter%%pattern}

As above, but the longest match is deleted.

${parameter/pat/string}

Results in the expanded value of 'parameter' with the first (unanchored) match of 'pat' replaced by 'string'. Assume null string when the '/string' part is absent.

${parameter//pat/string}

As above, but every match of 'pat' is replaced.

${parameter/#pat/string}

As above, but matched against the beginning. Useful for adding a common prefix with a null pattern: "${array[@]/#/prefix}".

${parameter/%pat/string}

As above, but matched against the end. Useful for adding a common suffix with a null pattern.

Exemplos de comandos para executar um backup

Backups sudo tar -cvpzf "/vault/.backups/devices/homeserver/tar/backup_$(date +"%Y%m%d%H%M%S").tar.gz
--exclude=/proc
--exclude=/tmp
--exclude=/mnt
--exclude=/dev
--exclude=/sys
--exclude=/run
--exclude=/media
--one-file-system
/ Aceder a shares do windows (samba) Para mais informações consulte a página Smbclient

Benchmarking Discos sudo apt install hdparm sudo hdparm -Tt /dev/sdc