Silently install msi package

Silently install the msi package:

msiexec /i C:\setup.msi /qn

Silently install the msi package, no reboot

msiexec /i C:\setup.msi /qn /norestart

Silently install the msi package, force reboot

msiexec /i C:\setup.msi /qn /forcerestart

Silently install the msi package and write the installation log to file C:\msilog.txt

msiexec /i C:\setup.msi /l*v C:\msilog.txt /qn

Silently uninstall the msi package:

msiexec /x C:\setup.msi /qn

Silently uninstall the msi package by the product code:

msiexec /x {XXXXXXXX-9215-4780-AAC6-01FD101DC931} /qn

Fix squid password prompt

To fix squid authentication we need set permissions in  /var/lib/samba/winbindd_privileged folder:

Set user root and group for winbind:

chown root:proxy /var/lib/samba/winbindd_privileged -R
or
chown root:squid /var/lib/samba/winbindd_privileged -R

Set folder permission
chmod 750 /var/lib/samba/winbindd_privileged -R

and restart winbind and squid

systemctl restart winbind

systemctl restart squid



convert single line output to multiple line

$ips="10.26.208.28 10.26.208.26 10.26.208.27"

echo $ips | tr -s " " "\n"
or
echo $ips|xargs -n1

result
10.26.208.28
10.26.208.26
10.26.208.27

Linux date

/bin/date +"%c"
seg 26 nov 2018 23:46:42 -04


/bin/date +"%a, %d %b %Y, %H:%M"
seg, 26 nov 2018, 23:11

date +"%c" |cut -d":" -f1-2
seg 26 nov 2018 23:40

date "+%d %B %Y"
26 novembro 2018

/bin/date +"%d-%m-%Y"
26-11-2018

date +"%D"
11/26/18

date +"%T"
23:41:50

date +"%R"
23:43

date +%d-%m-%Y -d "5 days ago"
21-11-2018

date -d "2 week"
seg dez 10 23:49:29 -04 2018

date -d "5 month 2 day"
dom abr 28 23:51:59 -04 2019

Avoid blink on webfont load

@font-face {
    font-display:swap;
}

HTML images lazy load

<head>
    <script src="lazysizes.min.js" async></script>
</head>
<body>
    <img data-src="flower.jpg" class="lazyload" alt="">
</body>   


<img src="flower.jpg" lazyload="auto|on|off">


<!-- non-responsive: -->
<img data-src="image.jpg" class="lazyload" />

<!-- responsive example with automatic sizes calculation: -->
<img
    data-sizes="auto"
    data-src="image2.jpg"
    data-srcset="image1.jpg 300w,
    image2.jpg 600w,
    image3.jpg 900w" class="lazyload" />

<!-- iframe example -->
<iframe frameborder="0"
    class="lazyload"
    allowfullscreen=""
    data-src="//www.youtube.com/embed/ZfV-aYdU4uE">
</iframe>

ffmpeg

gif to video

ffmpeg -i dog.gif dog.mp4


add watermark

ffmpeg -i Christmas10.mp4 -i logo.png -filter_complex "[0:v][1:v]overlay=main_w-overlay_w-50:50[filtered]" -map "[filtered]" -map 0:a -codec:a copy paper.mp4 


cut start at 1m until 20 seg

ffmpeg -t 1:00 -i paper.mp4 -ss 20 output.mp4



Open port windows firewall


netsh advfirewall firewall add rule name="RULE_NAME" dir=in action=allow protocol=PROTOCOL localport=PORT

ex:
netsh advfirewall firewall add rule name="ZABBIX" dir=in action=allow protocol=TCP localport=10050

Set logrotate to specific time

If you only want to make logrotate run at midnight, move /etc/cron.daily/logrotate to some other directory, and add the line at the end of /etc/crontab.

0 0 * * * /new/path/to/logrotate
 

Set Ubuntu Locale

sudo locale-gen pt_BR
sudo locale-gen pt_BR.UTF-8
sudo dpkg-reconfigure locales
sudo update-locale LANG=pt_BR.UTF-8

List Windows group members


Get-ADGroupMember “Group Name” -recursive | Out-File c:\groupmembers.html

Apache2 HTTPS

Install ssl packages

sudo apt-get install openssl ssl-cert

Enable SSL module

sudo a2enmod ssl

Create certificate

sudo openssl req $@ -new -x509 -days 365 -nodes -out /etc/apache2/apache.pem -keyout /etc/apache2/apache.pem

