← Back to list

Dicas shell

Coletânea de dicas úteis, para uso no shell (bash)

Bruno Lima · 2024-07-22 22:45 · 0 claps · 5.6 min read
#linux #shell-script
Open on Medium ↗
Wiki topics: 🔓 · Open Source

Dicas shell

Coletânea de dicas úteis, para uso no shell (bash)

Colorir saída (log)

# ccze - A robust log colorizer 
apt-cache search ccze

# Instalar ccze
apt install ccze

# Exemplo de uso
journalctl -f | ccze

Confirmação ao realizar comando de restart ou shutdown

# molly-guard guard against accidental shutdowns/reboots
apt-cache search molly-guard

# instalar molly-guard
apt install molly-guard

Visualizar mais de uma saída de log

# MultiTail - browse through several files at once 
apt-cache search multitail

# instalar multitail
apt install multitail

# uso
multitail -f /var/log/messages /var/log/secure

Data e hora no histórico linux

Inserir a seguinte linha no arquivo .bashrc no diretório home do usuário

# Inserir a linha no profile caso queira que a opção seja global
export HISTTIMEFORMAT="%d-%m-%y %r "
echo 'export HISTTIMEFORMAT="%d-%m-%y %r " ' >> ~/.bashrc

# Forçar gravação após execução a cada comando
echo ‘PROMPT_COMMAND="history -a"’ >> .bashrc

Executar comando remoto em outra máquina usando sshpass

# Instalar sshpass
apt install sshpass

# Definir usuário e senha
SSH_USER='user'
SSH_PASS='pass'
SSH_IP='192.168.0.100'
SSH_COMMAND='cat /etc/fstab'

# Executar sshpass
sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 "$SSH_USER"@"$SSH_IP" "$SSH_COMMAND" > /dev/null 2>&1

Montar diretório remoto usando sshfs

# Instalar sshfs
apt install sshfs

# Realizar montagem
mount -t sshfs user@192.168.100.125:/opt/ /mnt

# Listar diretórios
ls /mnt

Desativar ipv6

# Editar o arquivo
nano /etc/sysctl.conf

# Adicionar as seguintes linhas no arquivo sysctl
# Disable IPv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1

# Aplicar configuração
sysctl -p

Listar arquivos com permissões Suid e Sguid:

# Listar arquivos usando find
find /  -path /proc -prune -o -type f \( -perm -4000 -o -perm -2000 \) -exec ls -l {} \;

Monitorar website — Usando cron

# Monitora site example.com a cada 5 min
*/5 * * * * curl -s -o /dev/null -w "%{http_code}" https://example.com | grep -q "200" || echo "$(date): Website Down" >> /path/to/log/website.log

Gerar senhas aleatórias com entropia de 128

# Gerar palavra
pwmake 128

Usar partições separadas para maior segurança

/(root) 
/boot  
/home  
/tmp 
/var

Forçar rotacionamento de logs:

# Realizar checagem manual do logrotate
logrotate -vdf /etc/logrotate.conf

Inicialização do sistema— systemd

# Analisar o tempo de carregamento
systemd-analyze blame

# 

Gerenciamento de logs — journalctl

# Listar serviço por unidade
journalctl -u sshd

# Listar detalhes
journalctl -xe

# Listar arquivos de log do kernel
journalctl -k

# Listar logs em tempo real
journalctl -f

# Listar tamanho do log
journalctl --disk-usage

# Verificar a consistencia dos logs
journalctl --verify

# Sanitizar os logs
journalctl --vacuum-size 10M

Gerenciamento de serviços — systemctl

# Listar todas a unidades
systemctl list-units

# Listar arquivos das unidades e estado do serviço
systemctl list-unit-files

# Listar serviço de uma unidade
systemctl show sshd

# Exibir configuração da unidade
systemctl cat sshd

# Listar dependências
systemctl list-dependencies sshd

# Listar serviços em execução
systemctl list-units --type=service --state=running

# Listar serviços habilitados
systemctl list-unit-files --type=service --state=enabled

# Listar sockets dos serviços
systemctl list-sockets

Montar diretório na memória -Ramdisk

# Criar diretório
mkdir /mnt/ramdisk

# Realizar montagem
mount -t tmpfs -o rw,size=2G tmpfs /mnt/ramdisk

Impedir script de rodar caso já esteja em execução

pidof -o %PPID -x "$(basename "$0")" > /dev/null && { echo "Script is already running"; exit 1; }

Comandos ip

# Adicionar ip na interface
ip address add 192.168.1.100/24 dev eth0

# Deletar ip na interface
ip address del 192.168.1.100/24 dev eth0

# Ativar interface
ip link set eth0 up

# Desativar interface
ip link set eth0 down

# Alterar mtu
ip link set eth0 mtu 1500

# Ativar captura de pacotes
ip link set eth0 promisc on

# Definir rota padrão
ip route add default via 192.168.1.1

# Definir rota estática
ip route add 172.16.0.0/16 via 192.168.1.254

# Definir rota estática escolhendo uma interface
ip route add 192.168.2.0/24 via 192.168.1.1 dev eth0

# Deletar uma rota
ip route del 172.16.0.0/16 via 192.168.1.254

# Exibir rota
ip route show

Remover comentários de arquivos

# Remover linhas com comentários
grep -vE '^(\s*#|\s*$)' arquivo

Verificar o tipo de arquivo

# Verificar o tipo de arquivo
file -b --mime-type arquivo

Enviar mensagem para usuário logado no sistema

# write <usuário> <número do tty>, usar em conjunto com o comando who
write root tty1

Receber alerta sobre algum evento de erro ocorrido no log do sistema

