Mostrando postagens com marcador Linux. Mostrar todas as postagens
Mostrando postagens com marcador Linux. Mostrar todas as postagens

Command ip examples

 
# Forcefully close a connection to a specific destination
sudo ss -K dst 192.168.1.100

# view routes
ip r
ip route

# To reject a route (block traffic to an IP)
ip route add unreachable 74.1.1.0/24
ip route del unreachable 74.1.1.0/24

  
# add route 
sudo ip route add {NETWORK/MASK} via {GATEWAYIP}
sudo ip route add {NETWORK/MASK} dev {DEVICE}
sudo ip route add default {NETWORK/MASK} dev {DEVICE}
sudo ip route add default {NETWORK/MASK} via {GATEWAYIP}

# Here is another example where I am setting up route for my VPN gateway:
ip link set dev tun0 up mtu 1500
ip addr add dev tun0 10.8.0.2/24 broadcast 10.8.0.255
ip route add 139.59.2.125/32 via 192.168.2.254
ip route add 0.0.0.0/1 via 10.8.0.1
ip route add 128.0.0.0/1 via 10.8.0.1


Edit config file such as /etc/sysconfig/network-scripts/route-eth0 on a CentOS/RHEL/Fedora Linux for interface eth0 using a text editor such as nano command or vim command:
vim /etc/sysconfig/network-scripts/route-eth0

Append the following text:
172.10.1.0/24 via 10.0.0.100 dev eth0

Save and exit (close) the file in a vim text editor. Finally, restart your network service on a CentOS/RHEL/Fedora Linux so they take effect:
systemctl restart network.service



A note about ip command and persistence static routing on a Debian/Ubuntu

Edit your /etc/network/interfaces file for say eth0:
vi /etc/network/interfaces

Update it as follows:

auto eth0
iface eth0 inet static
address 192.168.1.2
netmask 255.255.255.0
gateway 192.168.1.254
## static ip config START ##
up /sbin/ip route add 172.10.1.0/24 via 10.8.0.1 dev eth0
down /sbin/ip route delete 172.10.1.0/24 via 10.8.0.1 dev eth0
## static ip config END ##


## How to find the route used for an destination IP

The syntax is as follows:
ip route get to {IPv4_address_here}
ip route get to {IPv6_address_here}
ip route get to 172.66.43.74

Outputs indicating that 172.66.43.74 can be reached via the wg0 interface with 192.168.13.4 as source IP:

172.66.43.74 dev wg0 table 51832 src 192.168.13.4 uid 1000 
    cache 

Schedule a Linux reboot

 

Schedule a Linux reboot using shutdown -r <time>  

for one-time events, or crontab -e for recurring reboots. 

Common methods include sudo shutdown -r +60 (in 60 mins),  

sudo shutdown -r 02:00 (at 2 AM), 

 Use "shutdown -c" to cancel reboot 

or adding 0 3 * * * /sbin/shutdown -r now to crontab for daily 3 AM reboots


Export netflow from linux server

 
https://github.com/irino/softflowd

pico /etc/systemd/system/softflowd.service

[Unit]
Description=Softflowd exporter
After=network.target


[Service]
ExecStart=softflowd -i ens160 -v 9 -s 1 -t maxlife=1 -t general=15 -d -n 10.25.10.59:9996
Restart=always
User=root
Group=root

[Install]
WantedBy=default.target



Fix netplan gateway4 deprecated

 

            routes:
                - to: default
                  via: 192.168.10.1
 

example:                  
network:
  version: 2
  renderer: networkd
  ethernets:
    eno1:
      dhcp4: false
      dhcp6: false
     addresses:
      - 192.168.10.10/24
     routes:
      - to: default
        via: 192.168.10.1

     nameservers:
       addresses: [192.168.10.1]

Fix permissions:
chmod 600 /etc/netplan/your_config_file.yaml 

 

 

Criando partição com parted

 

parted  /dev/sdb

(parted) select /dev/sdb

(parted) print

 CRIANDO UMA PARTIÇÃO NO DISCO SELECIONADO (/dev/sdb)

Passo 1: Primeiramente, vamos criar um label (tabela de partições) do tipo desejado no disco. Como exemplo usaremos gpt.

 (parted) mklabel gpt

 Passo 2: Criaremos a partição com o comando “mkpart”.

 (parted) mkpart primary ext4 0% -1

 Primary -> aqui definimos o tipo de partição, podendo ser primária, estendida ou uma unidade lógica.