Set certificate permissions

sudo chmod 600 /etc/apache2/apache.pem

Edit the file /etc/apache2/sites-available/ssl

NameVirtualHost *:443
<VirtualHost *:443 >
        SSLEngine on
        ServerSignature On
        SSLCertificateFile /etc/apache2/apache.pem


Enable https for site

sudo a2ensite ssl

Restart Apache2

sudo apache2ctl restart


Testing

Open https://localhost on browser

File /etc/network/interfaces

# 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
auto enp4s0
iface enp4s0 inet static
        address 10.20.10.232
        netmask 255.255.255.0
        network 10.20.10.0
        broadcast 10.20.10.255
        gateway 10.20.10.1
        dns-nameservers 10.20.10.11 10.20.10.10
        dns-domain domain.local
        # dns-* options are implemented by the resolvconf package, if installed

Secure SSH


1 – Edit sshd_config file
vi /etc/ssh/sshd_config

# Allow only listed users
AllowUsers adam bob carl

# SSH port
Port 22

# Deny root login
PermitRootLogin no

# Deny login without password
PermitEmptyPasswords no

cron

Cron log
tail -f /var/log/cron

ENTRADAS ESPECIAIS DO CRON
Para ver os horario de execução da variaves especiais:
awk '/^[0-9]/ {print $1,$2,$3,$4,$5,$(NF-1)}' /etc/crontab

Executa script.sh ao ligar servidor
@restart /usr/local/bin/script.sh

Executa script.sh de hora em hora. Equivalente X * * * *
@hourly /usr/local/bin/script.sh

Executa script.sh uma vez ao dia. Equivalente X X * * *
@daily /usr/local/bin/script.sh

Executa script.sh uma vez por semana. Equivalente X X * * 0
@weekly /usr/local/bin/script.sh

Executa script.sh uma vez por mês. Equivalente X X 1 * *
@monthly /usr/local/bin/script.sh

Windows - RDP CredSSP Encryption Oracle Fix


Run the command below in CMD, as administrator. Maybe needs reboot if don't work on first run.

reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\CredSSP\Parameters" /f /v AllowEncryptionOracle /t REG_DWORD /d 2

Hide Squid info

Add at the end of error pages

<br clear="all">
<hr noshade size=1>
Generated %T
<!-- %h (%s) -->



Zabbix remote ping check


I’ve had my Zabbix install set up to notify me if the remote server has a high ping using this expression:

{__Remote_Hosts:icmppingsec.avg(30)}>120

The problem is, if your network is congested, it can really hit often. I recommend moving the failed ping average up to 500, and adding another trigger:

{__Remote_Hosts:icmpping.max(120)}<1

This checks for no ping within 120 seconds (or 2 minutes) so it gives you a better idea if the host is "down" or just seeing a high ping latency.

tcpdump

To filter eth1 interface
tcpdump -i eth1

To filter eth1 interface without resolv DNS
tcpdump -i eth1 -nn

To filter one IP
tcpdump -i eth1 -nn host 192.168.0.7

To filter eth1 and destination port
tcpdump -i eth1 -nn dst port 2967

To filter more that one destination port
tcpdump -i eth1 -nn dst port 2967 or 80

To filter one source IP
tcpdump -i eth1 -nn src 10.20.181.55

To filter a destination IP
tcpdump -i eth1 -nn dst 207.46.26.23

To filter one IP and port
tcpdump -i eth1 -nn host 192.168.0.7 and port 80

To filter one source IP and port
tcpdump -i eth1 -nn src 10.20.181.55 and port 1863

rsync

rsync

Incremental backup
rsync -av --delete /home/donato/ /backup/

Date validation with regex

Date validation with regex – dd/mm/yyyy

