Scripts Linux.









backup mariadb e pastas



echo “Programa de backup”

dadosfull() {
SRCDIR=”/pasta/” #diretórios que serão feito backup
DSTDIR=/pastadestino/ #diretório de destino do backup
DATA=`date +”%d-%m-%Y”` #pega data atual
TIME_BKCP=+15 #número de dias em que será apagado o arquivo de backup
USER=”utilizador com permissao paras as bds”
PASSWORD=’password’
OUTPUT=”pastadestino/” # pasta destino bds

#criar o arquivo full-data.tar no diretório de destino
ARQ=$DSTDIR/full-$DATA.zip
#data de inicio backup
DATAIN=`date +%c`
echo “Data de inicio: $DATAIN”
}

backupfull(){
sync
zip -r $ARQ $SRCDIR -x “/srv/www/htdocs/owncloud/*” “/srv/www/htdocs/phpMyAdmin/*”
rm “$OUTPUT/*gz” > /dev/null 2>&1
databases=`mysql –user=$USER –password=$PASSWORD -e “SHOW DATABASES;” | tr -d “| ” | grep -v Database`
for db in $databases; do
if [[ “$db” != “information_schema” ]] && [[ “$db” != _* ]] && [[ “$db” != “phpmyadmin” ]] && [[ “$db” != “mysql” ]] && [[ “$db” != “performance_schema” ]] && [[ “$db” != “Owncloud” ]]; then
echo “Dumping database: $db”
mysqldump –force –opt –user=$USER –password=$PASSWORD –databases $db > $OUTPUT/$DATA.$db.sql
gzip $OUTPUT/$DATA.$db.sql
fi
done

if [ $? -eq 0 ] ; then
echo “—————————————-”

echo “Backup Full concluído com Sucesso”
DATAFIN=`date +%c`
echo “Data de termino: $DATAFIN”
echo “Backup realizado com sucesso” >> /var/log/backup_full.log
echo “Criado pelo usuário: $USER” >> /var/log/backup_full.log
echo “INICIO: $DATAIN” >> /var/log/backup_full.log
echo “FIM: $DATAFIN” >> /var/log/backup_full.log
echo “—————————————–” >> /var/log/backup_full.log
echo ” ”
echo “Log gerado em /var/log/backup_full.log”
else
echo “ERRO! Backup do dia $DATAIN” >> /var/log/backup_full.log
fi
}

procuraedestroifull(){
#apagando ficheiros mais antigos (a mais de X dias que existe)
find $DSTDIR -name “full*” -ctime $TIME_BKCP -exec rm -f {} “;”
if [ $? -eq 0 ] ; then
echo “Nao existe ficheiro antigo para eliminar!”
else
echo “Ficheiro antigo eliminado!”
fi
}

dadosfull
backupfull
procuraedestroifull
exit 0










Configurar postfix para gmail



1. Install Required Software


Debian, Ubuntu:
apt-get update && apt-get install postfix mailutils
When prompted for “General type of mail configuration,” choose Internet Site.
When prompted for a “Mail name,” choose a hostname to be used in mail headers as the origin of your emails. A fully-qualified domain name is preferred, but using your machine’s simple hostname is OK. Regardless of what you enter here, your return address will appear to recipients as your Gmail address.
You may be prompted to set the “Root and postmaster mail recipient.” Enter root, or another user who should receive mail subsystem notifications.
For any other prompts, you can choose the default values.

Fedora:
dnf update && dnf install postfix mailx

CentOS:
yum update && yum install postfix mailx cyrus-sasl cyrus-sasl-plain
OpenSUSE:

zypper update && zypper install postfix mailx cyrus-sasl
Arch Linux:
pacman -Sy postfix mailutils
FreeBSD:

Compile Postfix from the ports collection to incorporate support for SASL:
portsnap fetch extract update
cd /usr/ports/mail/postfix
make config
In the configuration dialogs, select SASL support. All other options can remain the same. Then:
make install clean
Mailx can be installed from the binary package:
pkg install mailx

2. Configure Gmail Authentication


Create or modify a password file which will be used by Postfix to establish authentication with Gmail. In the authentication information below, replace username with your Gmail username and password with your Gmail password. If you are using a custom Gmail Apps domain name, you may replace gmail.com with your Google Apps domain.

The password file will reside in the Postfix configuration directory. The file can be named whatever you like, but the recommended filename is sasl_passwd.

Debian, Ubuntu, Fedora, CentOS, OpenSUSE, Arch Linux:

Postfix configuration files reside in the directory /etc/postfix. Create or edit the password file:
vi /etc/postfix/sasl_passwd
Add the line:
[smtp.gmail.com]:587 username@gmail.com:password
tive que tirar os parentises retos para funcionar o melhor é tirar mesmo
Save and close the file. Your Gmail password is stored as plaintext, so make the file accessible only by root:
# chmod 600 /etc/postfix/sasl_passwd

FreeBSD:

Postfix configuration files reside in the directory /usr/local/etc/postfix. Create or edit the password file:
vi /usr/local/etc/postfix/sasl_passwd
Add the line:
[smtp.gmail.com]:587 username@gmail.com:password
Save and close the file. Make it accessible only by root:
chmod 600 /usr/local/etc/postfix/sasl_passwd

3. Configure Postfix



There are six parameters which must be set in the Postfix configuration file main.cf. The parameters are:
relayhost, which specifies the mail relay host and port number. The host name will be enclosed in brackets to specify that no MX lookup is required.
smtp_use_tls, which enables (or disables) transport layer security.
smtp_sasl_auth_enable, which enables (or disables) SASL authentication.
smtp_sasl_security_options, which in the following configuration will be set to empty, to ensure that no Gmail-incompatible security options are used.
smtp_sasl_password_maps, which specifies the password file to use. This file will be compiled and hashed by postmap in a later step.
smtp_tls_CAfile, which specifies the list of certificate authorities to use when verifying server identity.

Debian, Ubuntu, Arch Linux:

Edit the main Postfix configuration file:
vi /etc/postfix/main.cf
Add or modify the following values:
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Save and close the file.

Fedora, CentOS:

Edit the main Postfix configuration file:
vi /etc/postfix/main.cf
Add or modify the following values:
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-bundle.crt

Save and close the file.

OpenSUSE:

Edit the main Postfix configuration file:
vi /etc/postfix/main.cf
Add or modify the following values:
relayhost = [smtp.gmail.com]:587
em outro server tive que retirar os parentisis retos relayhost = smtp.gmail.com:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
versão nova smtp_sasl_password_maps = lmdb:/etc/postfix/sasl_passwd

smtp_sasl_mechanism_filter = login plain

smtp_tls_CAfile = /etc/ssl/ca-bundle.pem
smtp_tls_security_level = may
Save and close the file.

OpenSUSE also requires that the Postfix master process configuration file master.cf be modified. Open it for editing:
vi /etc/postfix/master.cf
Locate the line which reads:
#tlsmgr unix – – n 1000? 1 tlsmgr
Uncomment it, so it reads:
tlsmgr unix – – n 1000? 1 tlsmg
Save and close the file.

FreeBSD:

Edit the main Postfix configuration file:
vi /usr/local/etc/postfix/main.cf
Add or modify the following values:
relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/usr/local/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/mail/certs/cacert.pem

Save and close the file.

4. Process Password File



Use postmap to compile and hash the contents of sasl_passwd. The results will be stored in your Postfix configuration directory in the file sasl_passwd.db.

Debian, Ubuntu, Fedora, CentOS, OpenSUSE, Arch Linux:

postmap /etc/postfix/sasl_passwd

FreeBSD:

postmap /usr/local/etc/postfix/sasl_passwd

5. Restart Postfix



Restart the Postfix service, putting your changes into effect.

Debian, Ubuntu, Fedora, CentOS, OpenSUSE, Arch Linux:

systemctl restart postfix.service

FreeBSD:

To start the Postfix service for this session only:
service postfix onestart
To start Postfix automatically when the system initializes, open /etc/rc.conf for editing:
vi /etc/rc.conf
Add the line:
postfix_enable=YES
Save and close the file. You may then run:
service postfix start
To start Postfix.

6. Enable “Less Secure Apps” In Gmail



By default, only the most secure sign-ins, such as logging in to Gmail on the web, are allowed for your Gmail account. To permit relay requests, log in to your Gmail account and turn on Allow less secure apps.
For more information, review the Google Support document “Allowing less secure apps to access your account.”

7. Send A Test Email



Test your new configuration by sending an email using the mail command. Run:
mail -s “Test subject” recipient@domain.com
You will be presented with a blank line (or a CC: field, which you can bypass by pressing Enter). Type the body of your message, pressing Enter for new lines. When you are finished composing the email, type CTRL-D to send it. To cancel the email, press CTRL-C twice.
To send a precomposed email, use the command:
mail -s “Subject Here” recipient@domain.com < textfile
Where textfile is the name of a file containing the text to be sent.

Troubleshooting
If it’s not working, check the logs for any Postfix errors:

Debian:

less /var/log/mail.log

Ubuntu, Fedora, CentOS, OpenSUSE, Arch Linux:

journalctl

FreeBSD:

less /var/log/maillog
If you receive authentication errors from Gmail, verify that Allow Less Secure Apps is turned on in your Gmail account settings, as specified in Step 6.
Verify that the password file sasl_passwd exists, and that its contents are formatted correctly, as specified in Step 2. If you make any changes to the password file, make sure to repeat Steps 4 and 5 to hash the new password file and restart Postfix.
If you see any TLS errors, double check the configuration in main.cf as specified in Step 3. If you make any configuration changes, restart Postfix as specified in Step 5.


-------------------------------------
contas gmail
ativar verificacao 2 passos na conta google
criar uma app password
colocar a password gerada no ficheiro /etc/postfix/sasl_passwd
executar postmap /etc/postfix/sasl_passwd
executar postfix reload















Script para verificar se servico esta ativo




#!/bin/bash
service=nome_do_servico

if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
then
echo “$service is running!!!”
else
/etc/init.d/$service start //comando para iniciar o servico
fi










Comando rsync porta diferente verbose mostra progresso



rsync --progress --bwlimit=500 -vr --rsh='ssh -p22' /run/media/xxx/E2B_PTN3/xxxx/ xxx@xxx.net:/mnt/xxxx/xxxx
rsync --rsh='ssh -p30' --progress -v (/origem/*) utilizador@servidor.net:/destino/













Script para inicialização linux




#!/bin/bash
# chkconfig: 2345 20 80
# description: descrição do script

# libraria de funcoes.
. /etc/init.d/functions

start() {
# codigo de arranque caso opcao start
}

stop() {
# codigo para parar o script
# exemplo: killproc program_name
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
#codigo status
# exemplo: status program_name
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
esac










certificado de linux para windows



Criar um ficheiro para crt e um para key

openssl pkcs12 -export -out ficheiro_que_sera_gerado-output.pfx -inkey ficheiro_key_retirado do site.key -in certificado_retirado_do_site.crt


No IISImportar o certificado para o windows

No IIS Ir ao SITE botao lado direito "edit bindings" editar certificado porta 443 e escolher o certificado restart SITE lado direito












Instalar certificado no homeassistant por ssh



ssh homeassistant.xxxx.net
cd /ssh
vi privkey.pem
Colar private key
vi fullchain.pem
Colar certificado
ha core restart










Vim backup automatico



/usr/share/vim/vim-ULTIMA VERSAO
editar defaults.vim

colar a seguinte linha
:au! BufWrite * execute "w" expand("%") . strftime(".%y%m%d.%H%M%S")











Criar servico e arrancar vm no arranque automatico



Criar um ficheiro nome.service em /etc/systemd/system
[Unit]
Description = VirtualBox LAMP Server

[Service]
Type = idle
User=dos
Group=vboxusers
ExecStart = /usr/bin/VBoxHeadless --startvm "LAMP"
ExecStop = /usr/bin/VBoxManage controlvm "LAMP" poweroff
ExecStopPost = /usr/bin/sleep 40
Restart = on-abort
StartLimitInterval = 60
StartLimitBurst = 10

[Install]
WantedBy = multi-user.target







I then enabled the service and can start/stop using the normal systemd commands. I used a 40 second delay on stop so that the vm does a clean shutdown when I reboot my computer.














Raid 1








The post describes the steps to replace a mirror disk in a software RAID array. In this example, we have used /dev/sda1 as the known good partition, and /dev/sdb1 as the suspect or failing partition. Before proceeding, it is recommended to backup the original disk. Before removing raid disks, please make sure you run the following command to write all disk caches to the disk:

listar os discos no sistema (fdisk -l)

1. Mark the disk as failed

# mdadm --manage /dev/md0 --fail /dev/sd?1
# mdadm --manage /dev/md127 --fail /dev/sd?2

To verify that the disk is failed, check /proc/mdstat:

# cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid5] [raid4] [raid6] [raid10]
md0 : active raid1 sda1[0] sd?1[2](F)
976773168 blocks [2/1] [U_]

md1 : active raid1 sda2[0] sd?2[1]
976773168 blocks [2/2] [UU]

Failed disk will be marked as “(F)”.

2. Remove the disk by mdadm

# mdadm --manage /dev/md0 --remove /dev/sd?1
# mdadm --manage /dev/md127 --remove /dev/sd?2

3. Replace the disk

Replace the faulty disk with new one.
4. Copy the partition table to the new disk

Copy the partition table to the new disk (Caution: This sfdisk command will replace the entire partition table on the target disk with that of the source disk – use an alternative command if you need to preserve other partition information):

# sfdisk -d /dev/sda | sfdisk /dev/sd?

5. Create mirror

Create the mirror of the disk:

# mdadm --manage /dev/md0 --add /dev/sd?1
# mdadm --manage /dev/md127 --add /dev/sd?2

6. Verify

To test the setup, enter the below command:

# /sbin/mdadm --detail /dev/md0
# /sbin/mdadm --detail /dev/md127

The following command will show the current progress of the recovery of the mirror disk:

# cat /proc/mdstat

Opensuse ou outros, depois deste passo apenas um disco tem boot, o disco que foi substituido não tem o boot instalado
Para instalar o boot é necessario editar o seguinte ficheiro vi /etc/default/grub_installdevice e retirar o disco avariado e colocar o novo.
Para ver qual é o nome dos disco o comando é: ls -l /dev/disk/by-id
Depois temos que restaurar o boot
update-bootloader --reinit










VNC





verificar ligaçoes vnc
ps -ef|grep vnc
kill processo

iniciar conecao vnc como root escrever: vncsession utilizador :1

atuallizar password vnc
na sessao DO UTILIZADOR: vncpasswd










CERTIFICADOS





certificado SSLCertificateFile /etc/apache2/ssl.crt/server.crt
key SSLCertificateKeyFile /etc/apache2/ssl.key/server.key
intermediate SSLCertificateChainFile /etc/apache2/ssl.csr/server.crt











TAR GZ




When in linux use the TAR command to preserve file permissions
Compress folder to folder.tar.gz:

Shell
tar -pcvzf file.tar.gz folder

Uncompress:

Just switch the ‘c’ flag to an ‘x’ to extract
Shell
tar -pxvzf file.tar.gz -C destination_folder

Cheatsheet:

p == preserve permissions
c == create archive
v == verbose (print names while making tar)
z == gzip
f == tar file name










Backupvm








#!/bin/bash

# This scripts loops through all the user's VirtualBox vm's, pauses them,
# exports them and then restores the original state.
#
# VirtualBox's snapshot system is not stable enough for unmonitored use yet.
#
# Vorkbaard, 2012-02-01

# =============== Set your variables here ===============

EXPORTDIR=/mnt/fotos/backup/
MYMAIL=nuno.c.catarino@gmail.com
VBOXMANAGE="/usr/bin/VBoxManage -q"

# =======================================================

# Generate a list of all vm's; use sed to remove the double quotes.

# Note: better not use quotes or spaces in your vm name. If you do,
# consider using the vms' ids instead of friendly names:
# for VMNAME in $(vboxmanage list vms | cud -t " " -f 2)
# Then you'd get the ids in your mail so you'd have to use vboxmanage
# showvminfo $id or something to retrieve the vm's name. I never use
# weird characters in my vm names anyway.

for VMNAME in $(VBoxManage list vms | cut -d " " -f 1 | sed -e 's/^"//' -e 's/"$//')
do

ERR="nothing"
SECONDS=0

# Delete old export.log file if it exists
if [ -e export.log ]; then rm export.log; fi

# Get the vm state
VMSTATE=$(VBoxManage showvminfo $VMNAME --machinereadable | grep "VMState=" | cut -f 2 -d "=")
echo "$VMNAME's state is: $VMSTATE."

# If the VM's state is running or paused, save its state
if [[ $VMSTATE == \"running\" || $VMSTATE == \"paused\" ]]; then
echo "Saving state..."
VBoxManage controlvm $VMNAME savestate
if [ $? -ne 0 ]; then ERR="saving the state"; fi
fi

# Export the vm as appliance
if [ "$ERR" == "nothing" ]; then
echo "Exporting the VM..."
VBoxManage export $VMNAME --output $EXPORTDIR/$VMNAME-new.ova &> export.log
if [ $? -ne 0 ]; then
ERR="exporting"
else
# Remove old backup and rename new one
if [ -e $EXPORTDIR/$VMNAME.ova ]; then rm $EXPORTDIR/$VMNAME.ova; fi
mv $EXPORTDIR/$VMNAME-new.ova $EXPORTDIR/$VMNAME.ova
# Get file size
FILESIZE=$(du -h $EXPORTDIR/$VMNAME.ova | cut -f 1)
fi
else
echo "Not exporting because the VM's state couldn't be saved." &> export.log
fi

# Resume the VM to its previous state if that state was paused or running
if [[ $VMSTATE == \"running\" || $VMSTATE == \"paused\" ]]; then
echo "Resuming previous state..."
VBoxManage startvm $VMNAME --type headless
if [ $? -ne 0 ]; then ERR="resuming"; fi
if [ $VMSTATE == \"paused\" ]; then
VBoxManage controlvm $VMNAME pause
if [ $? -ne 0 ]; then ERR="pausing"; fi
fi
fi

# Calculate duration
duration=$SECONDS
duration="Operation took $(($duration / 60)) minutes, $(($duration % 60)) seconds."

# Notify the admin
if [ "$ERR" == "nothing" ]; then
MAILBODY="Virtual Machine $VMNAME was exported succesfully!"
MAILBODY="$MAILBODY"$'\n'"$duration"
MAILBODY="$MAILBODY"$'\n'"Export filesize: $FILESIZE"
MAILSUBJECT="VM $VMNAME succesfully backed up"
else
MAILBODY="There was an error $ERR VM $VMNAME."
if [ "$ERR" == "exporting" ]; then
MAILBODY=$(echo $MAILBODY && cat export.log)
fi
MAILSUBJECT="Error exporting VM $VMNAME"
fi

# Send the mail
echo "$MAILBODY" | mail -s "$MAILSUBJECT" $MYMAIL

# Clean up
if [ -e export.log ]; then rm export.log; fi

done














chaves ssh



Para iniciar o processo de criação das chaves deve abrir o terminal e executar o comando:

ssh-keygen -t rsa
Primeiro devem indicar onde vão guardar as chaves (id_rsa e id_rsa.pub). Depois basta indicar uma passphrase para que as chaves sejam geradas.
criar pasta no servidor remoto para enviar chaves
ssh username@nome-servidor-remoto mkdir -p .ssh
enviar chaves
cat .ssh/id_rsa.pub | ssh username@nome-servidor-remoto 'cat >> .ssh/authorized_keys'









Criar vpn no windows(source) através do linux(destino) com ssh



1 no putty gravar uma sessao ssh para o server linux com as defenicoes habituais
2 No putty na opção SSH --> Tunnels --> no campo Source port colocar uma porta por ex 31415 e clicar Add, selecionar Opção Dynamic
Gravar Sessão

3 No browser instalar uma extensão vpn que permita criar uma configuração manual socks5
4 Na configuração manual da extensão colocar no server 127.0.0.1 porta por ex 31415 e escolher opção Socks5
___________________________________________________________

Linux --> Linux
1 No cliente ssh criar vpn através do commando
ssh -f -N -D 31415 user@servidor.net -P30
2 No browser instalar uma extensão vpn que permita criar uma configuração manual socks5
3 Na configuração manual da extensão colocar no server 127.0.0.1 porta por ex 31415 e escolher opção Socks5











Bypass local user windows



Forgot to disconnect internet, I was able to use this shift+f10 start ms-cxh:localonly At the Sign in to your microsoft account when oobe didn't work there anymore