Ext4 -> definimos o tipo de sistema de arquivos a usar. Podemos escolher entre fat16, fat32, ext2, ext3, HFS, linux- swap, NTFS, reiserfs ou ufs.

0% -> local onde a partição inicia no disco.

-1 -> local onde a partição terminará.

A partição ainda não foi formatada. Especificar a opção ext4 para o sistema de arquivos apenas configura o ID correto para o sistema de arquivos que será utilizado.

De forma a finalizar a partição, necessitamos sair do parted com o comando “quit”, e então formatar a partição com o utilitário mkfs.ext4

(parted) quit

# mkfs.ext4 /dev/sdb1

 Adicionar o ponto de montagem em /etc/fstab

 

Increase linux disk size without reboot

First, increase disk size on vmware, then run:

echo 1 > /sys/class/block/sdc/device/rescan

growpart /dev/sdc 1

resize2fs /dev/sdc1

RKHunter - rootkit scan on ubuntu

 

To install the Rkhunter tool using the package manager on the Ubuntu system, run the following command.

sudo apt-get install rkhunter

After installation, you need to update the file properties database. To update the file properties database, run the following command.

sudo rkhunter –propupd

This above command lets the Rkhunter scanner to know the current state of individual files to avoid any false alarms during the scanning. After updating the file properties, run the following command to start the scanning.

sudo rkhunter –checkall

This scanner runs through some system commands, network settings, localhost settings, and files to check for actual rootkits and malware. Then, it records the findings to a log file. You can get the condensed look at the scan log using the below command. After checking the logs, you can implement a different process to improve your server security.

sudo cat /var/log/rkhunter.log | grep -i warning

If you want to scan Ubuntu Server every day at a particular time (suppose 4 am night) and send the report to your email address, add the following cron entry.

0 4 * * * /usr/sbin/rkhunter -c 2>&1 | mail -s “Rkhunter Report of the Server” you@domain.com

This above cron job runs at 4 am night every day and sends a report to your email address with the subject “Rkhunter Report of the Server”.

Shutdown Windows machine from linux terminal

 

There may be more setup to do, especially for Windows Vista, Windows 7 and further windows versions, to allow remote shutdown:

Part A) On the Windows machine:

1) Add a remote shutdown security policy:

  • run secpol.msc

  • in the program tree, open Security Settings > Local Policies > User rights Assignment

  • Find the entry Force shutdown from a remote system

  • Edit the entry, add the windows user account that will be used for shutdown (ex: nouknouk)

2) Add registry keys to disable UAC remote restrictions:

  • Run regedit.exe as Administrator

  • Find HKLM/SOFTWARE/Microsoft/Windows/CurrentVersion/Policies/System

  • Create a new registry DWORD(32) value named LocalAccountTokenFilterPolicy and then assign it the value 1

3) Start remote registry service:

  • Open cmd.exeas Administrator

  • Execute the two following commands:

    sc config RemoteRegistry start= auto

    sc start RemoteRegistry

Part B) On the Linux machine:

1) install the package samba-common:

It depends on your Linux distribution, but for Debian and derivated (Ubuntu, Linux Mint, ...), the apt-get command can be executed like that:

apt-get install samba-common

2) To actually shutdown your Windows machine from the Linux one, run the following command:

net rpc shutdown -f -t 0 -C 'message' -U userName%password -I xxx.yyy.zzz.ttt

Where:

  • -f means force shutting down all applications (may be mandatory)

  • -t 0 is the delay before doing it (0 means 'right now').

  • -U user%password is the local user and his password on the windows machine (the one that has been allowed to do remote shutdown in part A).

  • -I is the IP address of the windows machine to shutdown.

     

     

WSL install without Windows Store

 

wsl --install --web-download

wsl --update --web-download

wsl --install -d ubuntu --web-download

--web-download: Download the update from the internet instead of the Microsoft Store.



Vmware Linux Guest Add a New Hard Disk Without Rebooting

List SCSI hosts
ls /sys/class/scsi_host

Update info
echo "- - -" > /sys/class/scsi_host/host#/scan

Update all

echo "- - -" | tee /sys/class/scsi_host/host*/scan


Now, you can create partition using fdisk and format it using mkfs.ext3 command:
cfdisk /dev/sdc

### [if you want ext4 fs] ###
mkfs.ext4 /dev/sdc3