(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\d{2,2}

Remove blank lines with grep


Remove blank lines ( new line ) with grep
echo -e "a\n\nb" | grep -v '^ *$'

or

grep -v '^[\s\t]*$' file.txt  > new_file.txt

Include Shell Script

Include Shell Script

File in same directory
source $( dirname $0 )/include-functions.sh

Create ISO in pendrive Linux

Get pendrive address (/dev/sdX)
lsblk -S | awk '$NF ~ /usb$/ {print $1}'

Use dd to send ISO to pendrive
dd if=/image.iso of=/dev/sdb bs=4096

Manipulate dates with linux


Current formatted date
date +%d-%m-%Y

Current formatted date with time
date '+%d-%m-%Y %H:%M:%S'

1 day before the current date
date -d '-1 day' +%d-%m-%Y

1 day after the current date
date -d '+1 day' +%d-%m-%Y

First day of current month
date -d '-0 month' +01-%m-%Y

Last day of current month
date -d "-$(date +%d) days +1 month" +%d-%m-%Y

Last day of current month + one day
date -d "-$(date +%d) days +1 month +1 day" +%d-%m-%Y

First day of the previous month
date -d '-1 month' +01-%m-%Y

Last day of the previous month
date -d "-$(date +%d) days -0 month" +%d-%m-%Y

First day of the next month
date -d '+1 month' +01-%m-%Y

Last day of the next month
date -d "-$(date +%d) days +2 month" +%d-%m-%Y

Date format style /var/log/messages ( Aug 25 19:15:20 )
date '+%b %d %R:%S'

Concatenate variable shell script

  
VAR=abc; echo ${VAR}def

for i in {1..5}; do echo x${i}x; done

Comment line with sed

comment line starting with abc
sed -i '/^abc.*/s/^/#/' file

comment all lines in the file
sed -i '/^/s/^/#/' file

comment line starting with abc and append a comment on end of line
sed '/^abc.*/s/^/# /; //s/$/ comment/' file

Loop for shell script

loop for shell script

loop 1 until 10
for i in {1..10}; do echo $i; done

list all files in directory
for i in /etc/*; do echo $i; done

Execute command from windows batch file

execute command from windows batch file

cmd.exe /K ""C:\Program Files\exeNameHere.exe" paramsHere"

    /C Carries out the command specified by string and then terminates
    /K Carries out the command specified by string but remains

Use: cmd /? to see cmd help command

Replace char/word in shell script


substitute whitespace by commas to generate csv output

echo a b c | tr -s ' ' ','

Bandwidth control script for some ips


#!/bin/bash

BANDWIDTH_KBIT=7000
BANDWIDTH_INTERFACE=eth0
FINAL_IPs_WITH_BANDWIDTH_CONTROL=(7 8 50 111)
LAN_IP=$( ip addr show $BANDWIDTH_INTERFACE | grep -Eo '([0-9]{1,3}\.){3}' | sed -n 1p )

# clear all tc rules
tc qdisc del dev $BANDWIDTH_INTERFACE root

# create tc rules
tc qdisc add dev $BANDWIDTH_INTERFACE root handle 1: htb

for i in ${FINAL_IPs_WITH_BANDWIDTH_CONTROL[*]}; do
  tc class add dev $BANDWIDTH_INTERFACE classid 1:${i} htb rate ${BANDWIDTH_KBIT}kbit
  tc filter add dev $BANDWIDTH_INTERFACE parent 1: protocol ip prio 1 u32 match ip dst $LAN_IP${i} flowid 1:${i}
done

to list only machines that have traffic
tc -s -d class show dev eth0 | awk '$1 == "Sent" && $2 { print "\n"x; print } { x=$0 }'

to list only machines that have traffic order by traffic usage
tc -s -d class show dev eth0 | awk 'BEGIN{ ORS=" " } $1 == "Sent" && $2 { print "\n"x; print } { x=$0 }' | cut -d' ' -f1,3,9,10,29,30 | sort -k6n

Shell generate password


Shell generate password
 
echo stringHere | tr -t a-z 0-9@#$%

Reboot machine if it can’t ping

#!/bin/bash
# reboot if ping test fails for 3 times

unset IVAR

for i in {1..3}; do
  ping -c 1 8.8.8.8 > /dev/null || ((IVAR++))
done

if [ "$IVAR" == 3 ]; then
  echo '[' $( date '+%d/%m/%Y %R' ) '] reboot' | tee -a /var/log/$( basename $0 ).log
  /sbin/init 6
fi

Block IP's by countries



#!/bin/bash
# block countries with iptables based on list with range of ips

# download list with range of countries ips
rm -rf /tmp/all-zones*; wget -nc http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gz -P /tmp

mkdir /tmp/all-zones; tar -xzvf /tmp/all-zones.tar.gz -C $_

COUNTRIES_ISO_CODE_LIST=(af cu mo)

for country_iso_code in ${COUNTRIES_ISO_CODE_LIST[*]}; do

  for country_ip in $( cat /tmp/all-zones/$country_iso_code.zone ); do
    echo creating rules to $country_iso_code $country_ip
    /sbin/iptables -A INPUT -s $country_ip -m comment --comment "rule to $( echo $country_iso_code | tr '[:lower:]' '[:upper:]' ) country" -j DROP
  done
done

Creating columns bash


create 1 column
seq 10

create 2 columns
printf %s\\n ID-{1..3}' '{10..25..5}

create 3 or more columns
seq 12 | pr -3t | column -t

Setting maximum mail recipients in zimbra

Setting maximum mail recipients in zimbra

To adjust:

su - zimbra
postconf -e 'smtpd_recipient_limit = 1000'

To apply settings:

postfix reload

To check current settings:

postconf | grep smtpd_recipient_limit

Zabbix collect vSphere info

1) Create vSphere host
2) Add 3 macros:
- {$USERNAME} - username which has an administrative privileges on VMware
- {$PASSWORD) - password for username
- {$URL} - https://10.10.10.10/sdk (where 10.10.10.10 is the address of vSphere host, not VMware supervisor)
- {$UUID} - vsphere UUID - https://host/mob/?moid=ha-host&doPath=hardware.systemInfo
3) Add 3 templates to vSphere host:
- Template Virt VMware
- Template Virt VMware Guest
- Template Virt VMware Hypervisor

Enable Object Browser in vSphere 6.x

Starting with vSphere 6.0 the Managed Object Browser is disabled by default to avoid malicious configuration changes or actions. You can enable and disable the Managed Object Browser manually.

To enable or disable the Managed Object Browser by using the vSphere Client connected directly to the ESXi host, complete the following steps:

1 - In the vSphere Client, select the host in the inventory.
2 - In the right pane, click the Configuration tab.
3 - Under Software, select Advanced Settings.
4 - From the left pane of the Advanced Settings dialog box, select Config > HostAgent > plugins > solo.
5 - Select or deselect Config.HostAgent.plugins.solo.enableMob to enable or disable the Managed Object Browser.

To enable or disable the Managed Object Browser by using the vSphere Web Client, complete the following steps:

1 - Browse to the host in the vSphere Web Client navigator.
2 - On the Manage tab and click Settings.
3 - Under System, select Advanced System Settings.
4 - Select the Config.HostAgent.plugins.solo.enableMob option and click Edit to enable or disable the Managed Object Browser.

ESXI CLI

Activate SNMP on VSphere client
Configuration -> Security Profile -> Firewall -> Properties -> SNMP


Connect to ESXI using SSH and run the command below, changing community, contact email and location:

esxcli system snmp set -r && esxcli system snmp set -c public && esxcli system snmp set -p 161 && esxcli system snmp set -C contact@domain.com && esxcli system snmp set -L "City, State" && esxcli system snmp set -e yes


#firewall all hosts
esxcli network firewall ruleset set --ruleset-id snmp --allowed-all true
esxcli network firewall ruleset set --ruleset-id snmp --enabled true
#firewall for specific network
esxcli network firewall ruleset set --ruleset-id snmp --allowed-all false
esxcli network firewall ruleset allowedip add --ruleset-id snmp --ip-address 10.20.0.0.0/23
esxcli network firewall ruleset set --ruleset-id snmp --enabled true
#restart snmp
/etc/init.d/snmpd restart 



Set time:
esxcli system time set -d 31 -M 1 -y 2012 -H 18 -m 0 -s 0

source: https://kb.vmware.com/s/article/1003736


View log in browser:

https://server_ip_or_name/host/syslog.log





Use the Direct Console User Interface (DCUI) over ssh



1 - Browse to the host in the vSphere Web Client inventory.
2 - Click the Manage tab and click Settings.
3 - Under System, select Security Profile.
4 - In the Services panel, click Edit.
5 - Select a service from the list.

        ESXi Shell
        SSH
        Direct Console UI
      
6 - Click Service Details and select the startup policy Start and stop manually.
When you select Start and stop manually, the service does not start when you reboot the host. If you want the service to start when you reboot the host, select Start and stop with host.
7 - Select Start to enable the service.
8 - Click OK.

9 - Access the server over ssh andrun

dcui

ctrl+c to exit

ESXi Retrieving Networking Information

Linux commands for retrieving networking information are not included in the ESXi Shell. You can instead use ESXCLI commands.

On ESXi 5.0, ifconfig information is the information for the VMkernel NIC that attaches to the Management Network port group. You can retrieve that information by using ESXCLI commands.

    esxcli network ip interface list

    esxcli network ip interface ipv4 get -n vmk<X>

    esxcli network ip interface ipv6 get -n vmk<X>

    esxcli network ip interface ipv6 address list


You can retrieve information about DNS with the esxcli network ip dns command in the following two namespaces:

    esxcli network ip dns search

    esxcli network ip dns server


For information corresponding to the Linux netstat command, use the following ESXCLI command.

    esxcli network ip connection list

Zimbra get attachment sizes

Get attachment sizes

# zmprov gacf | grep zimbraMtaMaxMessageSize
zimbraMtaMaxMessageSize: 20480000

# zmprov gacf | grep zimbraFileUploadMaxSize
zimbraFileUploadMaxSize: 20480000

Change sizes:

zmprov mcf zimbraMtaMaxMessageSize 20480000

10240000 = 10mb
20480000 = 20mb
30720000 = 30mb

Zimbra export ldap schema

 export ldap schema

/opt/zimbra/libexec/zmslapcat /opt/backup/ldap

Zimbra manage accounts

Manage accounts
zimbraAccountStatus can be active, locked, maintenance or closed

zmprov ma accountname@domain.com  zimbraAccountStatus active

Zimbra clear zmlogger data

Clear zmlogger data

zmloggerctl stop
cd /opt/zimbra/logger/db/data
mv rrds rrds_old
mkdir rrds
zmlogger start

Zimbra recipient limits

Recipient limits

postconf | grep smtpd_recipient_limit
postconf -e smtpd_recipient_limit=100

Zimbra clean mailbox

Clean mailbox

su zimbra
zmmailbox -z -m admin@domain.com emptyFolder /Inbox

Zimbra change user COS

Change user COS

su zimbra
zmprov sac name.surname@domain.ltd cosname

Zimbra get account by state

Get account by state

zmprov -l sa "(zimbraAccountStatus=active)"
zmprov -l sa "(zimbraAccountStatus=lockout)"
zmprov -l sa "(zimbraAccountStatus=closed)"

Zimbra message trace

# by sender
/opt/zimbra/libexec/zmmsgtrace -s user@domain.com


# by recipient
/opt/zimbra/libexec/zmmsgtrace -r '@gmail.com'

Zimbra mail queue


View mail queue status

# /opt/zimbra/libexec/zmqstat
hold=0
corrupt=0
deferred=0
active=0
incoming=0

To Check current mail queue status

[root@mail lqs]# su zimbra
[zimbra@mail lqs]$ /opt/zimbra/postfix/sbin/postqueue -p
Mail queue is empty

To Flush Postfix Queue

[root@mail lqs]$ /opt/zimbra/postfix/sbin/postqueue -f

To Requeue Messages In Postfix

[root@mail lqs]$ /opt/zimbra/postfix/sbin/postsuper -r ALL

To Check current hold messages

[root@mail lqs]# /opt/zimbra/postfix/sbin/postsuper -h ALL

To Delete Single Message From Queue

[root@mail lqs]# /opt/zimbra/postfix/sbin/postsuper -d [MSGID From postqueue -p]

To Delete ALL Messages From Queue

[root@mail lqs]# /opt/zimbra/postfix/sbin/postsuper -d ALL

To Delete ALL Messages From The Deferred Queue

[root@mail lqs]# /opt/zimbra/postfix/sbin/postsuper -d ALL deferred

To Delete ALL Messages From The Hold Queue

[root@mail lqs]# /opt/zimbra/postfix/sbin/postsuper -d ALL hold

Clear inbox Zimbra

Clear all inbox from never login accounts

#!/bin/sh
#Limpa o inbox de todas as caias que nunca foram acessadas

cts=`zmaccts | grep never | cut -c 1-40`
for i in $cts; do
zmmailbox -z -m $i emptyFolder /Inbox
done

Zimbra login errors report

Creat script and config in crontab

#!/bin/bash

cat /opt/zimbra/log/audit.log |grep -i "authentication failed" > /var/log/auth_error.log

mail -s "Login Errors Report" admin@domain.com < /var/log/auth_error.log

Get the IP and number of login fails in Zimbra

Get the IP and number of login fails in Zimbra
Use "while read" with "iptables -j DROP" or "route add -host <IP> reject" to block

grep "SASL LOGIN" /var/log/zimbra.log | grep failed | awk '{print $7}' | cut -d[ -f 2 | cut -d] -f 1 | sort | uniq -c | sort -n -r

Fix pgp no public key

Fix pgp no public key

apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 4F4EA0AAE5267A6C

Temporary swap file linux

Adicionando memória virtual (SWAP) temporária no GNU/Linux

A memória que criaremos durará apenas até a próxima reinicialização do computador (mas podemos torná-la fixa). Logo depois, ela é apagada.

Para criarmos a memória virtual em um arquivo temporário, use o comando:

# dd if=/dev/zero of=/root/myswapfile bs=1M count=1024

Com isso, o arquivo será criado. Precisamos dar permissão de leitura e gravação (4 [leitura] + 2 [gravação] = 6) para o root com o comando chmod:

# chmod 600 /root/myswapfile

Precisamos definir o arquivo como SWAP com o comando:

# mkswap /root/myswapfile

Para habilitar a memória virtual no arquivo, use o comando:

# swapon /root/myswapfile

Você pode checar se ela foi criada usando o comando:

# swapon -s

Caso você deseja usá-la como memória virtual fixa, adicione a linha abaixo no arquivo /etc/fstab:

/root/myswapfile swap  swap  defaults   0   0

Para não ter de reiniciar o computador após alterar o /etc/fstab, use o comando:

# swapon -a

Ubuntu netplan config file

 Ubuntu netplan config file

Creat file 01-netcfg.yaml in /etc/netplan

pico /etc/netplan/01-netcfg.yaml

network:
    version: 2
    ethernets:
        ens192:
            addresses:
            - 10.20.1.16/24
            dhcp4: false
            gateway4: 10.20.1.216
            nameservers:
                addresses:
                - 10.20.1.11
                search:
                - mpro.gov
            routes:
             - to: 10.0.0.0/8
               via: 10.20.0.254

Shutdown VMWare guests


Method 1

#list Vms
vim-cmd vmsvc/getallvms

#get power state
vim-cmd vmsvc/power.getstate "VMID"

#Shutdown

vim-cmd vmsvc/power.shutdown "VMID"

Note: If the virtual machine fails to shut down, run this command:

vim-cmd vmsvc/power.off "VMID"


Method 2

#Get Vms info
esxcli vm process list |grep -i World |cut -d: -f2

#shutdown Vm
esxcli vms vm kill --type= [soft,hard,force] --world-id= WorldNumber
ex: esxcli vm process kill -w 69237 -t soft 


Get IP with nmap

Get only IP

nmap -sP -oG - 10.20.110.0/24 | awk '/Host/{print $2}'

Get IP and hostname

nmap -sP -oG - 10.20.200.0/22 | awk '/Host/{print $2 " " substr($3,2,length($3) - 2)}'

Hide info in apache2.conf

Hide info in apache2.conf

ServerTokens Prod
ServerSignature Off
TraceEnable Off
Options all -Indexes
Header always unset X-Powered-By

Show only repeated entries

show only repeated entries

echo -e 'a\nb\nc\na' | sort | uniq -D

nmap advanced

discover all IPs connected in our network, use lan ip of default gateway
nmap -sP $( ip route | grep '^default' | egrep -o '([0-9]{1,3}\.){3}' )0/24 | awk '/^Nmap.*[0-9]$/{print $NF}' | sort -n -t . -k 4

get information from hosts through windows sharing
nmap -script smb-os-discovery -p 445 -open 192.168.0.0/24

show hosts with port 631 open
nmap 192.168.0.0/24 -p 631 -open | awk '/)$/ {print $NF}'

Limits two simultaneous connections on port 80 to each host connected to the network
nmap -sP 192.168.0.0/24 | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}' | sort -n -t . -k 4 | xargs -I% iptables -A INPUT -s % -p tcp --dport 80 -m connlimit --connlimit-above 2 -j DROP

Get last field using cut

get last field using cut

echo 'www.google.com' | rev | cut -d'.' -f1 | rev

Filter last occurrence on file


filter last occurrence containing the DHCP string
tac /var/log/syslog | grep -m 1 'DHCP'

filter 3 lines between the last occurrence containing the err or warn string
tac /var/log/syslog | egrep -m 1 -C 3 'err|warn'

Get first and last line of file


bash way
(head -1; tail -1) < /etc/passwd

sed way
sed -n '1p; $p' /etc/passwd

awk way
awk 'NR==1; END { print }' /etc/passwd

Test if param is not empty

test if param is not empty bash

Test if $1 has value
[ -n "$1" ] && echo $1 || echo param is empty

Format columns shell


format output as a table
echo -e name age"\n"donato 30 | column -t

Creating columns bash


create 1 column
seq 10

create 2 columns
printf %s\\n ID-{1..3}' '{10..25..5}

create 3 or more columns
seq 12 | pr -3t | column -t

Shutdown Windows or Linux by network

Linux
sshpass -p "$PASSWD" ssh -o StrictHostKeyChecking=no -l $USER $IP 'init 0'


Windows

Use this command to shutdown the computer remotely:
net rpc shutdown --ipaddress ip --user username%password

Add -r if you want to restart, not shutdown:
net rpc shutdown -r -f --ipaddress ip --user username%password

Mount samba share on linux

mount cifs/samba share
mount -t cifs -o vers=1.0,user=userHere //192.168.0.7/sharedDir /mnt

mount cifs/samba share on system startup
vi /etc/fstab

//192.168.0.7/sharedDir /mnt cifs vers=1.0,user=userHere,pass=passwdHere,uid=1001,gid=100 0 0

Order ip adress with sort


order ip adress with sort

nmap -sP 192.168.0.0/24; arp -a | sort -n -t . -k 4

Get all mac address

get all mac address and ip from network order by ip

nmap -sP 192.168.0.0/24; arp -a | sort -n -t . -k 4 | awk '{print "mac:", $4, "#"$2}'

Slow ssh login


Disable DNS option in sshd
vi /etc/ssh/sshd_config

UseDNS no

Convert date time string to unix timestamp

convert date time string to unix timestamp in linux

Get date format style /var/log/messages
date '+%b %d %R:%S'

Convert date time string to unix timestamp
date -d 'Aug 21 15:29:40' +%s

Get current date time in unix timestamp
date +%s

Enable wol in vmware host

list network adapters
esxcli network nic list

check if network adapter supports wake-on-lan and it is enabled
esxcli network nic get -n vmnic0 | grep Wakeon

enable wol in network adapter, add this line before the line init 0 in local.sh file
vi /etc/rc.local.d/local.sh

ethtool -s vmnic0 wol g

Check if linux is physical or virtual


with dmesg
dmesg | grep 'Hypervisor detected'

with dmidecode
dmidecode -s system-manufacturer

with lshw
lshw -class system

Find directory size

find size of each directory in ‘/’ order by size
du -h --max-depth=1 / | sort -nr

find size of each directory in current directory order by size
du -h --max-depth=1 | sort -nr

Simple desktop firewall linux


Simple desktop firewall linux

minimal iptables rules to allow only output connections in local machine
iptables -P INPUT DROP
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT

Regex to math with range numbers


regex to match 10 to 15 like: 17:[10-15]
echo '17:11' | egrep '17:(10|11|12|13|14|15)'

Change file and print changed lines with sed

change file and print changed lines with sed

sed -i 's/8.8.8.8/8.8.4.4/ w/dev/stdout' /etc/resolv.conf

Convert to upper or lower case in shell

convert string to upper or lower case in shell script

convert string to upper case
echo aBcD | tr '[:lower:]' '[:upper:]'

convert string to lower case
echo aBcD | tr '[:upper:]' '[:lower:]'

Print specific line with awk


print first line with awk
ping -c 1 8.8.8.8 | awk 'NR==1'

print last line with awk
ping -c 1 8.8.8.8 | awk 'END { print }'

Merge output lines with awk

Use paste with comma, default is tab

paste file1.txt file2.txt -d ","


merge output lines in the same line with awk

echo -e 'a\nb\nc' | awk 'ORS=" " { print }'

Find files between dates


find files between two specified dates
find / -type f -newermt 2018-01-01 ! -newermt 2018-11-30 -ls

find files created between begin of current month and the current day
find / -type f -newermt $( date +%Y-%m-01 ) ! -newermt $( date +%Y-%m-%d ) -ls

find .php files modified on the last 30 days
find / -type f -regex .*php$ -mtime -30 -exec ls -lt {} +

find files between 1 month ago and 3 days ago that ends with numbers in name
find / -type f -regex .*[0-9]$ -newermt $( date -d '-1 month' +%Y-%m-%d ) ! -newermt $( date -d '-3 day' +%Y-%m-%d ) -exec ls -la {} +

compress files created between two specified dates
find / -type f -newermt $( date -d '-1 month' +%Y-%m-%d ) ! -newermt $( date -d '-3 day' +%Y-%m-%d ) -exec gzip -f {} +

Check if same row exist in two files

check if same row exist in two files 

while read i;do egrep ^$i$ file2 && echo $i >> exist.out || echo $i >> non_exist.out; done < file1

Insert line after line match with sed

insert line after line match with sed

echo -e "House\nCar" | sed '/^House/a Money'

Put char with sed

put char on position X with sed
 
put space on position 5
echo 1234567 | sed 's/./& /5'

put . on position 5
echo 1234567 | sed 's/./&./5'

List top sender address emails in zimbra

List top sender address emails in zimbra

How to List top sender address emails in zimbra from command line. From MTA zimbra I will run command to list 6 sender address email Zimbra.

The command as below:

    $ cat /var/log/zimbra.log | awk -F 'from=<' '{print $2}' | awk -F'>' '{print $1}' | sed '/^$/d' | sort | uniq -c | sort -nk1 -r | sed -n '1,10p'

List top receivers:

    $ cat /var/log/zimbra.log | awk -F 'to=<' '{print $2}' | awk -F'>' '{print $1}' | sed '/^$/d' | sort | uniq -c | sort -nk1 -r | sed -n '1,10p'

Note:

    sed '/^$/d' : To delete only blank lines
    sed -n '1,10p' : To print 1 line to 10 line.
    awk -F 'from=<' '{print $2}' | awk -F'>' '{print $1}' : To print the email of sender address

Set TimeZone Linux

Set TimeZone Linux

List timezones
timedatectl list-timezones

Set timezone
timedatectl set-timezone America/Manaus

Set NTP server on Linux

Set linux server time using ntp server

1 – Install ntpdate package
apt-get install ntpdate

2 – Configure time using ntpdate command
ntpdate pool.ntp.org

3 – Configure ntpdate on cron
crontab -e

@reboot /usr/sbin/ntpdate pool.ntp.org
@daily /usr/sbin/ntpdate pool.ntp.org

Search for email in zimbra log

search for email in zimbra log

grep -A 1 'mail@domain.com' /opt/zimbra/log/mailbox.log

Set/change linux date

Set/change/update date to 31/10/2017 10:15

Option 1 – date command syntax
date -s '2017-10-31 10:15'

Option 2 – date command syntax
date -s '31 OCT 2017 10:15'

Delete html tag using awk

delete html tag using awk
 
echo '<font>abc 123</font>' | awk -F'.?>' '{print $2}' | awk -F'</' '{ print $(NF-1) }'

Sort on linux

sorting by first field
echo -e 'x 2\nb 1\nm 3' | sort

sorting by second field
echo -e 'x 2\nb 1\nm 3' | sort -k2

sorting by second field using comma(csv) as field separator
echo -e 'x,2\nb,1\nm,3' | sort -t, -k2

sorting by fifth field with numeric order
df -h | sort -k5n

sorting by fifth field with reverse numeric order
df -h | sort -k5nr

count a chars in file order by last column
awk -F'a' '{print $0,NF-1}' /etc/passwd | rev | sort | rev

sort in numeric order
echo 1 2 10 | tr ' ' '\n' | sort -V

Execute command and keep ssh session open

execute command and keep ssh session open 

ssh -t 192.168.0.1 'ls /etc; bash'

Failed ssh login attempts

On Debian/Ubuntu

awk '/sshd.*Failed/ { for (f=1; f<NF; f++) if ( $f ~ "from" ) print $2, $1, $(f-1), $(f+1) }' /var/log/auth.log*

Programs connected to network/internet

show programs connected to network/internet

lsof -P -i -n | cut -d' ' -f1 | uniq | sed 1d

Your linux installation age

how old is your linux installation

tune2fs -l $( df -h | awk '$NF ~ "/$" {print $1}' ) | grep created

Sort number in bash


sort number in ascending/numeric order bash

echo 1 2 10 | tr ' ' '\n' | sort -V

Audible ping

using ping

ping -a -c 1 8.8.8.8
or 
while sleep 3;do ping -a -c 1 8.8.8.8; done

using beep
while sleep 3;do ping -c 1 8.8.8.8 && beep; done

Install MSIX with powershell

 Add-AppxPackage -Path "C:\Users\MyUserName\Downloads\affinity-designer-2.0.0.msix" -DependencyPath " https://aka.ms/Microsof...

Mais vistos