Step-1
mkdir ~/.certs
Step-2
certutil -N -d ~/.certs
Enter a password which will be used to encrypt your keys.
The password should be at least 8 characters long,
and should contain at least one non-alphabetic character.
Enter new password:
Re-enter password:
Step-3
echo -n | openssl s_client -starttls smtp -crlf -connect smtp.office365.com:587| sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/.certs/365.crt
certutil -A -n "Google Internet Authority" -t "C,," -d ~/.certs -i ~/.certs/365.crt
Step-4
vim mail-office365.sh
echo -e "Email content" | mailx -v -s "Email subject" \
-S smtp-auth=login \
-S smtp-use-starttls \
-S nss-config-dir=~/.certs \
-S smtp=smtp.office365.com:587 \
-S from="user@office365.com" \
-S smtp-auth-user=user@office365.com \
-S smtp-auth-password="passwordxxxx" \
-S ssl-verify=ignore \
user@gmail.com
Mostrando postagens com marcador Shell. Mostrar todas as postagens
Mostrando postagens com marcador Shell. Mostrar todas as postagens
Send Mail with Office365 Auth
Run local script on remote host via SSH
ssh root@<remoteServer> "bash -s" < /opt/script.shRun 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
Find files that ends with tilde
Find files:
find . -type f -name '*~'
To delete the files:
find . -type f -name '*~' -exec rm -f '{}' \;
Wget behind proxy
Add this lines in /etc/wgetrc file
use_proxy=yes
http_proxy=http://<proxy>:<port>
https_proxy=http://<proxy>:<port>
Shell get lines interval from a text file
cat file | head -n 16482 | tail -n 258
using sed:
sed -n '16224,16482p' in.sql > out.sql
using awk:
awk 'NR>=16224&&NR<=16482' in.sql > out.sql
View network connections, ports and process
View network connections, ports and process:
lsof command example
Type the following command to see IPv4 port(s), enter:
# lsof -Pnl +M -i4
Type the following command to see IPv6 listing port(s), enter:
# lsof -Pnl +M -i6
Process information
# lsof -p PID
netstat command example
Type the command as follows:
# netstat -patun
OR
# netstat -netpl
Domain controller verbose mode
Put the domain controller in verbose logging for the
netlogon service to actually find out where the logon attempt was coming
from.
First, open up command prompt as an administrator and execute the following command:
nltest /dbflag:0x2080ffff
Once done, execute the following command to turn off the debugging:
nltest /dbflag:0x0
This logs every transaction made to the file: %windir%\debug\netlogon.log (note, you need to run notepad as an administrator to read this file).
source: https://support.microsoft.com/en-us/help/109626/enabling-debug-logging-for-the-netlogon-service
nltest /dbflag:0x2080ffff
Once done, execute the following command to turn off the debugging:
nltest /dbflag:0x0
This logs every transaction made to the file: %windir%\debug\netlogon.log (note, you need to run notepad as an administrator to read this file).
source: https://support.microsoft.com/en-us/help/109626/enabling-debug-logging-for-the-netlogon-service
Rsync with SSH
On source server:
rsync -arvz -e 'ssh -p 22' –progress /local-folder remote_user@remote_ip:/remote-folder
Shell install/uninstall apk file
Show devices
adb devices
Install apk
adb install apk_name.apk
Unistall
adb shell
Find out your apps package name:
pm list packages | grep "app name/something related to your app name"
Then use:
adb uninstall package_name
OR
pm uninstall package_name
Disable apport at boot
pico /etc/default/apport
Change the line that says enabled=1 to enabled=0 to disable Apport.
To re-enable, change it back.
Remove files 30+ days old
#!/bin/bash
# log and delete files 30 days old
FILENAME=FILES_$(date +%Y%m%d%H%M%m).log
find . -mtime +30 -exec echo {} \; > $FILENAME
rm -rfv $(cat $FILENAME)
# log and delete files 30 days old
FILENAME=FILES_$(date +%Y%m%d%H%M%m).log
find . -mtime +30 -exec echo {} \; > $FILENAME
rm -rfv $(cat $FILENAME)
Dicas do comando FIND
1. Listar todos os arquivos contidos em um diretório e subdiretórios
Para exibir uma lista com todos os arquivos localizados em um determinado diretório, incluindo os arquivos armazenados nos subdiretórios, basta aplicar o comando find da seguinte forma:
$ find .
./exemplo.txt
./subpasta
./subpasta/comandofind.php
./audio.mp4
./exemplo2.php
2. Especificar um limite de subdiretórios a serem exibidos
Imaginemos uma situação em que o primeiro exemplo tenha sido aplicado e haja dezenas de subdiretórios que sendo exibidos na lista. No caso, você não precisa receber tantas informações, e então deseja que somente os primeiros subdiretórios sejam exibidos.
Leia também ... Servidor De Arquivos: Como Implementar Utilizando Linux (Mesmo Em Redes Com Windows)
Para isso, estabeleça uma condição que defina o nível de “profundidade” na navegação dos subdiretórios por meio do maxdepth:
$ find ./test -maxdepth 1 -name *.php
./test/comandofind.php
Caso a intenção seja a de localizar arquivos com um maior nível de profundidade, este nível deverá ser especificado logo após digitar “-maxdepth”. Exemplo:
$ find ./test -maxdepth 2 -name "*.php"
./test/subpasta/comandofind.php
./test/exemplo2.php
3. Combinar múltiplos critérios de busca
Estabelecer mais de um critério em uma mesma busca é mais simples do que se pode imaginar. Vamos supor que o usuário necessite localizar um arquivo chamado “comandofind.txt”, de forma que o “comandfind.php” não apareça — para isso, utiliza-se o inversion (!).
$ find ./test -name 'comandofind*' ! -name '*.php'
./test/comandofind.txt
É possível, também, aplicar a condição OR para estabelecer ainda mais critérios. Se o usuário quiser localizar arquivos levando em conta os formatos “txt” e “php”, basta incluir o caractere “o” na linha de comando.
$ find -name '*.php' -o -name '*.txt'
./exemplo.txt
./subdir/comandofind.php
./exemplo2.php
./exemplo3.txt
4. Localizar somente arquivos ou somente diretórios
Nos exemplos anteriores, percebe-se que arquivos e diretórios são listados juntos em cada busca. Porém, é possível buscar somente por uma das duas coisas:
$ find ./test -name exemplo*
./test/exemplo.txt
./test/exemplo
Somente arquivos
$ find ./test -type f -name "exemplo*"
./test/exemplo.txt
Somente diretórios
$ find ./test -type d -name "exemplo*"
./test/exemplo
Perceba que, na busca por arquivos, basta incluir “-type f” antes de digitar o nome, enquanto na busca por diretório inclui-se o “-type d”. Não por acaso, as letras representam as iniciais para files (arquivos) e directories (diretórios).
5. Localizar arquivos ocultos
Até agora, nós explicamos como usar o comando find para encontrar arquivos comuns, tendo plena ciência de seus nomes ou formatos. Mas como localizar os arquivos ocultos nos diretórios?
Muitas vezes, nem sabemos que existe um arquivo oculto — o que nos leva a desconhecer o nome do mesmo. Porém, apesar desse “pequeno” detalhe, encontrar esses arquivos é muito fácil.
Basta especificar que está buscando apenas arquivos (-type f) e usar um ponto final (.) no lugar do nome. Veja:
$ find ~ -type f -name ".*"
6. Encontrar arquivos com determinadas permissões
Se o termo “permissões” ainda não ficou muito claro para você, não se preocupe! No sistema Linux, as permissões são muito comuns, e são utilizadas justamente para definir os usuários que podem acessar determinados arquivos e diretórios.
E, como mencionamos no início do texto, o comando find pode ser utilizado para localizar arquivos e diretórios a partir de uma determinada permissão. Supondo que a permissão em questão seja a “permissão 0740”, o comando para localizar arquivos deve ser feito da seguinte forma:
$ find . -type f -perm 0740
./exemplo.txt
./subpasta/comandofind.php
./audio.mp4
./exemplo2.php
Lembra-se do inversion, a condição representada pelo ponto de exclamação? Ela pode ser aplicada para detectar possíveis erros de segurança ligados às permissões.
$ find . -type f -perm 0655
./exemplo.txt
./subpasta/comandofind.php
./audio.mp4
./exemplo2.php
7. Encontrar arquivos com base em proprietários
Assim como é possível utilizar o comando find para localizar arquivos a partir de uma permissão, o mesmo pode ser feito a partir de um determinado grupo ou owner.
Exemplo: para localizar arquivos pertencentes ao diretório de um determinado usuário chamado Maria, basta utilizar a condição “–user” e digitar o nome do usuário.
$ find . –user maria
./exemplo.txt
./subpasta/comandofind.php
./audio.mp4
./exemplo2.php
Para estabelecer um critério de busca, basta inseri-lo logo após o nome do usuário. Exemplo:
$ find . –user maria –name ‘*.txt’
8. Localizar arquivos pertencentes a um grupo
Se a ideia for usar o comando find com base em um determinado grupo (chamado “adm”, por exemplo), basta escrever a seguinte linha:
# find /var/www –group adm
9. Pesquisar por arquivos e diretórios com base em períodos de modificação
Uma das funcionalidades mais úteis do comando find é a pesquisa baseada em data e hora de modificação. Nos aspectos de segurança, podemos considerar esse critério fundamental. A seguir, apresentaremos alguns exemplos.
Localizar arquivos modificados há ‘N’ dias
Vamos supor que o usuário em questão deseje acessar arquivos modificados há 5 dias.
# find / -ntime 5
Localizar arquivos acessados há ‘N’ dias
Para isso, basta trocar o “–ntime” por “-atime”.
# find / -atime 5
Localizar arquivos modificados entre X e Y dias atrás
Se, por exemplo, o usuário precisar localizar arquivos modificados entre 30 e 90 dias atrás, basta digitar:
# find / -mtime +30 –mtime -90
Criados + de 30 dias
#find / -ctime +30
Criados - de 30 dias
#find / -ctime -30
Criados + de 30 dias
#find / -ctime +30
Criados - de 30 dias
#find / -ctime -30
Criados exatos 30 dias
#find / -ctime 30
10. Localizar arquivos com base no tamanho
Para utilizar o tamanho do arquivo como critério, utiliza-se o “-size” no comando find. Utilizemos como exemplo a busca por arquivos de 40MB:
# find / -size 40M
11. Arquivos criados em data específica
# find . -type f -newermt 2017-06-07 ! -newermt 2017-06-08
11. Arquivos criados em data específica
# find . -type f -newermt 2017-06-07 ! -newermt 2017-06-08
source: https://e-tinet.com/linux/comando-find-linux/
Shell script input trick
In the occasion where you are not sure how long the user input might be and you want to capture it all, you would use
In script run_this.sh:
userInputs=($@)
for i in "${userInputs[@]}";; do
echo "$i"
done
Running the command:
./run_this.sh who knows how long this can go
who
knows
how
long
this
can
go
source: https://medium.freecodecamp.org/functional-and-flexible-shell-scripting-tricks-a2d693be2dd4
$@
instead. In the following example, I took in the entire string and
print it out word by word after breaking them into a string array
according to the spaces in between. In script run_this.sh:
userInputs=($@)
for i in "${userInputs[@]}";; do
echo "$i"
done
Running the command:
./run_this.sh who knows how long this can go
who
knows
how
long
this
can
go
source: https://medium.freecodecamp.org/functional-and-flexible-shell-scripting-tricks-a2d693be2dd4
Remove comments and whitespaces with sed
pico /usr/bin/scrub
# Remove all comments and empty lines
sed -e ‘s/#.*//’ -e ‘s/[ ^I]*$//’ -e ‘/^$/ d’ $1
chmod 755 /usr/bin/scrub
pico /usr/bin/clrspace
# Remove all leading and trailing whitespace from each line;
sed ‘s/^[ t]*//;s/[ t]*$//’ $1
chmod 755 /usr/bin/clrspace
now you can simply run
scrub filename
clrspace filename
# Remove all comments and empty lines
sed -e ‘s/#.*//’ -e ‘s/[ ^I]*$//’ -e ‘/^$/ d’ $1
chmod 755 /usr/bin/scrub
pico /usr/bin/clrspace
# Remove all leading and trailing whitespace from each line;
sed ‘s/^[ t]*//;s/[ t]*$//’ $1
chmod 755 /usr/bin/clrspace
now you can simply run
scrub filename
clrspace filename
Linux shell network monitoring tools
1. Overall bandwidth - nload, bmon, slurm, bwm-ng, cbm, speedometer, netload
2. Overall bandwidth (batch style output) - vnstat, ifstat, dstat, collectl
2. Bandwidth per socket connection - iftop, iptraf, tcptrack, pktstat, netwatch, trafshow
3. Bandwidth per process - nethogs
Protect files and folders
Install safe-rm
sudo apt-get install safe-rm
Edit the conf file adding the folders path
pico /etc/safe-rm.conf
AWK get text between two patterns
awk '/BEGIN/,/END/' info.txt
***** BEGIN ***** BASH is awesome BASH is awesome ***** END *****
Ubuntu 18.04 change hostname
1. Change the hostname using hostnamectl.
In Ubuntu 18.04 we can change the system hostname and related settings using the command hostnamectl.
For example is we want to change the system static hostname to linuxize, we can use the following command:
sudo hostnamectl set-hostname linuxize
2. Edit the /etc/hosts file.Open the /etc/hosts file and change the old hostname to the new one.
127.0.0.1 localhost
127.0.0.1 linuxize
3. Edit the cloud.cfg file.
If the cloud-init package is installed you also need to edit the cloud.cfg file. This package is usually installed by default in the images provided by the cloud providers such as AWS and it is used to handle the initialization of the cloud instances.
To check if the package is installed run the following ls command:
ls -l /etc/cloud/cloud.cfg
In this case you’ll need to open the /etc/cloud/cloud.cfg file:
sudo nano /etc/cloud/cloud.cfg
Search for preserve_hostname and change the value from false to true:
# This will cause the set+update hostname module to not operate (if true)
preserve_hostname: true
Assinar:
Postagens (Atom)
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
-
Find Users Who Have Never Logged On Use the following PowerShell Command; Get-ADUser -Filter { LastLogonDate -notlike "*" -and En...
-
First you have to configure a wpad site in your IIS Open the proxypac.pac file you have previously created and save as wpad.dat. Copy wpa...
-
Java Keytool Command These commands allow you to generate a new Java Keytool keystore file, create a CSR, and import certificates. A...