Create a Mount Point And Update /etc/fstab

First, type the following mkdir command to make a dir/folder to mount the disk:
mkdir /disk3

Open the /etc/fstab file, enter:
vi /etc/fstab
/dev/sdc3               /disk3           ext4    defaults  



How Do I Delete a Single Device Called /dev/sdc?

In addition to re-scanning the entire bus, a specific device can be added or existing device deleted using the following command:
echo 1 > /sys/block/devName/device/delete
echo 1 > /sys/block/sdc/device/delete

 

source: https://www.cyberciti.biz/tips/vmware-add-a-new-hard-disk-without-rebooting-guest.html

Fixing -bash: /dev/null: Permission denied

 This should fix the issue (as root):

rm /dev/null
mknod /dev/null c 1 3
chmod 666 /dev/null


What these commands are doing:

rm is removing the bogus file that has been created because the expected one was missing;
mknod is creating a character device named /dev/null with the appropriate major and minor numbers for a Linux kernel;
chmod is setting the permissions for all users to be able to read and write to /dev/null.

Harden bash_history and bash configuration files

 

Harden bash_history and bash configuration files by making them append-only:

chattr +a /home/user/.bash_history
chattr +a /home/user/.bash_profile
chattr +a /home/user/.bash_login
chattr +a /home/user/.profile
chattr +a /home/user/.bash_logout
chattr +a /home/user/.bashrc

Harden env variables by adding the following lines to /home/user/.bashrc:

shopt -s histappend
readonly PROMPT_COMMAND="history -a"
readonly HISTFILE
readonly HISTFILESIZE
readonly HISTSIZE
readonly HISTCMD
readonly HISTCONTROL
readonly HISTIGNORE

histappend tells bash to append the last $HISTSIZE lines to the $HISTFILE file when an interactive shell exits. PROMPT_COMMAND executes the given command prior to issuing each prompt. history -a appends the command typed just before the current one to $HISTFILE.

Disable access to other shells:

chmod 750 csh
chmod 750 tcsh
chmod 750 ksh

 

 

Clean /var/log/journal

 

$ du -hs /var/log/journal/
4.1G    /var/log/journal/

4,1 GB de arquivos de diários, com o mais antigo datando de mais de dois meses.