tail -f /var/log/syslog | grep --line-buffered 'ERROR' | while read line; do echo "$line" | mail -s "Syslog Error Alert" admin@example.com; done

Listar arquivos maiores que um tamanho especifico

find / -type f -exec du -h {} + | sort -rh | head -n 10

# Deletar arquivos maiores que 100M
find /tmp/ -type f -size +100M -exec rm -i {} \;

Links de referência:

[embed]23 CentOS Server Hardening Security Tips - Part 2 Continuing the previous tutorial on how to secure CentOS 8/7, in this article we'll discuss other security tips that…www.tecmint.com

https://www.tecmint.com/security-and-hardening-centos-7-guide

[embed]Proxmox Cheatsheet This all based on my experiencemedium.com

[embed]ESXi Cheatsheet Complete cheatsheet to easier ESXi managementmedium.com

[embed]How to Deploy GlusterFS with Proxmox VE You can deploy this service as alternative from CEPHmedium.com

[embed]Dynamic IP Solutions — Duck DNS Setup My home server’s public IP address changes over time. Therefore, I decided to use the DDNS service to track my server’s…medium.com

[embed]Text Processing with AWK in Linux/Unix with examples awk is a powerful programming language and command-line utility for pattern scanning and processing. It is commonly…medium.com

[embed]Boosting Linux Storage Performance with LVM Striping medium.com

[embed]How to Create a Systemd Service in Linux Systemd is a system and service manager for Linux operating systems, which has become the default initialization system…medium.com

[embed]Commandline Auditing — Using different tools to security your Linux server and environments. By deault Linux does not offer or have any commandline auditing or logging so you never know who did what, where, when…medium.com

[embed]lsof I’m used to debugging issues with logs or metrics when they are presented to me on a lovely dashboard with an intuitive…copyconstruct.medium.com

[embed]GitHub - Nyr/openvpn-install: OpenVPN road warrior installer for Ubuntu, Debian, AlmaLinux, Rocky… OpenVPN road warrior installer for Ubuntu, Debian, AlmaLinux, Rocky Linux, CentOS and Fedora - Nyr/openvpn-installgithub.com

[embed]openvpn-install/openvpn-install.sh at master · angristan/openvpn-install Set up your own OpenVPN server on Debian, Ubuntu, Fedora, CentOS or Arch Linux. - openvpn-install/openvpn-install.sh at…github.com

[embed]GitHub - angristan/wireguard-install: WireGuard VPN installer for Linux servers WireGuard VPN installer for Linux servers. Contribute to angristan/wireguard-install development by creating an account…github.com

[embed]OpnSense Firewall: Configure GeoIP Groups for conditional blocking and network security If we want to control which countries we are allow to connect to or connect in we need a GeoIP list. In this case we…medium.com

[embed]SELinux — Part 1 This article is an introduction to SELinux in Red Hat or CentOS distributions. I will publish deeper articles about…medium.com

[embed]Linux: Make your scripts safe, don't run a script if an instance of the script is already run Assume the following scenario, you have created a script that does log analysis and writes results in files, but the…lovethepenguin.com

[embed]Cleaning Up and Managing Linux Journal Logs In the world of Linux system administration, efficient log management is crucial to maintaining system health and…medium.com

https://filterlists.com/

[embed]Unlock the full potential of Pihole Foreword: I’m fascinated by technology and I wanted to share my findings while expirementing with Pihole. I’m not…obutterbach.medium.com

[embed]How To Set Up an NFS Server Using Block Storage Introductionmedium.com

[embed]Linux Directory Structure Detailed Working of Linux Directory Structuredheeruthedeployer.medium.com

[embed]Installing Portainer: Your Docker Control Center Portainer in Proxmox LXC!harish2k01.medium.com

https://www.cyberciti.biz/tips/linux-security.html

[embed]How To Install Netdata On Rocky Linux 9 Netdata is an Open Source real-time server monitoring tool. It collects real-time data like CPU usage, RAM usage, Load…wiki.crowncloud.net

[embed]GitHub - kpatronas/curlify: The lovechild of inotify and curl: Perform an http request to a url in… The lovechild of inotify and curl: Perform an http request to a url in case of a file-system event - kpatronas/curlifygithub.com

[embed]Understanding and Modifying Shell Options in Linux What are Linux Shell Optionsmedium.com

[embed]GitHub - albddnbn/proxmox-ve-utility-scripts: Collection of shell scripts to maximize efficiency… Collection of shell scripts to maximize efficiency when using Proxmox VE. - albddnbn/proxmox-ve-utility-scriptsgithub.com

[embed]David Varghese - Medium Read writing from David Varghese on Medium. Cybersecurity Student | Digital Forensics | Security Analyst | Software…david-varghese.medium.com

[embed]Conditions in bash scripting (if statements) Introductionmedium.com

[embed]Linux Directory Structure Detailed Working of Linux Directory Structuredheeruthedeployer.medium.com

[embed]Network Scanning 101 Discover Host, OS and other Information through Nmap and Metasploitmedium.com

[embed]My Notes for Understanding the Linux Boot Process: A Comprehensive Guide The Linux boot process is a complex sequence of events that transforms a powered-off machine into a fully operational…medium.com

[embed]Web Check - X-Ray Vision for any Website Web Check is the all-in-one OSINT and security tool, for revealing the inner workings of any websiteweb-check.as93.net


메타데이터
post_id
c533c1a33a73
slug
dicas-shell-c533c1a33a73
url
https://medium.com/@lctec/dicas-shell-c533c1a33a73
canonical_url
https://medium.com/@lctec/dicas-shell-c533c1a33a73
author_url
https://medium.com/@lctec
status
ok
fetched_at
2026-06-12 18:14:10