$ ls -lath /var/log/journal/*/ | tail -n 2
-rw-r-x---+ 1 root systemd-journal 8.0M Dec 24 05:15 user-xxx.journal

Limpe systemd journals de mais de X dias

A primeira é baseada no tempo, limpando todo o suporte de há mais de, digamos, 10 dias.

$ journalctl --vacuum-time=10d

Vacuuming done, freed 2.3G of archived journals on disk.

Alternativamente, você pode limitar seu tamanho total.
Limpe systemd journals se eles excederem X de armazenamento

Este exemplo manterá 2GB de logs, limpando tudo o que excede isso.

$ journalctl --vacuum-size=2G

Vacuuming done, freed 720.0M of archived journals on disk.

 

 

Limit SSH access by user and network

 Add user filtering with AllowUsers option in sshd_config file:

AllowUsers johndoe@192.168.1.* admin2@192.168.1.* otherid1 otherid2

This allows johndoe and admin2 only from 192.168.1.* addresses and otherid1, otherid2 from anywhere.

 

 

Run local script on remote host via SSH

 

ssh root@<remoteServer> "bash -s" < /opt/script.sh
Run in multiple hosts: 
for i in `cat hosts.txt` ; do echo $i && ssh root@$i "bash -s" < script.sh ; done 

Source: https://unix.stackexchange.com/questions/87405/how-can-i-execute-local-script-on-remote-machine-and-include-arguments

Automatically keep current version of config files when apt-get install

 

apt install -o Dpkg::Options::="--force-confold" --only-upgrade <package> 


Remote:


ssh <user>@<ip_address> 'apt install -o Dpkg::Options::="--force-confold" --only-upgrade <package>'


Moving the MySQL data directory to a new location

In this article I will describe the process of moving the MySQL data directory to a separate location, namely on a level 10 raid with 4 disks, this will increase performance.
 
I’ll take an HP DL360p Gen8 server with a Smart Array P420i raid controller, and I’ll also take 6 Samsung 883 DCT Enterprise 240GB 2.5″ SATA III V-NAND MLC (MZ-7LH240NE).
From two disks we will create a mirrored raid 1 and install the Ubuntu 18.04 operating system on it, from the remaining 4 SSD we will create a level 10 raid that will be used only for the database.
 
Switch to root user:
sudo su
 
Stop the MySQL server:
systemctl stop mysql
systemctl status mysql

 
Let’s make a copy of the database files:
mkdir /var/lib/mysql_ixnfo.com
cp -r /var/lib/mysql/* /var/lib/mysql_ixnfo.com/

 
We delete files:
rm /var/lib/mysql/* -Rf
 
Let’s see the list of available disk systems:
fdisk -l
fdisk -l | grep '/dev/sd'

 
I got it displayed:
 
Disk /dev/sda: 223.6 GiB, 240021504000 bytes, 468792000 sectors
/dev/sda1   2048      4095      2048     1M BIOS boot
/dev/sda2   4096 468789247 468785152 223.5G Linux filesystem
Disk /dev/sdb: 447.1 GiB, 480047095808 bytes, 937591984 sectors

 
Let’s create a section on the second raid:
 
fdisk /dev/sdb
n
p
1
Enter
Enter
w
fdisk -l | grep '/dev/sd'
mkfs.ext4 /dev/sdb1
df -h

 
Mount the newly created partition in the database directory:
mount /dev/sdb1 /var/lib/mysql
 
Let’s see its UUID:
sudo blkid
 
I got it displayed:
/dev/sdb1: UUID="54bf0d45-c190-4185-968d-b440537122bd" TYPE="ext4" PARTUUID="d2090c9f-01"
 
To automatically mount when the operating system starts, open the /etc/fstab file in a text editor (in the nano editor, press Ctrl+X to exit and y/n to save or discard changes):
nano /etc/fstab
 
I added:
UUID=54bf0d45-c190-4185-968d-b440537122bd /var/lib/mysql ext4 defaults 0 0
 
From the previously made copy, copy the database files to the mounted raid 10:
cp -r /var/lib/mysql_ixnfo.com/* /var/lib/mysql/
 
Let’s set the correct owner and rights:
chown mysql:mysql /var/lib/mysql/ -R
chmod 755 /var/lib/mysql

 
Let’s check:
ls -l /var/lib/mysql/
 
We start the MySQL server:
systemctl start mysql
systemctl status mysql

 
Let’s restart the server to make sure that raid 10 is automatically mounted and the database server has started successfully:
reboot
 
After restarting, I noticed the default directory for lost files, I deleted it and restarted MySQL:
rm -d /var/lib/mysql/lost+found
systemctl restart mysql

 
If you wish, you can mount the raid to another directory and specify the path to it in my.cnf: 


[mysqld]
datadir=/mnt/sdb1/mysql
socket=/mnt/sdb1/mysql/mysql.sock
log-bin=/mnt/sdb1/mysql/mysql-bin
[mysqld_safe]
datadir=/mnt/sdb1/mysql
 
You can see which directory is specified like this:
mysql -u root -p
select @@datadir;
 
Let’s copy the files using rsync:
rsync -av /var/lib/mysql /mnt/sdb1/mysql
mv /var/lib/mysql /var/lib/mysql.mybakup

 
Let’s specify a new directory for apparmor in the /etc/apparmor.d/tunables/alias file:
alias /var/lib/mysql/ -> /mnt/sdb1/mysql/,
 
And let’s restart it:
systemctl restart apparmor
 
source: https://ixnfo.com/en/moving-the-mysql-data-directory-to-a-new-location.html
 

Block folder access - Nginx

 location /phpmyadmin {
  deny all;
  return 403;
}

location /phpmyadmin {

  allow 192.168.1.0/24;
  deny all;
  return 403;
}

Wget behind proxy

 

Add this lines in /etc/wgetrc file

use_proxy=yes
http_proxy=http://<proxy>:<port>
https_proxy=http://
<proxy>:<port>

 

Ubuntu 20.04 multipath syslog errors

Edit  /etc/multipath.conf 

and blacklist sda. Files contents which also blacklists common other devices like CDRom drives etc. that should never be checked for multipath configurations:

Code:

defaults {
    user_friendly_names yes
}
blacklist {
    devnode "^(ram|raw|loop|fd|md|dm-|sr|scd|st|sda)[0-9]*"
}



Adicionar registro DNS windows linha de comando

 Usando o Prompt de Comando (dnscmd)Abra o Prompt de Comando como Administrador e utilize a seguinte estrutura para adicionar um registro do...

Mais vistos