Poblando el git

This commit is contained in:
aken 2023-07-12 11:43:15 +00:00
parent af1346715e
commit c7ad9a096d
109 changed files with 8128 additions and 0 deletions

View file

@ -0,0 +1,89 @@
-- Proporciona información acerca de los usuarios actuales, sesiones y procesos en una instancia de SQL Server.
USE [master]
GO
exec sp_who; -- sp_who2 da más datos.
-- sp_who [ [ @loginame = ] 'login' | session ID | 'ACTIVE' ]
-- MUESTRA BLOQUEOS
USE [master]
GO
SELECT spid,status,loginame,hostname,blk = CONVERT(char(3), blocked),dbname=SUBSTRING(DB_NAME(dbid),1, 10),cmd,waittype
FROM master.dbo.sysprocesses
WHERE spid IN (SELECT blocked FROM master.dbo.sysprocesses)
GO
-- MUESTRA PROCESOS BLOQUEADOS (sesión_id) Y BLOQUEANTES (block_session_id),
-- qué tipo de espera está involucrado y cuál es el tiempo de espera de ese bloqueo, así como los recursos involucrados.
USE [master]
GO
SELECT session_id,blocking_session_id,wait_time,wait_type,last_wait_type,wait_resource,transaction_isolation_level,lock_timeout
FROM sys.dm_exec_requests
WHERE blocking_session_id <> 0
GO
-- MUESTRA PROCESOS ORDENADOS POR CONSUMO DE CPU
USE [master]
GO
SELECT TOP 10
qs.total_worker_time/qs.execution_count as [Avg CPU Time],
SUBSTRING(qt.text,qs.statement_start_offset/2,
(case when qs.statement_end_offset = -1
then len(convert(nvarchar(max), qt.text)) * 2
else qs.statement_end_offset end -qs.statement_start_offset)/2)
as query_text,
qt.dbid, dbname=db_name(qt.dbid),
qt.objectid
FROM sys.dm_exec_query_stats qs
cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt
ORDER BY
[Avg CPU Time] DESC
-- MUESTRA CONTADORES DE EJECUCION
USE [master]
GO
SELECT TOP 10
qs.execution_count,
SUBSTRING(qt.text,qs.statement_start_offset/2,
(case when qs.statement_end_offset = -1
then len(convert(nvarchar(max), qt.text)) * 2
else qs.statement_end_offset end -qs.statement_start_offset)/2)
as query_text,
qt.dbid, dbname=db_name(qt.dbid),
qt.objectid
FROM sys.dm_exec_query_stats qs
cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt
ORDER BY
qs.execution_count DESC
-- QUERYS CON MAYOR CONSUMO
SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.TEXT)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2)+1),
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_logical_reads DESC -- logical reads
-- ORDER BY qs.total_logical_writes DESC -- logical writes
-- ORDER BY qs.total_worker_time DESC -- CPU time
-- Para terminar la sesión que bloquea, ID 74 en este caso, usamos el comando KILL.
KILL 74
GO

View file

@ -0,0 +1,80 @@
#Primero nos conectamos al equipo Core donde vamos a instalar el WSUS
Enter-PSSession -ComputerName WSUSSRV01
#Miramos que características tenemos que instalar
Get-WindowsFeature UpdateServices*
#Instalamos todos menos SQL
Install-WindowsFeature UpdateServices,UpdateServices-WidDB,UpdateServices-Services
#Comprobamos que se han instalado todo
Get-WindowsFeature UpdateServices*
#Inicializamos el disco y preparamos apra recibir los datos de las actualizaciones.
Get-Disk
Initialize-Disk -Number 1 -PartitionStyle MBR
New-Partition -DiskNumber 1 -UseMaximumSize
Get-Partition -PartitionNumber 1 | Format-Volume -FileSystem NTFS -NewFileSystemLabel «Data» -Confirm: $false
Set-Partition -DiskNumber 1 -NewDriveLetter E
#Llevamos a cabo la postinstalacion y le indicamos la ruta donde guardar las descargas
cd C:\Program Files\Update Services\Tools
WsusUtil.exe postinstall /?
wsusutil.exe postinstall CONTENT_DIR=E:\WSUS
#Creamos las variables necesarias para configurar el WSUS
$wsus=Get-WsusServer
#Ya que solo tenemos un servidor WSUS. Guardamos la configuración en una variable
$wsusconfig=$wsus.GetConfiguration()
#Configuramos el servidor como Upstream.
Set-WsusServerSynchronization -SyncFromMU
#Indicamos que solo queremos descargar actualizaciones y parches en inglés
$wsusconfig.AllUpdateLanguagesDssEnabled =$false
$wsusconfig.SetEnabledUpdateLanguages(«en»)
$wsusconfig.Save()
#Descargamos las bases de actualizaciones y parches
$subscription=$wsus.GetSubscription()
$subscription.StartSynchronizationForCategoryOnly()
While ($subscription.GetSynchronizationStatus() -ne NotProcessing){
Write-Host «.» -NoNewline
Start-Sleep -Seconds 20
}
Write-Host «Sync is done»
#Seleccionamos los productos de los que queremos descargar actualizaciones y parches
Get-WsusProduct | Where-Object{
$_.Product.Title -in(
Windows Server 2016,
Windows 10
)
}|Set-WsusProduct
#Clasificacion de actualizaciones que vamos a instalar. En nuestro caso solo Security y Critical.
Get-WsusClassification | Where-Object {
$_.Classification.Title -in (
#Update Rollups,
Security Updates,
Critical Updates
#Service Packs,
#Updates
)
} | Set-WsusClassification
#Vamos a programar la sincronizacion, para decirle cuando se va a ejecutar
$subscription.SynchronizeAutomatically=$true
$subscription.SynchronizeAutomaticallyTimeOfDay=(New-TimeSpan -Hours 0)
$subscription.NumberOfSynchronizationsPerDay=1
$subscription.Save()
$subscription.StartSynchronization()
#Aprobamos las actualizaciones y parches descargados
Get-WsusUpdate -Classification All -Approval Unapproved -Status FailedOrNeeded | Approve-WsusUpdate -Action -TargetGroupName “Unassigned Computers”
#Ver si tenemos equipos registrados en el WSUS
Get-WsusComputer

View file

@ -0,0 +1,28 @@
BACKUP DATABASE [Database]
TO DISK = N'J:\MSSQL11.SQLSRV\MSSQL\Backup\Database.bak'
WITH NOFORMAT,
INIT,
NAME = N'Database-Completa Base de datos Copia de seguridad',
SKIP,
NOREWIND,
NOUNLOAD,
STATS = 10;
DECLARE @backupSetId AS INT;
SELECT @backupSetId = position
FROM msdb..backupset
WHERE database_name=N'Database' AND
backup_set_id=(SELECT MAX(backup_set_id)
FROM msdb..backupset
WHERE database_name=N'Database' );
IF @backupSetId IS NULL BEGIN
RAISERROR(N'Error de comprobación. No se encuentra la información de copia de seguridad para la base de datos ''Database''.', 16, 1)
END
RESTORE VERIFYONLY
FROM DISK = N'J:\MSSQL11.SQLSRV\MSSQL\Backup\Database.bak'
WITH FILE = @backupSetId,
NOUNLOAD,
NOREWIND;

View file

@ -0,0 +1,13 @@
USE "DATABASE";
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE "DATABASE"
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DATABASE_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE "DATABASE"
SET RECOVERY FULL;
GO

BIN
filethingie-master.zip Normal file

Binary file not shown.

View file

@ -0,0 +1,6 @@
# !/bin/bash
# Programa para ejemplificar el uso de la descarga de información desde internet utilizando el comando wget
# Autor: Marco Toscano Freire - @martosfre
echo "Descargar información de internet"
wget https://www-us.apache.org/dist/tomcat/tomcat-8/v8.5.35/bin/apache-tomcat-8.5.35.zip

View file

@ -0,0 +1,24 @@
# !/bin/bash
# Programa para ejemplificar el uso de la sentencia de decisión if, else
# Autor: Marco Toscano Freire - @martosfre
notaClase=0
edad=0
echo "Ejemplo Sentencia If -else"
read -n1 -p "Indique cúal es su nota (1-9):" notaClase
echo -e "\n"
if (( $notaClase >= 7 )); then
echo "El alumno aprueba la materia"
else
echo "El alumno reprueba la materia"
fi
read -p "Indique cúal es su edad:" edad
if [ $edad -le 18 ]; then
echo "La persona no puede sufragar"
else
echo "La persona puede sufragar"
fi

View file

@ -0,0 +1,17 @@
# !/bin/bash
# Programa para ejemplificar el uso de la sentencia de decisión if, else if, else
# Autor: Marco Toscano Freire - @martosfre
edad=0
echo "Ejemplo Sentencia If -else"
read -p "Indique cúal es su edad:" edad
if [ $edad -le 18 ]; then
echo "La persona es adolescente"
elif [ $edad -ge 19 ] && [ $edad -le 64 ]; then
echo "La persona es adulta"
else
echo "La persona es adulto mayor"
fi

View file

@ -0,0 +1,24 @@
# !/bin/bash
# Programa para ejemplificar el uso de los ifs anidados
# Autor: Marco Toscano Freire - @martosfre
notaClase=0
continua=""
echo "Ejemplo Sentencia If -else"
read -n1 -p "Indique cúal es su nota (1-9):" notaClase
echo -e "\n"
if [ $notaClase -ge 7 ]; then
echo "El alumno aprueba la materia"
read -p "Si va continuar estudiando en el siguiente nivel (s/n):" continua
if [ $continua = "s" ]; then
echo "Bienvenido al siguiente nivel"
else
echo "Gracias por trabajar con nosotros, mucha suerte !!!"
fi
else
echo "El alumno reprueba la materia"
fi

View file

@ -0,0 +1,39 @@
# !/bin/bash
# Programa para ejemplificar el uso de expresiones condicionales
# Autor: Marco Toscano Freire - @martosfre
edad=0
pais=""
pathArchivo=""
read -p "Ingrese su edad:" edad
read -p "Ingrese su país:" pais
read -p "Ingrese el path de su archivo:" pathArchivo
echo -e "\nExpresiones Condicionales con números"
if [ $edad -lt 10 ]; then
echo "La persona es un niño o niña"
elif [ $edad -ge 10 ] && [ $edad -le 17 ]; then
echo "La persona se trata de un adolescente"
else
echo "La persona es mayor de edad"
fi
echo -e "\nExpresiones Condicionales con cadenas"
if [ $pais = "EEUU" ]; then
echo "La persona es Americana"
elif [ $pais = "Ecuador" ] || [ $pais = "Colombia" ]; then
echo "La persona es del Sur de América"
else
echo "Se desconoce la nacionalidad"
fi
echo -e "\nExpresiones Condicionales con archivos"
if [ -d $pathArchivo ]; then
echo "El directorio $pathArchivo existe"
else
echo "El directorio $pathArchivo no existe"
fi

View file

@ -0,0 +1,18 @@
# !/bin/bash
# Programa para ejemplificar el uso de la sentencia case
# Autor: Marco Toscano Freire - @martosfre
opcion=""
echo "Ejemplo Sentencia Case"
read -p "Ingrese una opción de la A - Z:" opcion
echo -e "\n"
case $opcion in
"A") echo -e "\nOperación Guardar Arhivo";;
"B") echo "Operación Eliminar Archivo";;
[C-E]) echo "No esta implementada la operación";;
"*") "Opción Incorrecta"
esac

View file

@ -0,0 +1,28 @@
# ! /bin/bash
# Programa para ejemplificar el uso de los arreglos
# Autor: Marco Toscano Freire - @martosfre
arregloNumeros=(1 2 3 4 5 6)
arregloCadenas=(Marco, Antonio, Pedro, Susana)
arregloRangos=({A..Z} {10..20})
#Imprimir todos los valores
echo "Arreglo de Números:${arregloNumeros[*]}"
echo "Arreglo de Cadenas:${arregloCadenas[*]}"
echo "Arreglo de Números:${arregloRangos[*]}"
#Imprimir los tamaños de los arreglos
echo "Tamaño Arreglo de Números:${#arregloNumeros[*]}"
echo "Tamaño Arreglo de Cadenas:${#arregloCadenas[*]}"
echo "Tamaño Arreglo de Números:${#arregloRangos[*]}"
#Imprimir la posición 3 del arreglo de números, cadenas de rango
echo "Posición 3 Arreglo de Números:${arregloNumeros[3]}"
echo "Posición 3 Arreglo de Cadenas:${arregloCadenas[3]}"
echo "Posición 3 Arreglo de Rangos:${arregloRangos[3]}"
#Añadir y eliminar valores en un arreglo
arregloNumeros[7]=20
unset arregloNumeros[0]
echo "Arreglo de Números:${arregloNumeros[*]}"
echo "Tamaño arreglo de Números:${#arregloNumeros[*]}"

View file

@ -0,0 +1,37 @@
# ! /bin/bash
# Programa para ejemplificar el uso de la sentencia de iteración for
# Autor: Marco Toscano Freire - @martosfre
arregloNumeros=(1 2 3 4 5 6)
echo "Iterar en la Lista de Números"
for num in ${arregloNumeros[*]}
do
echo "Número:$num"
done
echo "Iterar en la lista de Cadenas"
for nom in "Marco" "Pedro" "Luis" "Daniela"
do
echo "Nombres:$nom"
done
echo "Iterar en Archivos"
for fil in *
do
echo "Nombre archivo:$fil"
done
echo "Iterar utilizando un comando"
for fil in $(ls)
do
echo "Nombre archivo:$fil"
done
echo "Iterar utilizando el formato tradcional"
for ((i=1; i<10; i++))
do
echo "Número;$i"
done

View file

@ -0,0 +1,13 @@
# ! /bin/bash
# Programa para ejemplificar el uso de la sentencia de iteración while
# Autor: Marco Toscano Freire - @martosfre
numero=1
while [ $numero -ne 10 ]
do
echo "Imprimiendo $numero veces"
numero=$(( numero + 1 ))
done

View file

@ -0,0 +1,12 @@
# ! /bin/bash
# Programa para ejemplificar el uso de los loops anidados
# Autor: Marco Toscano Freire - @martosfre
echo "Loops Anidados"
for fil in $(ls)
do
for nombre in {1..4}
do
echo "Nombre archivo:$fil _ $nombre"
done
done

View file

@ -0,0 +1,18 @@
# ! /bin/bash
# Programa para ejemplificar el uso de break y continue
# Autor: Marco Toscano Freire - @martosfre
echo "Sentencias break y continue"
for fil in $(ls)
do
for nombre in {1..4}
do
if [ $fil = "10_download.sh" ]; then
break;
elif [[ $fil == 4* ]]; then
continue;
else
echo "Nombre archivo:$fil _ $nombre"
fi
done
done

View file

@ -0,0 +1,9 @@
#! /bin/bash
# PROGRAMA: U-POSG
echo "Programa Utilidades Postgres"
<<"COMENTARIO 1"
Programa para administrar las utilidades de la Base
de Datos Postgres
"COMENTARIO 1"
exit 0

View file

@ -0,0 +1,4 @@
# !/bin/bash
# Programa para realizar algunas operaciones utilitarios de Postgres
echo "Hola bienvenido al curso de Programación bash"

View file

@ -0,0 +1,49 @@
# ! /bin/bash
# Programa que permite manejar las utilidades de Postres
# Autor: Marco Toscano Freire - @martosfre
opcion=0
while :
do
#Limpiar la pantalla
clear
#Desplegar el menú de opciones
echo "_________________________________________"
echo "PGUTIL - Programa de Utilidad de Postgres"
echo "_________________________________________"
echo " MENÚ PRINCIPAL "
echo "_________________________________________"
echo "1. Instalar Postgres"
echo "2. Desinstalar Postgres"
echo "3. Sacar un respaldo"
echo "4. Restar respaldo"
echo "5. Salir"
#Leer los datos del usuario - capturar información
read -n1 -p "Ingrese una opción [1-5]:" opcion
#Validar la opción ingresada
case $opcion in
1)
echo -e "\nInstalar postgres....."
sleep 3
;;
2)
echo -e "\nDesinstalar postgres...."
sleep 3
;;
3)
echo -e "\nSacar respaldo..."
sleep 3
;;
4)
echo -e "\nRestaurar respaldo..."
sleep 3
;;
5)
echo "Salir del Programa"
exit 0
;;
esac
done

View file

@ -0,0 +1,17 @@
# ! /bin/bash
# Programa para ejemplificar la creación de archivos y directorios
# Autor: Marco Toscano Freire - @martosfre
echo "Archivos - Directorios"
if [ $1 = "d" ]; then
mkdir -m 755 $2
echo "Directorio creado correctamente"
ls -la $2
elif [ $1 == "f" ]; then
touch $2
echo "Archivo creado correctamente"
ls -la $2
else
echo "No existe esa opción: $1"
fi

View file

@ -0,0 +1,12 @@
# ! /bin/bash
# Programa para ejemplificar como se escribe en un archivo
# Autor: Marco Toscano Freire - @martosfre
echo "Escribir en un archivo"
echo "Valores escritos con el comando echo" >> $1
#Adición multilínea
cat <<EOM >>$1
$2
EOM

View file

@ -0,0 +1,16 @@
# ! /bin/bash
# Programa para ejemplificar como se lee en un archivo
# Autor: Marco Toscano Freire - @martosfre
echo "Leer en un archivo"
cat $1
echo -e "\nAlmacenar los valores en una variable"
valorCat=`cat $1`
echo "$valorCat"
# Se utiliza la variable IFS (Internal Field Separator) para evitar que los espacios en blanco al inicio al final se recortan
echo -e "\nLeer archivos línea por línea utilizando while"
while IFS= read linea
do
echo "$linea"
done < $1

View file

@ -0,0 +1,19 @@
# ! /bin/bash
# Programa para ejemplificar las operaciones de un archivo
# Autor: Marco Toscano Freire - @martosfre
echo "Operaciones de un archivo"
mkdir -m 755 backupScripts
echo -e "\nCopiar los scripts del directorio actual al nuevo directorio backupScripts"
cp *.* backupScripts/
ls -la backupScripts/
echo -e "\nMover el directorio backupScripts a otra ubicación: $HOME"
mv backupScripts $HOME
echo -e "\nEliminar los archivos .txt"
rm *.txt

View file

@ -0,0 +1,8 @@
# ! /bin/bash
# Programa para ejemplificar el empaquetamiento con el comando tar
# Autor: Marco Toscano Freire - @martosfre
echo "Empaquetar todos los scripts de la carpeta shellCourse"
tar -cvf shellCourse.tar *.sh

View file

@ -0,0 +1,13 @@
# ! /bin/bash
# Programa para ejemplificar el empaquetamiento con el comando tar y gzip
# Autor: Marco Toscano Freire - @martosfre
echo "Empaquetar todos los scripts de la carpeta shellCourse"
tar -cvf shellCourse.tar *.sh
# Cuando se empaqueta con gzip el empaquetamiento anterior se elimina
gzip shellCourse.tar
echo "Empaquetar un solo archivo, con un ratio 9"
gzip -9 9_options.sh

View file

@ -0,0 +1,11 @@
# ! /bin/bash
# Programa para ejemplificar el empaquetamiento con el comando pbzip
# Autor: Marco Toscano Freire - @martosfre
echo "Empaquetar todos los scripts de la carpeta shellCourse"
tar -cvf shellCourse.tar *.sh
pbzip2 -f shellCourse.tar
echo "Empaquetar un directorio con tar y pbzip2"
tar -cf *.sh -c > shellCourseDos.tar.bz2

View file

@ -0,0 +1,6 @@
# ! /bin/bash
# Programa para ejemplificar el empaquetamiento con clave utilizando zip
# Autor: Marco Toscano Freire - @martosfre
echo "Empaquetar todos los scripts de la carpeta shellCourse con zip y asignarle una clave de seguridad"
zip -e shellCourse.zip *.sh

View file

@ -0,0 +1,13 @@
# ! /bin/bash
# Programa para ejemplificar la forma de como transferir por la red utilizando el comando rsync, utilizando las opciones de empaquetamiento para optmizar la velocidad de transferencia
# Autor: Marco Toscano Freire - @martosfre
echo "Empaquetar todos los scripts de la carpeta shellCourse y transferirlos por la red a otro equpoutilizando el comando rsync"
host=""
usuario=""
read -p "Ingresar el host:" host
read -p "Ingresar el usuario:" usuario
echo -e "\nEn este momento se procederá a empaquetar la carpeta y transferirla según los datos ingresados"
rsync -avz $(pwd) $usuario@$host:/Users/martosfre/Downloads/platzi

View file

@ -0,0 +1,14 @@
# !/bin/bash
# Programa para revisar la declaración de variables
# Autor: Marco Toscano Freire - @martosfre
opcion=0
nombre=Marco
echo "Opción: $opcion y Nombre: $nombre"
# Exportar la variable nombre para que este disponible a los demás procesos
export nombre
# Llamar al siguiente script para recuperar la variable
./2_variables_2.sh

View file

@ -0,0 +1,6 @@
# !/bin/bash
# Programa para revisar la declaración de variables
# Autor: Marco Toscano Freire - @martosfre
echo "Opción nombre pasada del script anterior: $nombre"

View file

@ -0,0 +1,74 @@
# ! /bin/bash
# Programa que permite manejar las utilidades de Postres
# Autor: Marco Toscano Freire - @martosfre
opcion=0
# Función para instalar postgres
instalar_postgres () {
echo "Instalar postgres..."
}
# Función para desinstalar postgres
desinstalar_postgres () {
echo "Desinstalar postres..."
}
# Función para sacar un respaldo
sacar_respaldo () {
echo "Sacar respaldo..."
echo "Directorio backup: $1"
}
# Función para restaurar un respaldo
restaurar_respaldo () {
echo "Restaurar respaldo..."
echo "Directorio respaldo: $1"
}
while :
do
#Limpiar la pantalla
clear
#Desplegar el menú de opciones
echo "_________________________________________"
echo "PGUTIL - Programa de Utilidad de Postgres"
echo "_________________________________________"
echo " MENÚ PRINCIPAL "
echo "_________________________________________"
echo "1. Instalar Postgres"
echo "2. Desinstalar Postgres"
echo "3. Sacar un respaldo"
echo "4. Restar respaldo"
echo "5. Salir"
#Leer los datos del usuario - capturar información
read -n1 -p "Ingrese una opción [1-5]:" opcion
#Validar la opción ingresada
case $opcion in
1)
instalar_postgres
sleep 3
;;
2)
desinstalar_postgres
sleep 3
;;
3)
read -p "Directorio Backup:" directorioBackup
sacar_respaldo $directorioBackup
sleep 3
;;
4)
read -p "Directorio de Respaldos:" directorioRespaldos
restaurar_respaldo $directorioRespaldos
sleep 3
;;
5)
echo "Salir del Programa"
exit 0
;;
esac
done

View file

@ -0,0 +1,96 @@
# ! /bin/bash
# Programa que permite manejar las utilidades de Postres
# Autor: Marco Toscano Freire - @martosfre
opcion=0
# Función para instalar postgres
instalar_postgres () {
echo -e "\n Verificar instalación postgres ...."
verifyInstall=$(which psql)
if [ $? -eq 0 ]; then
echo -e "\n Postgres ya se encuentra instalado en el equipo"
else
read -s -p "Ingresar contraseña de sudo:" password
read -s -p "Ingresar contraseña a utilizar en postgres:" passwordPostgres
echo "$password" | sudo -S apt update
echo "$password" | sudo -S apt-get -y install postgresql postgresql-contrib
sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD '{$PASSWORDpOSTGRES}';"
echo "$password" | sudo -S systemctl enable postgresql.service
echo "$password" | sudo -S systemctl start postgresql.service
fi
read -n 1 -s -r -p "PRESIONE [ENTER] para continuar..."
}
# Función para desinstalar postgres
desinstalar_postgres () {
read -s -p "Ingresar contraseña de sudo:" password
echo -e "\n"
echo "$password" | sudo -S systemctl stop postgresql.service
echo "$password" | sudo -S apt-get -y --purge remove postgresql\*
echo "$password" | sudo -S rm -r /etc/postgresql
echo "$password" | sudo -S rm -r /etc/postgresql-common
echo "$password" | sudo -S rm -r /var/lib/postgresql
echo "$password" | sudo -S userdel -r postgres
echo "$password" | sudo -S groupdel postgresql
read -n 1 -s -r -p "PRESIONE [ENTER] para continuar..."
}
# Función para sacar un respaldo
sacar_respaldo () {
echo "Sacar respaldo..."i
echo "Directorio backup: $1"
}
# Función para restaurar un respaldo
restaurar_respaldo () {
echo "Restaurar respaldo..."
echo "Directorio respaldo: $1"
}
while :
do
#Limpiar la pantalla
clear
#Desplegar el menú de opciones
echo "_________________________________________"
echo "PGUTIL - Programa de Utilidad de Postgres"
echo "_________________________________________"
echo " MENÚ PRINCIPAL "
echo "_________________________________________"
echo "1. Instalar Postgres"
echo "2. Desinstalar Postgres"
echo "3. Sacar un respaldo"
echo "4. Restar respaldo"
echo "5. Salir"
#Leer los datos del usuario - capturar información
read -n1 -p "Ingrese una opción [1-5]:" opcion
#Validar la opción ingresada
case $opcion in
1)
instalar_postgres
sleep 3
;;
2)
desinstalar_postgres
sleep 3
;;
3)
read -p "Directorio Backup:" directorioBackup
sacar_respaldo $directorioBackup
sleep 3
;;
4)
read -p "Directorio de Respaldos:" directorioRespaldos
restaurar_respaldo $directorioRespaldos
sleep 3
;;
5)
echo "Salir del Programa"
exit 0
;;
esac
done

View file

@ -0,0 +1,133 @@
# ! /bin/bash
# Programa que permite manejar las utilidades de Postres
# Autor: Marco Toscano Freire - @martosfre
opcion=0
fechaActual=`date +%Y%m%d`
# Función para instalar postgres
instalar_postgres () {
echo -e "\n Verificar instalación postgres ...."
verifyInstall=$(which psql)
if [ $? -eq 0 ]; then
echo -e "\n Postgres ya se encuentra instalado en el equipo"
else
echo -e "\n"
read -s -p "Ingresar contraseña de sudo:" password
read -s -p "Ingresar contraseña a utilizar en postgres:" passwordPostgres
echo "$password" | sudo -S apt update
echo "$password" | sudo -S apt-get -y install postgresql postgresql-contrib
sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD '{$PASSWORDpOSTGRES}';"
echo "$password" | sudo -S systemctl enable postgresql.service
echo "$password" | sudo -S systemctl start postgresql.service
fi
read -n 1 -s -r -p "PRESIONE [ENTER] para continuar..."
}
# Función para desinstalar postgres
desinstalar_postgres () {
echo -e "\n"
read -s -p "Ingresar contraseña de sudo:" password
echo -e "\n"
echo "$password" | sudo -S systemctl stop postgresql.service
echo "$password" | sudo -S apt-get -y --purge remove postgresql\*
echo "$password" | sudo -S rm -r /etc/postgresql
echo "$password" | sudo -S rm -r /etc/postgresql-common
echo "$password" | sudo -S rm -r /var/lib/postgresql
echo "$password" | sudo -S userdel -r postgres
echo "$password" | sudo -S groupdel postgresql
read -n 1 -s -r -p "PRESIONE [ENTER] para continuar..."
}
# Función para sacar un respaldo
sacar_respaldo () {
echo "Listar las bases de datos"
sudo -u postgres psql -c "\l"
read -p "Elegir la base de datos a respaldar:" bddRespaldo
echo -e "\n"
if [ -d "$1" ]; then
echo "Establecer permisos directorio"
echo "$password" | sudo -S chmod 755 $1
echo "Realizando respaldo..."
sudo -u postgres pg_dump -Fc $bddRespaldo > "$1/bddRespaldo$fechaActual.bak"
echo "Respaldo realizado correctamente en la ubicación:$1/bddRespaldo$fechaActual.bak"
else
echo "El directorio $1 no existe"
fi
read -n 1 -s -r -p "PRESIONE [ENTER] para continuar..."
}
# Función para restaurar un respaldo
restaurar_respaldo () {
echo "Listar respaldos"
ls -1 $1/*.bak
read -p "Elegir el respaldo a restaurar:" respaldoRestaurar
echo -e "\n"
read -p "Ingrese el nombre de la base de datos destino:" bddDestino
#Verificar si la bdd existe
verifyBdd=$(sudo -u postgres psql -lqt | cut -d \| -f 1 | grep -wq $bddDestino)
if [ $? -eq 0 ]; then
echo "Restaurando en la bdd destino: $bddDestino"
else
sudo -u postgres psql -c "create database $bddDestino"
fi
if [ -f "$1/$respaldoRestaurar" ]; then
echo "Restaurando respaldo..."
sudo -u postgres pg_restore -Fc -d $bddDestino "$1/$respaldoRestaurar"
echo "Listar la base de datos"
sudo -u postgres psql -c "\l"
else
echo "El respaldo $respaldoRestaurar no existe"
fi
read -n 1 -s -r -p "PRESIONE [ENTER] para continuar..."
}
while :
do
#Limpiar la pantalla
clear
#Desplegar el menú de opciones
echo "_________________________________________"
echo "PGUTIL - Programa de Utilidad de Postgres"
echo "_________________________________________"
echo " MENÚ PRINCIPAL "
echo "_________________________________________"
echo "1. Instalar Postgres"
echo "2. Desinstalar Postgres"
echo "3. Sacar un respaldo"
echo "4. Restar respaldo"
echo "5. Salir"
#Leer los datos del usuario - capturar información
read -n1 -p "Ingrese una opción [1-5]:" opcion
#Validar la opción ingresada
case $opcion in
1)
instalar_postgres
sleep 3
;;
2)
desinstalar_postgres
sleep 3
;;
3)
echo -e "\n"
read -p "Directorio Backup:" directorioBackup
sacar_respaldo $directorioBackup
sleep 3
;;
4)
echo -e "\n"
read -p "Directorio de Respaldos:" directorioRespaldos
restaurar_respaldo $directorioRespaldos
sleep 3
;;
5)
echo "Salir del Programa"
exit 0
;;
esac
done

View file

@ -0,0 +1,34 @@
# ! /bin/bash
# Programa para revisar los tipos de operadores
# Autor: Marco Toscano - @martosfre
numA=10
numB=4
echo "Operadores Aritméticos"
echo "Números: A=$numA y B=$numB"
echo "Sumar A + B =" $((numA + numB))
echo "Restar A - B =" $((numA - numB))
echo "Multiplicar A * B =" $((numA * numB))
echo "Dividir A / B =" $((numA / numB))
echo "Residuo A % B =" $((numA % numB))
echo -e "\nOperadores Relaciones"
echo "Números: A=$numA y B=$numB"
echo "A > B =" $((numA > numB))
echo "A < B =" $((numA < numB))
echo "A >= B =" $((numA >= numB))
echo "A <= B =" $((numA <= numB))
echo "A == B =" $((numA == numB))
echo "A != B =" $((numA != numB))
echo -e "\nOperadores Asignación"
echo "Números: A=$numA y B=$numB"
echo "Sumar A += B" $((numA += numB))
echo "Restar A -= B" $((numA -= numB))
echo "Multiplicación A *= B" $((numA *= numB))
echo "Dividir A /= B" $((numA /= numB))
echo "Residuo A %= B" $((numA %= numB))

View file

@ -0,0 +1,10 @@
# ! /bin/bash
# Programa para ejemplificar el paso de argumentos
# Autor: Marco Toscano Freire - @martosfre
nombreCurso=$1
horarioCurso=$2
echo "El nombre del curso es: $nombreCurso dictado en el horario de $horarioCurso"
echo "El número de parámetros enviados es: $#"
echo "Los parámetros enviados son: $*"

View file

@ -0,0 +1,9 @@
# ! /bin/bash
# Programa para revisar como ejecutar comados dentro de un programa y almacenar en una variable para su posterior utilización
# Autor: Marco Toscano Freire - @martosfre
ubicacionActual=`pwd`
infoKernel=$(uname -a)
echo "La ubicación actual es la siguiente: $ubicacionActual"
echo "Información del Kernel: $infoKernel"

View file

@ -0,0 +1,15 @@
# ! /bin/bash
# Programa para ejemplificar como capturar la información del usuario utilizando el comando echo, read y $REPLY
# Autor: Marco Toscano Freire - @martosfre
option=0
backupName=""
echo "Programa Utilidades Postgres"
echo -n "Ingresar una opción:"
read
option=$REPLY
echo -n "Ingresar el nombre del archivo del backup:"
read
backupName=$REPLY
echo "Opción:$option , backupName:$backupName"

View file

@ -0,0 +1,11 @@
# ! /bin/bash
# Programa para ejemplificar como capturar la información del usuario utilizando el comando read
# Autor: Marco Toscano Freire - @martosfre
option=0
backupName=""
echo "Programa Utilidades Postgres"
read -p "Ingresar una opción:" option
read -p "Ingresar el nombre del archivo del backup:" backupName
echo "Opción:$option , backupName:$backupName"

View file

@ -0,0 +1,19 @@
# ! /bin/bash
# Programa para ejemplificar como capturar la información del usuario y validarla
# Autor: Marco Toscano Freire - @martosfre
option=0
backupName=""
clave=""
echo "Programa Utilidades Postgres"
# Acepta el ingreso de información de solo un caracter
read -n1 -p "Ingresar una opción:" option
echo -e "\n"
read -n10 -p "Ingresar el nombre del archivo del backup:" backupName
echo -e "\n"
echo "Opción:$option , backupName:$backupName"
read -s -p "Clave:" clave
echo "Clave: $clave"

View file

@ -0,0 +1,21 @@
# ! /bin/bash
# Programa para ejemplificar como se realiza el paso de opciones con sin parámetros
# Autor: Marco Toscano - @martosfre
echo "Programa Opciones"
echo "Opción 1 enviada: $1"
echo "Opción 2 enviada: $2"
echo "Opción enviadas: $*"
echo -e "\n"
echo "Recuperar valores"
while [ -n "$1" ]
do
case "$1" in
-a) echo "-a option utilizada";;
-b) echo "-b option utilizada";;
-c) echo "-c option utlizada";;
*) echo "$! no es una opción";;
esac
shift
done

28
linux/ban_unban_3.0.sh Normal file
View file

@ -0,0 +1,28 @@
#!/bin/bash
state=$(sudo /etc/init.d/fail2ban status | grep active | grep active | cut -d "s" -f 1)
echo $(hostname -A) > ./check_fail2ban/resultado.txt
echo "-------------------------------------------------------------------------------" >> ./check_fail2ban/resultado.txt
echo -e "El estado de fail2ban es $state \n" >> ./check_fail2ban/resultado.txt
#HACEMOS LISTA DE BANEOS Y HORAS
grep -e "Unban" -e "Ban" /var/log/fail2ban.log.1 | cut -d " " -f 2 > ./check_fail2ban/time.txt
grep -e "Unban" -e "Ban" /var/log/fail2ban.log.1 | cut -d "E" -f 2 > ./check_fail2ban/ban.txt
paste ./check_fail2ban/time.txt ./check_fail2ban/ban.txt > ./check_fail2ban/ban_unban.txt
echo "Esta es la lista de IPs baneadas y desbaneadas durante las ultimas 24 horas" >> ./check_fail2ban/resultado.txt
echo "-------------------------------------------------------------------------------" >> ./check_fail2ban/resultado.txt
#abrimos el fichero para sacar los datos y pasarlos a una variable
cat ./check_fail2ban/ban_unban.txt | \
#IFS es el separador de campo
while IFS=" " read time bantype ban ip
do
nsresult=$(sudo nslookup $ip | grep name | cut -d "=" -f 2)
echo $time" - "$bantype" - "$ip" - "$ban" - "$nsresult >> ./check_fail2ban/resultado.txt
echo " " >> ./check_fail2ban/resultado.txt
done
rm ./check_fail2ban/time.txt ./check_fail2ban/ban.txt ./check_fail2ban/ban_unban.txt
exit

18
linux/calculadora_fpm.sh Normal file
View file

@ -0,0 +1,18 @@
#!/bin/bash
FPM_MASTER_PID=4422
while true;
do
printf -- '-%.0s' {1..100}; echo ""
date --iso-8601=seconds
echo ""
pstree $FPM_MASTER_PID -c -l -p -U
echo ""
ps -ylC php-fpm --sort:rss -u nginx
echo ""
ps --no-headers -o "rss,cmd" -C php-fpm -u nginx | awk '{ sum+=$1 } END { printf ("%d%s\n", sum/NR/1024,"M") }'
echo ""
ps -eo size,pid,user,command --sort -size | awk '{ hr=$1/1024 ; printf("%13.2f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | grep "php-fpm:"
echo ""
sleep 2
done

View file

@ -0,0 +1,17 @@
#!/bin/bash
LAST_KERNEL=$(rpm -q --last kernel | perl -pe 's/^kernel-(\S+).*/$1/' | head -1)
CURRENT_KERNEL=$(uname -r)
if [[ $LAST_KERNEL != $CURRENT_KERNEL ]]
then
echo "REQUIERE REINICIO KERNEL" > ./check_reboot_needed.txt
else
NEEDRESTART=$(needs-restarting -r | grep 'Reboot is required' | cut -b 1-18)
if [[ $NEEDRESTART == "Reboot is required" ]]
then
echo "REQUIERE REINICIO OTHER" > ./check_reboot_needed.txt
else
echo "NO NECESITA REINICIARSE" > ./check_reboot_needed.txt
fi
fi
exit

37
linux/check_cifs_nfs.sh Normal file
View file

@ -0,0 +1,37 @@
#!/bin/bash
if [ "$#" -eq "0" ]
then
echo "Debe pasar la IP a comprobar: $0 ip"
exit
fi
IP=$1
echo "Comprobando hostname de $IP"
HOSTNAME=$(ssh "$IP" "hostname -f")
echo -e "Hostname: $HOSTNAME \nComprobando sistemas cifs / nfs"
cifs_fs=$(ssh globaluser@"$IP" "sudo df -t cifs -h")
nfs_fs=$(ssh globaluser@"$IP" "sudo df -t nfs -h")
nfs4_fs=$(ssh globaluser@"$IP" "sudo df -t nfs4 -h")
echo -e "CIFS:\n$cifs_fs\n"
echo -e "NFS:\n$nfs_fs\n"
echo -e "NFS4:\n$nfs4_fs\n"
cifs=$(echo "$cifs_fs" | tail -n +2 | awk -F " " '{ print $1"#"$2"#"$3"#"$4"#"$5"#"$6 }')
nfs=$(echo "$nfs_fs" | tail -n +2 | awk -F " " '{ print $1"#"$2"#"$3"#"$4"#"$5"#"$6 }')
nfs4=$(echo "$nfs4_fs" | tail -n +2 | awk -F " " '{ print $1"#"$2"#"$3"#"$4"#"$5"#"$6 }')
echo "hostname#ip#tipo#export#tamaño#usado#disponible#%uso#montado en"
if [[ "$cifs" != "" ]]; then
for fs in $cifs; do
echo "$HOSTNAME $IP cif $fs" | awk '{ print $1"#"$2"#"$3"#"$4 }'
done
fi
if [[ "$nfs" != "" ]]; then
#nfsVersion=$(ssh globaluser@"$IP" "sudo nfsstat -c | grep 'Client nfs' | awk -F ":" '{ print \$1 }' | awk '{ print \$3 }' | paste -s -d_") # el paste es por si hay varias versiones en varias lineas las concatene
for fs in $nfs; do
echo "$HOSTNAME $IP nfs_v3 $fs" | awk '{ print $1"#"$2"#"$3"#"$4 }'
done
fi
if [[ "$nfs4" != "" ]]; then
for fs in $nfs4
do
echo "$HOSTNAME $IP nfs_v4 $fs" | awk '{ print $1"#"$2"#"$3"#"$4 }'
done
fi

153
linux/check_log4j.sh Normal file
View file

@ -0,0 +1,153 @@
#!/bin/bash
# source https://github.com/rubo77/log4j_checker_beta
# needs locate to be installed, be sure to be up-to-date with
# sudo updatedb
# regular expression, for which packages to scan for:
PACKAGES='nginx\|solr\|elastic\|log4j'
export LANG=
RED="\033[0;31m"; GREEN="\033[32m"; YELLOW="\033[1;33m"; ENDCOLOR="\033[0m"
# if you don't want colored output, set the variables to empty strings:
# RED=""; GREEN=""; YELLOW=""; ENDCOLOR=""
function warning() {
printf "${RED}[WARNING] %s${ENDCOLOR}\n" "$1" >&2
}
function information() {
printf "${YELLOW}[INFO] %s${ENDCOLOR}\n" "$1"
}
function ok() {
printf "${GREEN}[INFO] %s${ENDCOLOR}\n" "$1"
}
function locate_log4j() {
if [ "$(command -v locate)" ]; then
locate log4j
else
find \
/var /etc /usr /opt /lib* \
-name "*log4j*" \
2>&1 \
| grep -v '^find:.* Permission denied$' \
| grep -v '^find:.* No such file or directory$'
fi
}
function find_jar_files() {
find \
/var /etc /usr /opt /lib* \
-name "*.jar" \
-o -name "*.war" \
-o -name "*.ear" \
2>&1 \
| grep -v '^find:.* Permission denied$' \
| grep -v '^find:.* No such file or directory$'
}
if [ $USER != root ]; then
warning "You have no root-rights. Not all files will be found."
fi
# Set this if you have a download for sha256 hashes
download_file=""
dir_temp_hashes=$(mktemp -d)
file_temp_hashes="$dir_temp_hashes/vulnerable.hashes"
ok_hashes=
if [[ -n $download_file && $(command -v wget) ]]; then
wget --max-redirect=0 --tries=2 --no-netrc -O "$file_temp_hashes.in" -- "$download_file"
elif [[ -n $download_file && $(command -v curl) ]]; then
curl --globoff -f "$download_file" -o "$file_temp_hashes.in"
fi
if [[ $? = 0 && -s "$file_temp_hashes.in" ]]; then
cat "$file_temp_hashes.in" | cut -d" " -f1 | sort | uniq > "$file_temp_hashes"
ok_hashes=1
information "Downloaded vulnerable hashes from ..."
fi
information "Looking for files containing log4j..."
if [ "$(command -v locate)" ]; then
information "using locate, which could be using outdated data. besure to have called updatedb recently"
fi
OUTPUT="$(locate_log4j | grep -iv log4js | grep -v log4j_checker_beta)"
if [ "$OUTPUT" ]; then
warning "Maybe vulnerable, those files contain the name:"
printf "%s\n" "$OUTPUT"
else
ok "No files containing log4j"
fi
information "Checking installed packages Solr ElasticSearch and packages containing log4j"
if [ "$(command -v yum)" ]; then
# using yum
OUTPUT="$(yum list installed | grep -i $PACKAGES | grep -iv log4js)"
if [ "$OUTPUT" ]; then
warning "Maybe vulnerable, yum installed packages:"
printf "%s\n" "$OUTPUT"
else
ok "No yum packages found"
fi
fi
if [ "$(command -v dpkg)" ]; then
# using dpkg
OUTPUT="$(dpkg -l | grep -i $PACKAGES | grep -iv log4js)"
if [ "$OUTPUT" ]; then
warning "Maybe vulnerable, dpkg installed packages:"
printf "%s\n" "$OUTPUT"
else
ok "No dpkg packages found"
fi
fi
information "Checking if Java is installed..."
JAVA="$(command -v java)"
if [ "$JAVA" ]; then
warning "Java is installed"
printf " %s\n %s\n" \
"Java applications often bundle their libraries inside binary files," \
"so there could be log4j in such applications."
else
ok "Java is not installed"
fi
information "Analyzing JAR/WAR/EAR files..."
if [ $ok_hashes ]; then
information "Also checking hashes"
fi
if [ "$(command -v unzip)" ]; then
find_jar_files | while read -r jar_file; do
unzip -l "$jar_file" 2> /dev/null \
| grep -q -i "log4j" \
&& warning "$jar_file contains log4j files"
if [ $ok_hashes ]; then
dir_unzip=$(mktemp -d)
base_name=$(basename "$jar_file")
unzip -qq -DD "$jar_file" '*.class' -d "$dir_unzip" \
&& find "$dir_unzip" -type f -not -name "*"$'\n'"*" -name '*.class' -exec sha256sum "{}" \; \
| cut -d" " -f1 | sort | uniq > "$dir_unzip/$base_name.hashes";
num_found=$(comm -12 "$file_temp_hashes" "$dir_unzip/$base_name.hashes" | wc -l)
if [[ -n $num_found && $num_found != 0 ]]; then
warning "$jar_file contains vulnerable binary classes"
else
ok "No .class files with known vulnerable hash found in $jar_file at first level."
fi
rm -rf -- "$dir_unzip"
fi
done
else
information "Cannot look for log4j inside JAR/WAR/EAR files (unzip not found)"
fi
[ $ok_hashes ] && rm -rf -- "$dir_temp_hashes"
information "_________________________________________________"
if [ "$JAVA" == "" ]; then
warning "Some apps bundle the vulnerable library in their own compiled package, so 'java' might not be installed but one such apps could still be vulnerable."
fi
echo
warning "This whole script is not 100% proof you are not vulnerable, but a strong hint"
echo

View file

@ -0,0 +1,26 @@
#!/bin/bash
if (($# != 1));
then
echo "0"
else
# Obtain day, month and year of certificate expiration
expiration_date=`echo | openssl s_client -servername $1 -connect $1:443 2>/dev/null | openssl x509 -noout -enddate | cut -d= -f2- | awk '{print $2"-"$1"-"$4}'`
# Get certificate expiration date in epoch format
cert_epoch=`date --date="$expiration_date" +%s`
# Get current date in epoch format
curr_epoch=`date +%s`
# Get the difference and convert to days
difference=`expr $(( (cert_epoch - $curr_epoch) / 86400))`
if [ "$difference" -le 0 ]; then
# Print 0 in case of invalid certificate
echo "0"
else
# Days untill expiration
echo "$difference"
fi
fi

View file

@ -0,0 +1,47 @@
#!/bin/bash
nombres=(
'nombre1'
'nombre2'
'...')
sufijo=".dominioquesea.es"
true > jaulas.local.inc
#creamos un fichero con todas las jaulas para luego incluirlo en el jail.local de fail2ban
for nombre in "${nombres[@]}"
do
echo "Creando la jaula $nombre"
{
echo "[$nombre]"
echo "enabled = true"
echo "filter = $nombre$sufijo"
echo "port = http,https"
echo "logpath = /var/log/nginx/$nombre""_access.log"
echo "banaction = firewallcmd-ipset"
echo "maxretry = 3000"
echo "bantime = 3600"
echo "findtime = 3600"
echo ""
echo "[$nombre-loop]"
echo "enabled = true"
echo "filter = $nombre$sufijo"
echo "port = http,https"
echo "logpath = /var/log/nginx/$nombre""_access.log"
echo "banaction = firewallcmd-ipset"
echo "maxretry = 5999"
echo "bantime = 86400"
echo "findtime = 7200"
echo ""
} >> jaulas.local.inc
done
#creamos todos los ficheros necesarios para los filtros que luego hay que mover a /etc/fail2ban/filter.d
for nombre in "${nombres[@]}"
do
echo "Creando el filtro $nombre$sufijo.conf"
{
echo "[Definition]"
echo 'failregex = ^<HOST> -.*"(GET)*("http://'$nombre$sufijo'/")*$'
} > $nombre$sufijo.conf
done

39
linux/fechas_linux.sh Normal file
View file

@ -0,0 +1,39 @@
#!/bin/bash
fecha_inicio=20131225
fecha_final=20140106
HOY=$(date)
echo "La fecha de hoy es $HOY"
HOY_FORMATO_1=$(date +%Y-%m-%d)
echo "Fecha hoy en formato ano-mes-dia : $HOY_FORMATO_1"
HOY_FORMATO_2=$(date +%d-%m-%Y)
echo "Fecha hoy en formato dia-mes-ano : $HOY_FORMATO_2"
DIFERENCIA=$(( ($(date --date "$fecha_final" +%s) - $(date --date "$fecha_inicio" +%s) )/(60*60*24) ))
echo "Diferencia $fecha_inicio y $fecha_final : $DIFERENCIA dias"
PRIMER_DIA_DEL_MES=$(date --date "-$(($(date +%d) -1)) days" +%Y%m%d)
echo "Fecha 1er. dia del mes : $PRIMER_DIA_DEL_MES"
ULTIMO_DIA_DEL_MES=$(date --date "-$(($(date +%d) -1)) days + 1 month -1 days" +%Y%m%d)
echo "Fecha ultimo dia del mes : $ULTIMO_DIA_DEL_MES"
DOMINGO=$(date --date "-$(date +%u) days" +%Y%m%d)
echo "Fecha dia Domingo Anterior : $DOMINGO"
LUNES=$(date --date "-$(( $(date +%u) + 6 )) days" +%Y%m%d)
echo "Fecha dia Lunes Anterior : $LUNES"
HACE_TRES_DIAS=$(date --date "-3 days" +%Y%m%d)
echo "Hace tres dias : $HACE_TRES_DIAS"
MAS_TRES_DIAS=$(date --date "+3 days" +%Y%m%d)
echo "En tres dias mas : $MAS_TRES_DIAS"
HACE_UN_MES=$(date --date "-1 month" +%Y%m%d)
echo "Hace un mes : $HACE_UN_MES"
exit

View file

@ -0,0 +1,30 @@
#!/bin/bash
HOY=$(date +%Y-%m-%d)
FECHAFIN="$HOY 06:26:00"
HORAACTUAL=$(date +"%T")
FECHAACTUAL="$HOY $HORAACTUAL"
echo "Hora actual: " $HORAACTUAL
echo "Hora fin: " $HORAFIN
echo "Fecha actual: " $FECHAACTUAL
echo "Fecha fin: " $FECHAFIN
#en segundos
DIF_SEGUNDOS=$(( ($(date --date "$FECHAFIN" +%s) - $(date --date "$FECHAACTUAL" +%s) ) ))
#en minutos
DIF_MINUTOS=$(( ($(date --date "$FECHAFIN" +%s) - $(date --date "$FECHAACTUAL" +%s) )/(60) ))
#en horas
DIF_HORAS=$(( ($(date --date "$FECHAFIN" +%s) - $(date --date "$FECHAACTUAL" +%s) )/(60*60) ))
#en dias
DIF_DIAS=$(( ($(date --date "$FECHAFIN" +%s) - $(date --date "$FECHAACTUAL" +%s) )/(60*60*24) ))
echo "Me tengo que esperar " $DIF_SEGUNDOS " segundos"
if [ $DIF_SEGUNDOS -gt 2 ]
then
sleep $DIF_SEGUNDOS
fi
echo "Ya son las " $(date +"%T")

17
linux/getswap.sh Normal file
View file

@ -0,0 +1,17 @@
#!/bin/bash
# Get current swap usage for all running processes
# Erik Ljungstrom 27/05/2011
SUM=0
OVERALL=0
for DIR in `find /proc/ -maxdepth 1 -type d | egrep "^/proc/[0-9]"` ; do
PID=`echo $DIR | cut -d / -f 3`
PROGNAME=`ps -p $PID -o comm --no-headers`
for SWAP in `grep Swap $DIR/smaps 2>/dev/null| awk '{ print $2 }'`
do
let SUM=$SUM+$SWAP
done
echo "PID=$PID - Swap used: $SUM - ($PROGNAME )"
let OVERALL=$OVERALL+$SUM
SUM=0
done
echo "Overall swap used: $OVERALL"

View file

@ -0,0 +1,606 @@
#!/bin/bash
# GPL ETD
LOG_PATH="/tmp/inventario_servicios"
LOG_PATH_CSV="$LOG_PATH/csv"
LOG_PATH_TMP="$LOG_PATH/tmp"
LOG="resultadoInventarioServicios.txt"
LOG_RESULTADOS="$LOG_PATH/$LOG"
LISTA_IPs="$LOG_PATH_TMP/listaIPs"
LISTA_IPs_ANSIBLE="$LOG_PATH_TMP/listaIPsAnsible"
LOG_PHP_CSV="$LOG_PATH_CSV/listadoServidoresPhp.csv"
LOG_NGINX_CSV="$LOG_PATH_CSV/listadoServidoresNginx.csv"
LOG_APACHE_CSV="$LOG_PATH_CSV/listadoServidoresApache.csv"
LOG_TOMCAT_CSV="$LOG_PATH_CSV/listadoServidoresTomcat.csv"
LOG_MARIADB_CSV="$LOG_PATH_CSV/listadoServidoresMariaDB.csv"
LOG_POSTGRESQL_CSV="$LOG_PATH_CSV/listadoServidoresPostgreSQL.csv"
LOG_WILDFLY_CSV="$LOG_PATH_CSV/listadoServidoresWildfly.csv"
LOG_DRUPAL_CSV="$LOG_PATH_CSV/listadoServidoresDrupal.csv"
LOG_WORDPRESS_CSV="$LOG_PATH_CSV/listadoServidoresWordpress.csv"
LOGS_MONTAJES_CSV="$LOG_PATH_CSV/listadoServidoresConMontajesCifsNfs.csv"
#LOG_FILE SE DEFINE EN LA FUNCION DE INICIO SIENDO LA UNION DE HOSTNAME E IP DE CADA SERVIDOR DENTRO DEL DIRECTORIO tmp
cd $LOG_PATH || mkdir -p $LOG_PATH 2>&1
mkdir -p $LOG_PATH_TMP 2>&1
mkdir -p $LOG_PATH_CSV 2>&1
mkdir -p $LOG_PATH/antiguos 2>&1
# vaciamos las carpetas tmp y csv de los logs existentes, haciendo antes un backup
NOW=$(date +%Y-%m-%d)
tar -zcvf $LOG_PATH/antiguos/$NOW-tmp.tgz $LOG_PATH_TMP
tar -zcvf $LOG_PATH/antiguos/$NOW-csv.tgz $LOG_PATH_CSV
rm $LOG_PATH_TMP/*.log
rm $LOG_PATH_CSV/*.csv
mv $LOG_RESULTADOS $LOG_PATH/antiguos/$LOG.$NOW
#inicializamos el fichero de log y los CSV
true > $LOG_RESULTADOS
echo "HOSTNAME#IP#Version#php-fpm#Estado#Alternatives#Configuracion#root_path#fastcgi" > $LOG_PHP_CSV
echo "HOSTNAME#IP#Version#Estado#Configuracion#Servicio#root_path" > $LOG_NGINX_CSV
echo "HOSTNAME#IP#Version#Carpeta" > $LOG_APACHE_CSV
echo "HOSTNAME#IP#Version#Carpeta#javaHome#javaVersion#enUso" > $LOG_TOMCAT_CSV
echo "HOSTNAME#IP#Version#Estado" > $LOG_MARIADB_CSV
echo "HOSTNAME#IP#Version#Estado" > $LOG_POSTGRESQL_CSV
echo "HOSTNAME#IP#Servicio#Estado#Version#Path#connectionUrl" > $LOG_WILDFLY_CSV
echo "HOSTNAME#IP#Configuracion#Server#serverRoot#Version_Drupal#Version_Drush" > $LOG_DRUPAL_CSV
echo "HOSTNAME#IP#path" > $LOG_WORDPRESS_CSV
echo "HOSTNAME#IP#Servidor de ficheros#Punto de montaje" > $LOGS_MONTAJES_CSV
echo "HOSTNAME#IP#Tipo#Export#Tamaño#Usado#Disponible#%Uso#Montado en" > $LOGS_MONTAJES_CSV
## LA FUNCION INICIO SE ENCUENTRA AL FINAL, DESPUES DE LAS FUNCIONES
##############################################################################
# FUNCIONES
##############################################################################
generaListaIPs() {
# generamos listado de ips en base a ansible
echo "Buscando IPs CentOS"
ansible centos -m ping > "$LISTA_IPs_ANSIBLE"
echo "Buscando IPs Ubuntu"
ansible ubuntu -m ping >> "$LISTA_IPs_ANSIBLE"
echo "Buscando IPs RedHat"
ansible redhat -m ping >> "$LISTA_IPs_ANSIBLE"
echo "Buscando IPs Oracle"
ansible oracle -m ping >> "$LISTA_IPs_ANSIBLE"
echo "Buscando IPs SuSe"
ansible suse -m ping >> "$LISTA_IPs_ANSIBLE"
# generamos el listado solo con las ips desechando el resto de información que da ansible
echo "Creamos el fichero con IPs"
sudo cat "$LISTA_IPs_ANSIBLE" | grep -oi "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" | sort | uniq > "$LISTA_IPs"
}
# Apache (apache2)
compruebaApache2() {
echo "=== APACHE ===" >> "$LOG_FILE"
apache=$(ssh globaluser@"$IP" "dpkg -l | grep apache2 | grep ii | sort | head -1 | awk '{ print \$2 }'")
if [ "$apache" = "apache2" ]; then
apache_version=$(ssh globaluser@"$IP" "/usr/sbin/apache2 -v | grep "\"Server version"\" | awk -F ":" '{ print \$2 }' | sed 's/\ //g'")
apache_carpeta=$(ssh globaluser@"$IP" "/usr/sbin/apache2 -V | grep HTTPD_ROOT | awk '{ print \$2 }' | awk -F "=" '{ print \$2 }' | sed 's/\"//g'")
{
echo " Apache APACHE2"
echo " Version: $apache_version"
echo " Carpeta: $apache_carpeta"
} >> "$LOG_FILE"
echo "$HOSTNAME#$IP#$apache_version#$apache_carpeta" >> "$LOG_APACHE_CSV"
fi
}
# Apache (httpd)
compruebaApache_httpd() {
echo "=== APACHE ===" >> "$LOG_FILE"
apache=$(ssh globaluser@"$IP" "rpm -qa | grep "^httpd-[0-9]" | sort | awk -F"-" '{ print \$1 }'")
if [ "$apache" = "httpd" ]; then
apache_version=$(ssh globaluser@"$IP" "/usr/sbin/httpd -v | grep "\"Server version"\" | awk -F ":" '{ print \$2 }' | sed 's/\ //g'")
apache_carpeta=$(ssh globaluser@"$IP" "/usr/sbin/httpd -V | grep HTTPD_ROOT | awk '{ print \$2 }' | awk -F "=" '{ print \$2 }' | sed 's/\"//g'")
{
echo " Apache HTTPD"
echo " Version: $apache_version"
echo " Carpeta: $apache_carpeta"
} >> "$LOG_FILE"
echo "$HOSTNAME#$IP#$apache_version#$apache_carpeta" >> "$LOG_APACHE_CSV"
fi
}
# Apache Tomcat
compruebaTomcat () {
echo "=== APACHE TOMCAT ===" >> "$LOG_FILE"
# primero buscamos instalaciones estándar y luego instalaciones independientes usando locate
tomcat=$(ssh globaluser@"$IP" "/sbin/tomcat version | head -1 | awk '{ print \$4 }' | awk -F '/' '{ print \$1 }'")
if [ "$tomcat" = "Tomcat" ]; then
tomcatVersion=$(ssh globaluser@"$IP" "/sbin/tomcat version | head -1")
{
echo " Tomcat Distro Release"
echo " Version: $tomcatVersion"
echo " Carpeta: /sbin/tomcat"
} >> "$LOG_FILE"
echo "$HOSTNAME#$IP#$tomcatVersion#'/sbin/tomcat'###" >> "$LOG_TOMCAT_CSV"
fi
tomcat_localizaciones=$(ssh globaluser@"$IP" "/usr/bin/locate version.sh | grep tomcat")
for tomcatVersionFile in $tomcat_localizaciones
do
tomcatVersion=$(ssh globaluser@"$IP" "$tomcatVersionFile | grep "\"Server version"\"")
carpetaTomcat=$(echo "$tomcatVersionFile" | awk -F "/" '{ print "/"$2"/"$3"/"$4 }')
javaHome=$(echo "$tomcatVersionFile" | awk -F "/" '{ print "/"$2"/"$3 }')
javaVersion=$(ssh globaluser@"$IP" "ls -l $javaHome/jdk | awk '{print \$NF}'")
versionTomcat=$(echo "$tomcatVersion" | awk -F ":" '{ print $2 }')
homeTomcat=$(echo "$javaHome" | awk -F "/" '{ print $3 }')
enUso=$(ssh globaluser@"$IP" "grep $homeTomcat /etc/tomcats")
if [ "$enUso" = "$homeTomcat" ]; then
enUso="Si"
else
enUso="No"
fi
{
echo " Tomcat Standalone Release"
echo " Version: $versionTomcat"
echo " Carpeta: $carpetaTomcat"
echo " Java: $javaVersion"
echo "Java home: $javaHome"
echo " En Uso: $enUso"
} >> "$LOG_FILE"
echo "$HOSTNAME#$IP#$versionTomcat#$carpetaTomcat#$javaHome#$javaVersion#$enUso" >> "$LOG_TOMCAT_CSV"
done
}
# NGINX
compruebaNginx() {
echo "=== NGINX ===" >> "$LOG_FILE"
existeNGINX=$(ssh globaluser@"$IP" "systemctl list-units | grep nginx")
if [[ "$existeNGINX" == *"nginx.service"* ]]; then
estadoServicioNginx=$(ssh globaluser@"$IP" "systemctl | grep -w nginx.service | awk '{ print \$2, \$3, \$4 }'")
configuracionesNginx=$(ssh globaluser@"$IP" "ls -la /etc/nginx/conf.d/ | grep -E '\.conf$' | awk '{ print \$9 }'")
confs=$(echo "$configuracionesNginx" | sed 's/ /, /g' | wc -l)
versionNGINX=$(ssh globaluser@"$IP" "/usr/sbin/nginx -v 2>&1 | awk -F ":" '{ print \$2 }' | sed 's/ //'")
{
echo " Version Nginx: $versionNGINX"
echo " Estado del servicio: $estadoServicioNginx"
echo " Configuraciones: $confs"
echo " Datos de las configuraciones encontradas:"
} >> "$LOG_FILE"
# Voy a mirar en todos los .conf de nginx el server name y la ruta de root
configsNginx=$(ssh globaluser@"$IP" "ls /etc/nginx/conf.d/*.conf")
for config in $configsNginx
do
server_name=$(ssh globaluser@"$IP" "grep 'server_name' $config | head -n 1 | awk '{print \$NF}' | sed -e 's/.$//'")
root_path=$(ssh globaluser@"$IP" "grep 'root' $config | grep -v '#root' | head -n 1 | awk '{print \$NF}' | sed -e 's/.$//'")
{
echo " Fichero de configuración: $config"
echo " Server Name: $server_name"
echo " Server Root: $root_path"
} >> "$LOG_FILE"
echo "$HOSTNAME#$IP#$versionNGINX#$estadoServicioNginx#$config#$server_name#$root_path" >> "$LOG_NGINX_CSV"
done
fi
}
# PHP
compruebaPHP() {
echo "=== PHP ===" >> "$LOG_FILE"
existePhp=$(ssh globaluser@"$IP" "systemctl list-units | grep php | grep .service")
if [[ "$existePhp" == *"-fpm.service"* ]]; then
phpfpm=$(ssh globaluser@"$IP" "systemctl list-units | grep php | grep .service | awk '{ print \$1 }'")
versionPhp=$(ssh globaluser@"$IP" "php -v | head -n1")
estadoPhp=$(ssh globaluser@"$IP" "systemctl list-units | grep php | grep .service | awk '{ print \$2, \$3, \$4 }'")
alternativesPhp=$(ssh globaluser@"$IP" "update-alternatives --get-selections | grep 'php ' | awk -F' ' '{ print \$1\" \"\$2\" \"\$3 }'")
{
echo " Version Php: $versionPhp"
echo " Estado $phpfpm: $estadoPhp"
echo " Alternatives: $alternativesPhp"
} >> "$LOG_FILE"
existeNGINX=$(ssh globaluser@"$IP" "systemctl list-units | grep nginx")
if [[ "$existeNGINX" == *"nginx.service"* ]]; then
configs=$(ssh globaluser@"$IP" "ls /etc/nginx/conf.d/*.conf")
echo " configuracion nginx : directorio root : fastcgi_pass" >> "$LOG_FILE"
for config in $configs
do
rootPath=$(ssh globaluser@"$IP" "grep 'root' $config | grep -v '#root' | head -n 1 | awk '{print \$NF}' | sed -e 's/.$//'")
fastcgi=$(ssh globaluser@"$IP" "grep 'fastcgi_pass' $config | grep -v \"#\"")
# con el awk quitamos los espacios en blanco del principio
fastcgiPass=$(echo "$fastcgi" | awk '{sub(/^[ \t]+/, ""); print }')
if [ "$fastcgiPass" != "" ]; then
echo " $config : $rootPath : $fastcgiPass " >> "$LOG_FILE"
echo "$HOSTNAME#$IP#$versionPhp#$phpfpm#$estadoPhp#$alternativesPhp#$config#$rootPath#$fastcgiPass" >> "$LOG_PHP_CSV"
fi
done
else
echo "$HOSTNAME#$IP#$versionPhp#$phpfpm#$estadoPhp#$alternativesPhp###" >> "$LOG_PHP_CSV"
fi
fi
}
# MariaDB o mySQL
compruebaMariaDb_mySQL() {
echo "=== MARIADB o MYSQL ===" >> "$LOG_FILE"
existeMariadb=$(ssh globaluser@"$IP" "systemctl list-units | grep mariadb")
existeMysql=$(ssh globaluser@"$IP" "systemctl list-units | grep mysqld")
if [[ "$existeMariadb" == *"mariadb.service"* ]] || [[ "$existeMysql" == *"mysqld.service"* ]]; then
tipoBBDD=$(ssh globaluser@"$IP" "mysql -V")
else
return
fi
if [[ "$tipoBBDD" == *"MariaDB"* ]]; then
estadoServicioBBDD=$(ssh globaluser@"$IP" "systemctl list-units | grep mariadb.service | awk '{ print \$2, \$3, \$4 }'")
else
estadoServicioBBDD=$(ssh globaluser@"$IP" "systemctl list-units | grep mysqld.service | awk '{ print \$2, \$3, \$4 }'")
fi
{
echo " MariaDB" >> "$LOG_FILE"
echo " Version: $tipoBBDD"
echo " Estado del servicio: $estadoServicioBBDD"
} >> "$LOG_FILE"
echo "$HOSTNAME#$IP#$tipoBBDD#$estadoServicioBBDD" >> "$LOG_MARIADB_CSV"
}
# PostgreSQL
compruebaPostgreSQL() {
echo "=== POSTGRESQL ===" >> "$LOG_FILE"
existePostgresql=$(ssh globaluser@"$IP" "systemctl list-units | grep postgresql")
if [[ "$existePostgresql" == *"postgresql.service"* ]]; then
versionPSQL=$(ssh globaluser@"$IP" "psql -V")
estadoServicioPSQL=$(ssh globaluser@"$IP" "systemctl | grep postgresql.service | awk '{ print \$2, \$3, \$4 }'")
{
echo " Version Postgresql: $versionPSQL"
echo " Estado del servicio: $estadoServicioPSQL"
} >> "$LOG_FILE"
echo "$HOSTNAME#$IP#$versionPSQL#$estadoServicioPSQL" >> "$LOG_POSTGRESQL_CSV"
fi
}
# Fail2ban
compruebaFail2ban() {
echo "=== FAIL2BAN ===" >> "$LOG_FILE"
existeFail2ban=$(ssh globaluser@"$IP" "systemctl list-units | grep fail2ban")
if [[ "$existeFail2ban" == *"fail2ban.service"* ]]; then
versionFail2ban=$(ssh globaluser@"$IP" "fail2ban-client --version")
estadoServicioFail2ban=$(ssh globaluser@"$IP" "systemctl | grep fail2ban.service | awk '{ print \$2, \$3, \$4 }'")
jaulasFail2ban=$(ssh globaluser@"$IP" "sudo fail2ban-client status | grep 'Jail list' | cut -d':' -f2-")
{
echo " Version Fail2ban: $versionFail2ban"
echo " Estado del servicio: $estadoServicioFail2ban"
echo " Jaulas configuradas: $jaulasFail2ban"
} >> "$LOG_FILE"
fi
}
# Wildfly
compruebaWildfly() {
echo "=== WILDFLY ===" >> "$LOG_FILE"
existeWildfly=$(ssh globaluser@"$IP" "systemctl list-units | grep wildfly")
if [[ "$existeWildfly" == *"wildfly"* ]]; then
echo " Wildfly" >> "$LOG_FILE"
cantidadServiciosWildfly=$(ssh globaluser@"$IP" "systemctl list-units | grep wildfly | wc -l")
serviciosWildfly=$(ssh globaluser@"$IP" "systemctl list-units | grep wildfly | awk -F '.' '{ print \$1 }'")
echo " Número de servicios Wildfly activos: $cantidadServiciosWildfly" >> "$LOG_FILE"
for servicio in $serviciosWildfly
do
estadoServicioWildfly=$(ssh globaluser@"$IP" "systemctl | grep $servicio.service | awk '{ print \$2, \$3, \$4 }'")
echo " Estado de $servicio: $estadoServicioWildfly" >> "$LOG_FILE"
versionWildfly=$(ssh globaluser@$IP "sudo grep "WFLYSRV0049" /opt/$servicio/standalone/log/server.* | awk '{ print \$10 \$11 \$12 \$13 \$14 \$15 }' | sort | tail -1")
echo " Version de $servicio: $versionWildfly" >> "$LOG_FILE"
carpetaWildfly=$(ssh globaluser@$IP "sudo /opt/$servicio/bin/standalone.sh --version | grep "JBOSS_HOME" | awk '{ print \$2 }'")
echo " Carpeta de $servicio: $carpetaWildfly" >> "$LOG_FILE"
connectionUrl=$(ssh globaluser@"$IP" "sudo grep '<connection-url>jdbc:oracle:thin:@' /opt/$servicio/standalone/configuration/standalone.xml | awk -F ':' '{ print \$5 }' | awk -F '/' '{print \$2}' | sed -e 's/.$//' | tr '\n' ','")
echo " Connections URL de $servicio: $connectionUrl" >> "$LOG_FILE"
echo "$HOSTNAME#$IP#$servicio#$estadoServicioWildfly#$versionWildfly#$carpetaWildfly#$connectionUrl" >> "$LOG_WILDFLY_CSV"
done
fi
}
# Drupal
compruebaDrupal() {
echo "=== DRUPAL / DRUSH ===" >> "$LOG_FILE"
# Lo primero es ver si existe drupal instalado, si no existe no devolvera nada y nos marcharemos
existeDrupal=$(ssh globaluser@"$IP" "drush status && echo valido || echo error")
if [[ "$existeDrupal" == *"error"* ]]; then
return
fi
echo " Drupal" >> "$LOG_FILE"
# Voy a mirar en todos los .conf de nginx la ruta root y ejecutar 'drush status' para ver si tiene drupal y sacar la info
confsNginx=$(ssh globaluser@"$IP" "ls /etc/nginx/conf.d/*.conf")
for conf in $confsNginx
do
serverName=$(ssh globaluser@"$IP" "grep 'server_name' $conf | head -n 1 | awk '{print \$NF}' | sed -e 's/.$//'")
serverRoot=$(ssh globaluser@"$IP" "grep 'root' $conf | head -n 1 | awk '{print \$NF}' | sed -e 's/.$//'")
infoDrupal=$(ssh globaluser@"$IP" "sudo su -c 'cd $serverRoot; drush status'")
versionDrupal=$(echo "$infoDrupal" | grep 'Drupal version' | awk -F ':' '{print $2}')
versionDrush=$(echo "$infoDrupal" | grep 'Drush version' | awk -F ':' '{print $2}')
{
echo " Configuración nginx: $conf"
echo " Server Name: $serverName"
echo " Server Root: $serverRoot"
echo " Version Drupal: $versionDrupal"
echo " Version Drush: $versionDrush"
} >> "$LOG_FILE"
echo "$HOSTNAME#$IP#$conf#$serverName#$serverRoot#$versionDrupal#$versionDrush" >> "$LOG_DRUPAL_CSV"
done
}
# Wordpress
compruebaWordpress() {
echo "=== WORDPRESS ===" >> "$LOG_FILE"
existeWordpress=$(ssh globaluser@"$IP" "sudo find /usr/share/nginx -maxdepth 6 -name wp-admin")
if [[ "$existeWordpress" == "" ]]; then
return
fi
echo " Wordpress" >> "$LOG_FILE"
pathWp=$(echo "$existeWordpress" | awk '{print $1}')
echo " Path: $pathWp" >> "$LOG_FILE"
for path in $pathWp
do
echo "$HOSTNAME#$IP#$path" >> "$LOG_WORDPRESS_CSV"
done
}
# Puntos de montaje CIFS / NFS
compruebaMontajesNfsCifs() {
echo "=== CIFS/NFS ===" >> "$LOG_FILE"
cifs_fs=$(ssh globaluser@"$IP" "sudo df -t cifs -h")
nfs_fs=$(ssh globaluser@"$IP" "sudo df -t nfs -h")
nfs4_fs=$(ssh globaluser@"$IP" "sudo df -t nfs4 -h")
cifs=$(echo "$cifs_fs" | tail -n +2 | awk -F " " '{ print $1"#"$2"#"$3"#"$4"#"$5"#"$6 }')
nfs=$(echo "$nfs_fs" | tail -n +2 | awk -F " " '{ print $1"#"$2"#"$3"#"$4"#"$5"#"$6 }')
nfs4=$(echo "$nfs4_fs" | tail -n +2 | awk -F " " '{ print $1"#"$2"#"$3"#"$4"#"$5"#"$6 }')
if [[ "$cifs" != "" || "$nfs" != "" || "$nfs4" != "" ]]; then
{
echo " cifs/nfs"
echo "$cifs_fs"
echo "$nfs_fs"
echo "$nfs4_fs"
} >> "$LOG_FILE"
fi
if [[ "$cifs" != "" ]]; then
for fs in $cifs
do
echo "$HOSTNAME $IP cif $fs" | awk '{ print $1"#"$2"#"$3"#"$4 }' >> "$LOGS_MONTAJES_CSV"
done
fi
if [[ "$nfs" != "" ]]; then
#nfsVersion=$(ssh globaluser@"$IP" "nfsstat -c | grep 'Client nfs' | awk -F ":" '{ print \$1 }' | awk '{ print \$3 }' | paste -s -d_") # el paste es por si hay varias versiones en varias lineas las concatene
for fs in $nfs
do
echo "$HOSTNAME $IP nfs_v3 $fs" | awk '{ print $1"#"$2"#"$3"#"$4 }' >> "$LOGS_MONTAJES_CSV"
done
fi
if [[ "$nfs4" != "" ]]; then
for fs in $nfs4
do
echo "$HOSTNAME $IP nfs_v4 $fs" | awk '{ print $1"#"$2"#"$3"#"$4 }' >> "$LOGS_MONTAJES_CSV"
done
fi
}
compruebaServicios() {
# Apache se comprueba de forma independiente ya que en unos es apache2 y en otros es httpd
if [[ "$queEscaneo" = "2" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Apache Tomcat..."
compruebaTomcat
fi
if [[ "$queEscaneo" = "3" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Nginx..."
compruebaNginx
fi
if [[ "$queEscaneo" = "4" || "$queEscaneo" = "0" ]]; then
echo "Comprobando PHP..."
compruebaPHP
fi
if [[ "$queEscaneo" = "5" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Mariadb y/o Mysql..."
compruebaMariaDb_mySQL
fi
if [[ "$queEscaneo" = "6" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Postgresql..."
compruebaPostgreSQL
fi
if [[ "$queEscaneo" = "7" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Wildfly..."
compruebaWildfly
fi
if [[ "$queEscaneo" = "8" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Drupal / Drush..."
compruebaDrupal
fi
if [[ "$queEscaneo" = "9" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Wordpress..."
compruebaWordpress
fi
if [[ "$queEscaneo" = "A" || "$queEscaneo" = "a" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Fail2ban..."
compruebaFail2ban
fi
if [[ "$queEscaneo" = "B" || "$queEscaneo" = "b" || "$queEscaneo" = "0" ]]; then
echo "Comprobando puntos de montaje cifs/nfs..."
compruebaMontajesNfsCifs
fi
}
infoUbuntu() {
if [[ "$queEscaneo" = "1" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Apache2..."
compruebaApache2
fi
compruebaServicios
}
infoCentOS() {
if [[ "$queEscaneo" = "1" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Apache httpd..."
compruebaApache_httpd
fi
compruebaServicios
}
infoRedHat() {
if [[ "$queEscaneo" = "1" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Apache httpd..."
compruebaApache_httpd
fi
compruebaServicios
}
infoOracle() {
if [[ "$queEscaneo" = "1" || "$queEscaneo" = "0" ]]; then
echo "Comprobando Apache httpd..."
compruebaApache_httpd
fi
compruebaServicios
}
infoSuse() {
true
}
compruebaSSH() {
retorno_ssh=$(ssh -o BatchMode=yes -o ConnectTimeout=5 globaluser@"$IP" "cat /etc/lsb-release 2>&1;cat /etc/oracle-release 2>&1;cat /etc/centos-release 2>&1;cat /etc/redhat-release 2>&1;cat /etc/issue 2>&1")
return $?
}
sacaVersiones() {
# Ahora sacamos las versiones de los sistemas operativos y dependiendo de que sea sacamos el resto de información
case $retorno_ssh in
*"Ubuntu "*)
RELEASE=$(echo "$retorno_ssh" | grep -oi "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" | uniq)
# el if -z comprueba si la variable está vacia
if [ -z "$RELEASE" ]; then
RELEASE=$(echo "$retorno_ssh" | grep -oi "[0-9]\{1,3\}\.[0-9]\{1,3\}" | uniq)
fi
SERVER="Ubuntu $RELEASE"
echo "Sistema Operativo: $SERVER"
echo "SISTEMA OPERATIVO: $SERVER" >> "$LOG_FILE"
infoUbuntu
;;
*"CentOS "*)
RELEASE=$(echo "$retorno_ssh" | grep -oi "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" | uniq)
if [ -z "$RELEASE" ]; then
RELEASE=$(echo "$retorno_ssh" | grep -oi "[0-9]\{1,3\}\.[0-9]\{1,3\}" | uniq)
fi
SERVER="CentOS $RELEASE"
echo "Sistema Operativo: $SERVER"
echo "SISTEMA OPERATIVO: $SERVER" >> "$LOG_FILE"
infoCentOS
;;
*"Red Hat "*)
RELEASE=$(echo "$retorno_ssh" | grep -oi "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" | uniq)
if [ -z "$RELEASE" ]; then
RELEASE=$(echo "$retorno_ssh" | grep -oi "[0-9]\{1,3\}\.[0-9]\{1,3\}" | uniq)
fi
SERVER="Red Hat $RELEASE"
echo "Sistema Operativo: $SERVER"
echo "SISTEMA OPERATIVO: $SERVER" >> "$LOG_FILE"
infoRedHat
;;
*"Oracle "*)
SERVER="Oracle"
echo "Sistema Operativo: $SERVER"
echo "SISTEMA OPERATIVO: $SERVER" >> "$LOG_FILE"
infoOracle
;;
*"SUSE "*)
RELEASE=$(ssh globaluser@"$IP" "cat /etc/SuSE-release | grep SUSE")
SERVER="Suse $RELEASE"
echo "Sistema Operativo: $SERVER"
echo "SISTEMA OPERATIVO: $SERVER" >> "$LOG_FILE"
infoSuse
;;
*)
SERVER="DESCONOCIDO"
echo "Sistema Operativo: $SERVER"
echo "SISTEMA OPERATIVO: $SERVER" >> "$LOG_FILE"
;;
esac
}
inicio() {
# Iniciamos el recorrido por los servers en búsqueda de los diferentes servicios
for IP in $(cat "$LISTA_IPs")
do
#HOSTNAME=$(dig -x "$IP" | grep -a1 "ANSWER SECTION:" | grep "PTR" | awk '{print $NF}')
HOSTNAME=$(ssh "$IP" "hostname -f")
echo -e "\nComprobando conexión SSH con $HOSTNAME ($IP)"
if compruebaSSH
then
LOG_FILE="$LOG_PATH_TMP/$HOSTNAME-$IP.log"
{
echo "************************************"
echo " Conexión establecida..."
echo " Servidor: $HOSTNAME ($IP)"
echo "************************************"
} > "$LOG_FILE"
sacaVersiones
cat "$LOG_FILE" >> "$LOG_RESULTADOS"
else
echo "Conexión ERRONEA."
echo "NO hay conexión con $HOSTNAME ($IP)" >> $LOG_PATH_TMP"/conexion_ssh_fallida.err"
fi
done
}
####################################################################################################
# MODULO MAIN
####################################################################################################
clear
echo ""
echo "Inventario de servicios"
echo ""
if [[ $1 = "ALL" || $1 = "TODOS" || $1 = "all" || $1 = "todos" || $1 = "0" ]]; then
queEscaneo="0"
generaListaIPs
inicio
else
echo "¿Deseas generar la lista de IPs de nuevo? (SI/NO)"
read -r respuesta
if [[ "$respuesta" = "SI" || "$respuesta" = "si" || "$respuesta" = "Si" || "$respuesta" = "S" || "$respuesta" = "s" ]]; then
generaListaIPs
fi
echo ""
echo "Selecciona un servicio específico o todos"
echo "-------------------------------------------"
echo "1) Apache"
echo "2) Apache Tomcat"
echo "3) Nginx"
echo "4) Php"
echo "5) mariaDB/ mySQL"
echo "6) postgreSQL"
echo "7) Wildfly"
echo "8) Drupal"
echo "9) Wordpress"
echo "A) Fail2ban"
echo "B) Puntos de montaje CIFS/NFS"
echo ""
echo "0) TODOS LOS SERVICIOS"
echo "X) SALIR - EXIT"
echo ""
echo "¿Que opción quieres?"
read -r queEscaneo
case ${queEscaneo} in
1|2|3|4|5|6|7|8|9|0|A|a|B|b)
inicio
;;
X|x)
exit
;;
*)
echo ""
echo "OPCION INVALIDA, VUELVE A INTENTARLO"
echo""
;;
esac
fi

4
linux/libera_ram_swap.sh Normal file
View file

@ -0,0 +1,4 @@
#!/bin/bash
sync; echo 3 > /proc/sys/vm/drop_caches
sleep 5
swapoff -a && swapon -a

39
linux/mariadb_backup.sh Normal file
View file

@ -0,0 +1,39 @@
#!/bin/bash
#Si la web es drupal ir al directorio de la web y vaciar cache:
#echo "Borramos cache antes del backup"
#cd /usr/share/nginx/[WEB]/project/docroot
#drush cr
DB_USER="user"
DB_PASSWD="password"
DB_DATABASE="database"
BACKUP_PATH="/var/data/mariadb_backup"
BACKUP_FILE=$DB_DATABASE"-"$(date +%Y-%m-%d-%H-%M)".sql"
LOGFILE=$BACKUP_PATH"/"$DB_DATABASE"_backup.log"
SERVIDOR=$(hostname -f)
DIASMANTENER=15
now=$(date +"%d-%m-%Y")
true > $LOGFILE
echo "=================================================" >> $LOGFILE
echo "Servidor: $SERVIDOR" >> $LOGFILE
echo "BACKUP BBDD $DB_DATABASE - Realizado el $now" >> $LOGFILE
echo "BORRAMOS LOS BACKUPS QUE TIENEN MAS DE $DIASMANTENER DIAS DE ANTIGUEDAD" >> $LOGFILE
find $BACKUP_PATH/ -type f -name $DB_DATABASE"*" -mtime +$DIASMANTENER -delete
echo "CREANDO COPIA DE SEGURIDAD CON mysqldump" >> $LOGFILE
mysqldump -u $DB_USER -p$DB_PASSWD --single-transaction --quick $DB_DATABASE > $BACKUP_PATH/$BACKUP_FILE 2>>$LOGFILE
if [ "$?" -eq 0 ]
then
echo "Volcado de la base de datos $DB_DATABASE correcto. Comprimiendo con gzip." >> $LOGFILE
gzip -9 $BACKUP_PATH/$BACKUP_FILE 2>>$LOGFILE
ls -lah $BACKUP_PATH/$BACKUP_FILE".gz" >> $LOGFILE
echo "BACKUP CORRECTO" >> $LOGFILE
else
echo "Ha habido un error en el volcado, mirar el mensaje devuelto por mysqldump justo aqui encima." >> $LOGFILE
echo "BACKUP ERRONEO" >> $LOGFILE
fi
echo "=================================================" >> $LOGFILE

View file

@ -0,0 +1,69 @@
#!/bin/bash
# PRUEBA DE MENU UTILIZANDO ARRAYS, CASE, IF y FOR
colores[0]="verde"
colores[1]="rojo"
colores[2]="azul"
colores[3]="blanco"
colores[4]="cyan"
Amarillo="\e[1;33m"
Blanco="\e[1;97m"
Rojo="\e[1;31m"
Verde="\e[1;32m"
Azul="\e[1;34m"
Cyan="\e[1;36m"
while [ true ]
do
echo -e $Amarillo
echo "**************************************************"
echo "** **"
echo "** Los colores disponibles son: **"
echo "** blanco,verde,azul,rojo y cyan **"
echo "** **"
echo "**************************************************"
echo "¿Que color quieres? (fin para acabar)"
read -r opcion
case ${opcion} in
verde)
echo -e $Verde
echo "has elegido verde"
;;
blanco)
echo -e $Blanco
echo "has elegido blanco"
;;
cyan)
echo -e $Cyan
echo "has elegido cyan"
;;
rojo)
echo -e $Rojo
echo "has elegido rojo"
;;
azul)
echo -e $Azul
echo "has elegido azul"
;;
fin)
exit 0
;;
*)
if [[ ${colores[*]} != ${opcion} ]]
then
echo -e "\e[1;35m"
echo "Opcion elegida: "$opcion
echo "Ese color no lo conozco, los colores que conozco son:"
for color in ${colores[@]};
do
echo " "$color
done
else
echo -e "\e[1;37m;45m"
read -p "RAREZA EN EL IF, pulsa una tecla y elige otra opcion "
fi
;;
esac
done

View file

@ -0,0 +1,24 @@
#!/bin/bash
if [ $# -ne 2 ]
then
echo "===="; echo "Uso: $0 [web] [conexiones]"; echo "====";
exit 0
fi
if [ $2 -gt 0 ]
then
times=$2
else
times=1
fi
echo "Se van a realizar $times conexiones a la web $1"
read -p "Pulse [ENTER] para comenzar."
while [ $times -gt 0 ]
do
echo "Conexiones restantes $times"
wget $1 --delete-after &
times=$(($times-1))
rm wget-log*
done
rm wget-log*
echo "Done"

View file

@ -0,0 +1,39 @@
#!/bin/bash
DATABASE="database"
BACKUP_PATH="/var/data/postgres_backup"
BACKUP_FILE=$DATABASE"-"$(date +%Y-%m-%d-%H-%M)".sql"
LOGFILE=$BACKUP_PATH"/"$DATABASE"_backup.log"
SERVIDOR=$(hostname -f)
DIASMANTENER=15
now=$(date +"%d-%m-%Y")
true > $LOGFILE
# Nos movemos a este directorio para que el pg_dump no de error de no acceso a /root/scripts (si usamos este directorio para ejecutar el script)
cd $BACKUP_PATH
echo "=================================================" >> $LOGFILE
echo "Servidor: $SERVIDOR" >> $LOGFILE
echo "BACKUP BBDD $DATABASE - Realizado el $now" >> $LOGFILE
echo "BORRAMOS LOS BACKUPS QUE TIENEN MAS DE $DIASMANTENER DIAS DE ANTIGUEDAD" >> $LOGFILE
find $BACKUP_PATH/ -type f -name $DATABASE"*" -mtime +$DIASMANTENER -delete
echo "CREANDO COPIA DE SEGURIDAD CON postgres" >> $LOGFILE
sudo -u postgres /usr/bin/pg_dump $DATABASE > $BACKUP_PATH/$BACKUP_FILE 2>>$LOGFILE
if [ "$?" -eq 0 ]
then
echo "Volcado de la base de datos $DATABASE correcto. Comprimiendo con gzip." >> $LOGFILE
gzip -9 $BACKUP_PATH/$BACKUP_FILE 2>>$LOGFILE
chown postgres:postgres $BACKUP_PATH/$BACKUP_FILE".gz"
chmod 600 $BACKUP_PATH/$BACKUP_FILE".gz"
ls -lah $BACKUP_PATH/$BACKUP_FILE".gz" >> $LOGFILE
echo "BACKUP CORRECTO" >> $LOGFILE
else
echo "Ha habido un error en el volcado, mirar el mensaje devuelto por postgres justo aqui encima." >> $LOGFILE
echo "BACKUP ERRONEO" >> $LOGFILE
fi
echo "=================================================" >> $LOGFILE

View file

@ -0,0 +1,42 @@
#!/bin/bash
BACKUP_PATH="/var/data/postgresql_backup/"
BACKUP_FECHA=$(date +%d-%m-%Y_%H-%M)
DIASMANTENER="30"
SERVIDOR=$(hostname -f)
# Nos movemos a este directorio para que el pg_dump no de error de no acceso a /root/scripts (si usamos este directorio para ejecutar el script)
cd $BACKUP_PATH
#Creamos lista de bases de datos para realizar backup
LISTA_DATABASES=$(sudo -u postgres /usr/bin/psql -l -t | cut -d'|' -f1 | sed -e 's/ //g' -e '/^$/d')
#Comenzamos tarea de backup
for DATABASE in $LISTA_DATABASES; do
if [ "$DATABASE" != "template0" ] && [ "$DATABASE" != "template1" ]; then
LOGFILE=$BACKUP_PATH$DATABASE"_backup.log"
BACKUP_FILE=$BACKUP_PATH$DATABASE"_"$BACKUP_FECHA".sql"
true > $LOGFILE
echo "=================================================" >> $LOGFILE
echo $SERVIDOR >> $LOGFILE
echo "BACKUP BBDD $DATABASE - Realizado el $now" >> $LOGFILE
sudo -u postgres /usr/bin/pg_dump -Fc $DATABASE > $BACKUP_FILE 2>>$LOGFILE
if [ "$?" -eq 0 ]
then
echo "Volcado de la base de datos $DATABASE correcto. Comprimiendo con gzip." >> $LOGFILE
chown postgres:postgres $BACKUP_FILE
chmod 600 $BACKUP_FILE
gzip -9 $BACKUP_FILE 2>>$LOGFILE
echo "----------------------" >> $LOGFILE
echo "BACKUP CORRECTO" >> $LOGFILE
else
echo "Ha habido un error en el volcado, mirar el mensaje devuelto por postgres justo aqui encima." >> $LOGFILE
echo "----------------------" >> $LOGFILE
echo "BACKUP ERRONEO" >> $LOGFILE
fi
fi
done
#Realizamos tareas de limpieza de todos los ficheros existentes en el directorio de backup
find $BACKUP_PATH -type f -prune -mtime +$DIASMANTENER -exec rm -f {} \;

View file

@ -0,0 +1,34 @@
#!/bin/bash
#Tarea de Backup Bases de datos POSTGRESQL de GITLAB-CE
backup_dir="/var/data/backup/"
#Añadimos la fecha de backup al nuevo archivo
backup_fecha=$(date +%d-%m-%Y_%H:%M)
echo "Fecha de backup: $backup_fecha"
#Número de días que vamos a mantener nuestros backups
numero_dias="30"
#Creamos lista de bases de datos para realizar backup
bases_de_datos=$(sudo su - gitlab-psql -c "/opt/gitlab/embedded/bin/psql -l -t -h /var/opt/gitlab/postgresql -p 5432 | cut -d'|' -f1 | sed -e 's/ //g' -e '/^$/d'")
echo "Bases de datos encontradas:"
for i in $bases_de_datos; do
if [ "$i" != "template0" ] && [ "$i" != "template1" ]; then
echo "$i"
fi
done
#Comenzamos tarea de backup
#El nombre del fichero de backup dera: nombre de la base de datos + fecha + estensión .gz
for i in $bases_de_datos; do
if [ "$i" != "template0" ] && [ "$i" != "template1" ]; then
volcado="$backup_dir$i""_$backup_fecha"".psql.gz"
echo "Volcamos $i a $volcado"
sudo su - gitlab-psql -c "/opt/gitlab/embedded/bin/pg_dump -Fc $i -h /var/opt/gitlab/postgresql -p 5432 | gzip > $volcado"
fi
done
echo "Backups finalizados, limpiamos los backups más antiguos de $numero_dias días"
#Realizamos tareas de limpieza
sudo find $backup_dir -type f -prune -mtime +$numero_dias -exec rm -f {} \;

120
linux/pwin2lin.pl Normal file
View file

@ -0,0 +1,120 @@
#!/usr/bin/perl -w
# Dan Witt
# 5/28/2010
# Convert Windows PuTTY sessions to Linux
#How to use pwin2lin.pl
sub help {
print<<HELP
Export the PuTTY registry settings from Windows:
Start->Run->regedit
HKEY_CURRENT_USER\\Software\\SimonTatham\\
Right click PuTTY and choose 'Export'. Save the registry file to your Linux machine and run this script from a shell (chmod 755 first):
./pwin2lin.pl
Examples:
Running the script alone:
foo\@bar:~\$ ./pwin2lin.pl
Specify files from the command line:
foo\@bar:~\$ ./pwin2lin.pl myPuttySessions.reg /home/foo/.putty
HELP
}
# Includes
use Encode;
use File::Path;
use strict;
# Globals
my $winRegFile = "";
my $puttyPath = "";
if($#ARGV + 1) { # If any command line arguments are specified try to parse
if($ARGV[0] eq "--help") {
&help();
exit;
} elsif($ARGV[0] && $ARGV[1]) {
$winRegFile = $ARGV[0];
chomp $winRegFile;
$puttyPath = $ARGV[1];
chomp $puttyPath;
} else {
print "Usage:\n ./pwin2lin.pl [Windows Reg File] [Path to save PuTTY sessions]\n ./pwin2lin.pl --help\n";
exit;
}
} else { # Ask them where the registry file is and where they'd like to store the converted sessions.
print "Specify the path and file to convert:\n";
$winRegFile = <STDIN>;
chomp $winRegFile;
print "Specify the path to store the converted sessions:\n";
$puttyPath = <STDIN>;
chomp $puttyPath;
$puttyPath = "./" if !$puttyPath;
}
# Open the file and convert it from UTF-16LE
open(FILE, "<:encoding(UTF-16LE):crlf", $winRegFile) or die $!;
my @lines = <FILE>;
close FILE;
mkpath "$puttyPath/sessions", 0740 unless -d "$puttyPath/sessions";
my $linesLen = scalar @lines;
# Parse the registry file, try to guess some settings
my $i = 0;
while($i < $linesLen) {
chomp $lines[$i];
if($lines[$i] =~
m/^\[HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions\\(.+)\]/)
{
my $hostname = $1;
$i++;
next if $hostname =~ m/^Default.+Settings$/; # Use Linux Defaults
#print "$hostname\n";
open HOST, ">$puttyPath/sessions/$hostname" or die $!; # Write out the session
while(1) {
chomp $lines[$i];
last if $lines[$i] eq "";
$lines[$i] =~ s/\"//g;
if($lines[$i] =~ m/dword:(.+)/) {
my $dec = $1;
if($dec eq "ffffffff") {
$dec = -1;
} else {
$dec = hex($dec);
}
$lines[$i] =~ s/dword:.+/$dec/g;
}
$lines[$i] =~ s/^Font\=.+/FontName=server:fixed/g;
$lines[$i] =~ s/^NoRemoteQTitle\=(.+)/RemoteQTitleAction\=$1/g;
$lines[$i] =~ s/^SerialLine\=.+/SerialLine\=\/dev\/ttyS0/g;
$lines[$i] =~ s/^FontVTMode\=.+/FontVTMode\=4/g;
#print "$lines[$i]\n";
print HOST "$lines[$i]\n";
$i++;
}
close HOST;
} elsif($lines[$i] =~
m/\[HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\SshHostKeys\]/) {
$i++;
open SSH, ">$puttyPath/sshhostkeys" or die $!;
while($i < $linesLen) {
chomp($lines[$i]);
$lines[$i] =~ s/\"//g;
print SSH "$lines[$i]\n";
$i++;
}
close SSH;
}
$i++;
}

View file

@ -0,0 +1,284 @@
#!/bin/bash
# Este Script tiene 6 secciones o módulos de respaldo de configuraciones, data o valores de que son los siguientes:
# --VARIABLES Y PARÁMETROS BÁSICOS: Aquí se declaran las variables con los valores de ubicación, tiempo, datos del
# equipo y carpetas de trabajo necesarios para ejecutar las tareas de respaldos.
# --CONFIGURACIÓN BÁSICA DE EQUIPOS: Aquí se establecen los archivos y carpetas del Sistema Operativo que deben ser
# respaldadas. Habilite/Deshabilite, Incluya/Quite lo que necesite respaldar según el tipo de Usuario/Equipo usado.
# --CONFIGURACIÓN AVANZADA DE EQUIPOS: Aquí se establecen las Bases de Datos y el Tipo de Respaldo que se aplicará sobre
# cada una de ellas.
# --DATA ESENCIAL DE LOS USUARIOS: Aquí se programa el respaldo total o selectivo del Home del Usuario/Equipo.
# --VALORES Y PARÁMETROS DEL EQUIPO: Aquí se almacenan todos los valores o parámetros de Hardware y Software del Equipo
# proveídos por el comando “lshw” y los programados individualmente mediante comandos de Bash vía Shell Scripting.
# --MANTENIMIENTO DE LOS RESPALDO DEL EQUIPO: Aquí se le otorga a los respaldos creados los permisos o valores de
# propietarios requeridos más la cantidad de archivos del mismo que deberán almacenarse para el buen funcionamiento
# del Script.
# --COPIADO REMOTO DE LOS RESPALDO DEL EQUIPO: Aquí se le indica al Script ¿Cómo? y hacia ¿Donde? se respaldaran los
# archivos de respaldos.
# --NOTIFICACIÓN REMOTA DE LOS RESPALDO DEL EQUIPO: Aquí se le programa al Script que envíe un mensaje de correo a un
# Destinatario X para notificar la realización del Respaldo.
################################################################################
# INICIO DEL MÓDULO DE INICIALIZACIÓN DE VARIABLES Y PARÁMETROS BÁSICOS
################################################################################
DIR_INI=$(echo $PWD)
FEC_INI=$(date +"%d-%b-%y")
FEC_RESP=$(date "+%d-%m-%y_%H-%M-%S")
NOM_HOST=$(cat /etc/hostname)
IP_ETH0_HOST=$(ifconfig eth0 | grep inet | grep -v inet6 | cut -d ":" -f 2 | cut -d " " -f 1)
NAME_ROOT=root
HOME_ROOT=/root
USER1000_HOST=$(cat /etc/passwd | grep 1000 | cut -d: -f1)
DIR_RESP_CA=/opt/respaldo/$NOM_HOST-$IP_ETH0_HOST/$FEC_INI/conf_avanzada
if [ ! -d $DIR_RESP_CA ]; then mkdir -p $DIR_RESP_CA; fi ; chmod -R 777 $DIR_RESP_CA/ ; chown -R $USER1000_HOST. $DIR_RESP_CA/
DIR_RESP_CB=/opt/respaldo/$NOM_HOST-$IP_ETH0_HOST/$FEC_INI/conf_basica
if [ ! -d $DIR_RESP_CB ]; then mkdir -p $DIR_RESP_CB; fi ; chmod -R 777 $DIR_RESP_CB/ ; chown -R $USER1000_HOST. $DIR_RESP_CB/
DIR_RESP_DU=/opt/respaldo/$NOM_HOST-$IP_ETH0_HOST/$FEC_INI/data_usuarios
if [ ! -d $DIR_RESP_DU ]; then mkdir -p $DIR_RESP_DU; fi ; chmod -R 777 $DIR_RESP_DU/ ; chown -R $USER1000_HOST. $DIR_RESP_DU/
DIR_RESP_VP=/opt/respaldo/$NOM_HOST-$IP_ETH0_HOST/$FEC_INI/valores_parametros
if [ ! -d $DIR_RESP_VP ]; then mkdir -p $DIR_RESP_VP; fi ; chmod -R 777 $DIR_RESP_VP/ ; chown -R $USER1000_HOST. $DIR_RESP_VP/
# Parámetros de Variables de Inicialización del Script
################################################################################
# FINAL DEL MÓDULO DE INICIALIZACIÓN DE VARIABLES Y PARÁMETROS BÁSICOS PARA EL RESPALDO
################################################################################
################################################################################
# INICIO DEL MÓDULO DE RESPALDO DE CONFIGURACIÓN BÁSICA DE EQUIPOS
################################################################################
cd $DIR_RESP_CB
# RESPALDO DE ARCHIVOS IMPORTANTES
cp /boot/grub/grub.cfg ./grub.cfg.bck-$FEC_RESP
cp /boot/config-$(uname -r) ./config-$(uname -r).bck-$FEC_RESP
cp /etc/bash.bashrc ./bash.bashrc.bck-$FEC_RESP
cp /etc/crontab ./crontab.bck-$FEC_RESP
cp /etc/debian_version ./crontab.bck-$FEC_RESP
cp /etc/environment ./environment.bck-$FEC_RESP
cp /etc/fstab ./fstab.bck-$FEC_RESP
cp /etc/group ./group.bck-$FEC_RESP
cp /etc/hostname ./hostname.bck-$FEC_RESP
cp /etc/hosts ./hosts.bck-$FEC_RESP
cp /etc/hosts.allow ./hosts.allow.bck-$FEC_RESP
cp /etc/hosts.deny ./hosts.deny.bck-$FEC_RESP
cp /etc/issue ./issue.bck-$FEC_RESP
cp /etc/issue.net ./issue.net.bck-$FEC_RESP
cp /etc/logrotate.conf ./logrotate.conf.bck-$FEC_RESP
cp /etc/motd ./motd.bck-$FEC_RESP
cp /etc/ntp.conf ./ntp.conf.bck-$FEC_RESP
cp /etc/os-release ./os-release.bck-$FEC_RESP
cp /etc/passwd ./passwd.bck-$FEC_RESP
cp /etc/profile ./profile.bck-$FEC_RESP
cp /etc/rc.local ./rc.local.bck-$FEC_RESP
cp /etc/resolv.conf ./resolv.conf.bck-$FEC_RESP
cp /etc/rsyslog.conf ./rsyslog.conf.bck-$FEC_RESP
cp /etc/services ./services.bck-$FEC_RESP
cp /etc/shadow ./shadow.bck-$FEC_RESP
cp /etc/shell ./shell.bck-$FEC_RESP
cp /etc/sudoers ./sudoers.bck-$FEC_RESP
cp /etc/sysctl.conf ./sysctl.conf.bck-$FEC_RESP
cp /etc/timezone ./timezone.bck-$FEC_RESP
cp /etc/apt/sources.list ./etc-apt-sources.list.bck-$FEC_RESP
cp /etc/default/prelink ./etc-default-prelink.bck-$FEC_RESP
cp /etc/network/interfaces ./etc-network-interfaces.bck-$FEC_RESP
cp /etc/NetworkManager/NetworkManager.conf ./NetworkManager.conf.bck-$FEC_RESP
cp /etc/rsyslog.d/bash.conf ./etc-rsyslog.d-bash.conf.bck-$FEC_RESP
cp /etc/security/limits.conf ./security-limits.conf.bck-$FEC_RESP
cp /etc/ssh/sshd_config ./ssh-sshd_config.bck-$FEC_RESP
cp /var/log/auth.log ./var-log-auth.log.bck-$FEC_RESP
cp /var/log/commands.log ./var-log-commands.log.bck-$FEC_RESP
cp /var/log/daemon.log ./var-log-daemon.log.bck-$FEC_RESP
cp /var/log/debug ./var-log-debug.bck-$FEC_RESP
cp /var/log/dmesg ./var-log-dmesg.bck-$FEC_RESP
cp /var/log/faillog ./var-log-faillog.bck-$FEC_RESP
cp /var/log/kern.log ./var-log-kern.log.bck-$FEC_RESP
cp /var/log/lastlog ./var-log-lastlog.bck-$FEC_RESP
cp /var/log/messages ./var-log-messages.bck-$FEC_RESP
cp /var/log/syslog ./var-log-syslog.bck-$FEC_RESP
cp /var/log/user.log ./var-log-user.log.bck-$FEC_RESP
# Incluya cualquier otro archivo importante que desee respaldar
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#
# RESPALDO DE CARPETAS IMPORTANTES
tar cvpzf dir_apache2-bck-$FEC_RESP.tar.gz /etc/apache2
tar cvpzf dir_mysql-bck-$FEC_RESP.tar.gz /etc/mysql
tar cvpzf dir_perl-bck-$FEC_RESP.tar.gz /etc/perl
tar cvpzf dir_php5-bck-$FEC_RESP.tar.gz /etc/php5
tar cvpzf dir_phppgadmin-bck-$FEC_RESP.tar.gz /etc/phppgadmin
tar cvpzf dir_postgresql-bck-$FEC_RESP.tar.gz /etc/postgresql
tar cvpzf dir_python-bck-$FEC_RESP.tar.gz /etc/python
tar cvpzf dir_python2.7-bck-$FEC_RESP.tar.gz /etc/python2.7
tar cvpzf dir_squid3-bck-$FEC_RESP.tar.gz /etc/squid3
tar cvpzf dir_squidguard-bck-$FEC_RESP.tar.gz /etc/squidguard
tar cvpzf dir_ssh-bck-$FEC_RESP.tar.gz /etc/ssh
tar cvpzf dir_opt-$FEC_RESP.tar.gz /opt/$tu_carpeta
tar cvpzf dir_$NAME_ROOT-$FEC_RESP.tar.gz $HOME_ROOT
tar cvpzf dir_var_lib_squidguard_db-$FEC_RESP.tar.gz /var/lib/squidguard/db
tar cvpzf dir_var_log-$FEC_RESP.tar.gz /var/log
tar cvpzf dir_var_www-$FEC_RESP.tar.gz /var/www
chmod -R 777 $DIR_RESP_CB/ ; chown -R $USER1000_HOST. $DIR_RESP_CB/
# Incluya cualquier otro archivo importante que desee respaldar
################################################################################
# FINAL DEL MÓDULO DE RESPALDO DE CONFIGURACIÓN BÁSICA DE EQUIPOS
################################################################################
################################################################################
# INICIO DEL MÓDULO DE RESPALDO DE CONFIGURACIÓN AVANZADA DE EQUIPOS
################################################################################
cd $DIR_RESP_CA
# RESPALDO DE BD DE POSTGRESQL
export PGUSER="postgres"
export PGPASSWORD="123456"
BD1_PGSQL=mi_bd_psql
pg_dump -i -h localhost -p 5432 -s -f "$DIR_RESP_CA/$BD1_PGSQL-$FEC_RESP.sql" $BD1_PGSQL
# PGUSER=postgres PGPASSWORD=123456 pg_dump -i -h localhost -p 5432 -s -f "$DIR_RESP_CA/$BD1_PGSQL-$FEC_RESP.sql" $BD1_PGSQL
# Respalda el Esquema (solamente) de la BD1_PGSQL
pg_dump -i -h localhost -p 5432 -U postgres -F t -b -v -f "$DIR_RESP_CA/$BD1_PGSQL-$FEC_RESP.backup" $BD1_PGSQL
# PGUSER=postgres PGPASSWORD=123456 pg_dump -i -h localhost -p 5432 -U postgres -F t -b -v -f "$DIR_RESP_CA/$BD1_PGSQL-$FEC_RESP.backup" $BD1_PGSQL
# Respalda toda la Data completa de la BD1_PGSQL
unset PGUSER
unset PGPASSWORD
# RESPALDO DE BD DE MYSQL
MYSQLPASSWORD="root"
MYSQLUSER="mipassword"
BD1_MYSQL=mi_bd_mysql
mysqldump -u $MYSQLPASSWORD -p$MYSQLUSER --add-drop-database --databases --events --ignore-table=mysql.events $BD1_MYSQL > $DIR_RESP_CA/$BD1-$FEC_RESP.sql
# mysqldump -u $MYSQLPASSWORD -p$MYSQLUSER --add-drop-database --all-databases --events --ignore-table=mysql.events > $DIR_RESP_CA/$ALL-BD-$FEC_RESP.sql
# Respalda toda la Data completa de la BD1_MYSQL
mysqldump -u $MYSQLPASSWORD -p$MYSQLUSER --add-drop-database --databases -d $BD1_MYSQL > $DIR_RESP_CA/$BD1-$FEC_RESP.sql
# mysqldump -u $MYSQLPASSWORD -p$MYSQLUSER --add-drop-database --all-databases -d > $DIR_RESP_CA/$BD1-$FEC_RESP.sql
# Respalda el Esquema (solamente) de la BD1_MYSQL
unset MYSQLUSER
unset MYSQLPASSWORD
################################################################################
# FINAL DEL MÓDULO DE RESPALDO DE CONFIGURACIÓN AVANZADA DE EQUIPOS
################################################################################
################################################################################
# INICIO DEL MÓDULO DE RESPALDO DE DATA ESENCIAL DE LOS USUARIOS DEL EQUIPOS
################################################################################
cd $DIR_RESP_DU
tar cvpzf dir_$USER1000_HOST-$FEC_RESP.tar.gz /home/$USER1000_HOST
# tar cvpzf dir_$USER1000_HOST-$FEC_RESP.tar.gz /home/$USER1000_HOST $DIR_RESP_CB/ --exclude="Descargas" --exclude="Download" --exclude="Imágenes" --exclude="Images" --exclude=Música" --exclude=Music --exclude=Vídeos --exclude=Videos --exclude=*.exe --exclude=*.com --exclude=*.dll --exclude=*.mp3 --exclude=*.avi --exclude=*.mkv --exclude=*.msi --exclude=*.mpg --exclude=*.wmv --exclude=*.wma
# Habilitar la linea superior en caso de que desee excluir tipos de archivos
################################################################################
# FINAL DEL MÓDULO DE RESPALDO DE DATA ESENCIAL DE LOS USUARIOS DEL EQUIPOS
################################################################################
################################################################################
# INICIO DEL MÓDULO DE RESPALDO DE VALORES Y PARAMETROS DEL EQUIPO
################################################################################
cd $DIR_RESP_VP
lshw -html > auditoria_tecnica_lshw.html
lshw -short > auditoria_tecnica_lshw_short.txt
lshw -businfo > auditoria_tecnica_lshw_businfo.txt
# Generar reportes del Hardware del Equipo en diversos formatos de archivos.
echo '
################################################################################
# MI_NOMBRE - MI_ORGANIZACIÓN
# LINUX POST INSTALL - RESPALDO DE RESPALDO DE VALORES Y PARAMETROS DEL EQUIPO
# FECHA DEL RESPALDO: $FEC_RESP
################################################################################
================================================================================
' > auditoria_tecnica_$FEC_INI.txt
echo '
================================================================================
' >> auditoria_tecnica_$FEC_INI.txt
echo '
# ALMACENAMIENTO DE VARIABLES INFORMATIVAS
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#
' >> auditoria_tecnica_$FEC_INI.txt
NOMBRE_HOST=$(cat /etc/hostname) ; echo "HOST: $NOMBRE_HOST" >> auditoria_tecnica_$FEC_INI.txt ; echo "" >> auditoria_tecnica_$FEC_INI.txt
# Nombre del Equipo.
FECHA_ACTUAL_EXT=$(date "+%d-%m-%y_%H-%M-%S") ; echo "FECHA: $FECHA_ACTUAL_EXT" >> auditoria_tecnica_$FEC_INI.txt ; echo "" >> auditoria_tecnica_$FEC_INI.txt
# Fecha actual extendida del Sistema
VERSION_SISTEMA=$(cat /etc/os-release | grep VERSION= | sed -n '1p' | sed 's/VERSION=//' | sed 's/"//g') ; echo "VERSION DE LA DISTRO: $VERSION_SISTEMA" >> auditoria_tecnica_$FEC_INI.txt ; echo "" >> auditoria_tecnica_$FEC_INI.txt
# Versión del Sistema Operativo
# Agregue cualquier otra línea de Shell Scripting de su elección
################################################################################
# INICIO DEL MÓDULO DE MANTENIMIENTO DE LOS RESPALDO DEL EQUIPO
################################################################################
chmod -R 777 $DIR_RESP_CA/ ; chown -R $USER1000_HOST. $DIR_RESP_CA/
chmod -R 777 $DIR_RESP_CB/ ; chown -R $USER1000_HOST. $DIR_RESP_CB/
chmod -R 777 $DIR_RESP_DU/ ; chown -R $USER1000_HOST. $DIR_RESP_DU/
chmod -R 777 $DIR_RESP_VP/ ; chown -R $USER1000_HOST. $DIR_RESP_VP/
# Otorgar permisos y propiedad adecuados a los archivos del Respaldo.
DIAS=30
find $DIR_RESP_CA -type f -name '*' -mtime +$DIAS -exec rm -rf {} \;
find $DIR_RESP_CB -type f -name '*' -mtime +$DIAS -exec rm -rf {} \;
find $DIR_RESP_DU -type f -name '*' -mtime +$DIAS -exec rm -rf {} \;
find $DIR_RESP_VP -type f -name '*' -mtime +$DIAS -exec rm -rf {} \;
# Conservar los dias de respaldos locales configurados
################################################################################
# FINAL DEL MÓDULO DE MANTENIMIENTO DE LOS RESPALDO DEL EQUIPO
################################################################################
################################################################################
# INICIO DEL MÓDULO DE COPIADO REMOTO DE LOS RESPALDO DEL EQUIPO
################################################################################
# PARÁMETROS PARA EL COPIADO REMOTO DE LOS RESPALDOS
USER_SERV_RESP=operador
IP_SERV_RESP=172.16.196.10
# PTO_SERV_RESP=4568
DIR_SERV_RESP=/home/operador/tecnologia/Respaldos_Servidores
DIR_SERV_RESP2=/home/operador/tecnologia/Respaldos_Servidores/Dir_Respaldo/*
DIR_USER_SAMBA=/home/samba/tecnologia/Respaldos_Servidores/Dir_Respaldo/
DIR_RESP_HOST=/opt/respaldo/
# COPIADO REMOTO DE LOS RESPALDOS USANDO SCP
# scp -r $DIR_RESP_HOST $USER_SERV_RESP@$IP_SERV_RESP:$DIR_SERV_RESP
# Copiado automatico de los respaldos locales al servidor de backup
# COPIADO REMOTO DE LOS RESPALDOS USANDO RSYNC
rsync -abhv -e 'ssh -p 4568' --iconv=utf-8,iso8859-15 --recursive $DIR_RESP_HOST $USER_SERV_RESP@$IP_SERV_RESP:$DIR_SERV_RESP
ssh operador@172.16.196.10 -p 4568 chmod 777 -R $DIR_SERV_RESP2
ssh operador@172.16.196.10 -p 4568 chown operador. -R $DIR_SERV_RESP2
ssh operador@172.16.196.10 -p 4568 mv $DIR_SERV_RESP2 $DIR_USER_SAMBA
################################################################################
# FINAL DEL MÓDULO DE COPIADO REMOTO DE LOS RESPALDO DEL EQUIPO
################################################################################
################################################################################
# INICIO DEL MÓDULO DE NOTIFICACIÓN REMOTA DE LOS RESPALDO DEL EQUIPO
################################################################################
echo "Respaldo Ejecutado" ; echo "" ; cat auditoria_tecnica_$FEC_INI.txt | mail -s "Notificación de Ejecución de Respaldo y Auditoria Programada" albertccs1976@gmail.com
# Ejecutar correo de notificación de realización de respaldos.
################################################################################
# FINAL DEL MÓDULO DE NOTIFICACION REMOTA DE LOS RESPALDO DEL EQUIPO
################################################################################

View file

@ -0,0 +1,84 @@
#!/bin/bash
# -*- ENCODING: UTF-8 -*-
echo '------------------'
echo '-Iniciando backup-'
echo '------------------'
date '+%A %T'
#Declaramos varibles a usar
dir_base="/var/www/vhosts/web.es/httpdocs/web/web"
dir_storage="/var/www/vhosts/web.es/httpdocs/backup-pruebas/web"
dir_storage_nfs="/var/www/vhosts/web.es/httpdocs/backup-storage/web/"
cd $dir_base
fecha=$(date '+%F')
usu_bd='usuario'
pass_bd='password'
name_bd='moodle'
#Activamos modo mantenimiento forzando la ejecución con PHP 5.6 (moodle 3.3 lo requiere)
/opt/plesk/php/5.6/bin/php www/admin/cli/maintenance.php --enable
#Eliminar backups antiguos: Anteriores a 15 días
find $dir_storage/*.zip -mtime +14 -type f -delete
find $dir_storage/*.sql -mtime +14 -type f -delete
find $dir_storage/*.gz -mtime +14 -type f -delete
echo '--- Backups previos eliminados ---'
dir='www'
echo '--- ZIP '$dir' ---'
printf "\n" >> $dir_storage/backup.log
echo '--- ZIP '$dir' ---' >> $dir_storage/backup.log
fichero=$fecha-$dir.zip
f_ini=$(date '+%T')
zip -rq $dir_storage/$fichero $dir
f_fin=$(date '+%T')
echo ' Proceso completo ['$f_ini']-['$f_fin']: '$fichero
printf "\n" >> $dir_storage/backup.log
echo ' Proceso completo ['$f_ini']-['$f_fin']: '$fichero >> $dir_storage/backup.log
f_ini=$(date '+%T')
mv $dir_storage/$fichero $dir_storage_nfs
f_fin=$(date '+%T')
printf "\n" >> $dir_storage/backup.log
echo ' Fichero movido ['$f_ini']-['$f_fin']: '$fichero >> $dir_storage/backup.log
dir='moodledata'
echo '--- ZIP '$dir' ---'
printf "\n" >> $dir_storage/backup.log
echo '--- ZIP '$dir' ---' >> $dir_storage/backup.log
fichero=$fecha-$dir.zip
f_ini=$(date '+%T')
zip -rq $dir_storage/$fichero $dir
f_fin=$(date '+%T')
echo ' Proceso completo ['$f_ini']-['$f_fin']: '$fichero
printf "\n" >> $dir_storage/backup.log
echo ' Proceso completo ['$f_ini']-['$f_fin']: '$fichero >> $dir_storage/backup.log
f_ini=$(date '+%T')
mv $dir_storage/$fichero $dir_storage_nfs
f_fin=$(date '+%T')
printf "\n" >> $dir_storage/backup.log
echo ' Fichero movido ['$f_ini']-['$f_fin']: '$fichero >> $dir_storage/backup.log
echo '--- DUMP GZIP BBDD ---'
printf "\n" >> $dir_storage/backup.log
echo '--- DUMP GZIP BBDD ---' >> $dir_storage/backup.log
fichero=$fecha-bbdd.sql.gz
f_ini=$(date '+%T')
mysqldump --user=$usu_bd --password=$pass_bd $name_bd | gzip > $dir_storage/$fichero
f_fin=$(date '+%T')
echo ' Proceso completo ['$f_ini']-['$f_fin']: '$fichero
printf "\n" >> $dir_storage/backup.log
echo ' Proceso completo ['$f_ini']-['$f_fin']: '$fichero >> $dir_storage/backup.log
f_ini=$(date '+%T')
mv $dir_storage/$fichero $dir_storage_nfs
f_fin=$(date '+%T')
printf "\n" >> $dir_storage/backup.log
echo ' Fichero movido ['$f_ini']-['$f_fin']: '$fichero >> $dir_storage/backup.log
#Desactivamos modo mantenimiento forzando la ejecución con PHP 5.6 (moodle 3.3 lo requiere)
/opt/plesk/php/5.6/bin/php www/admin/cli/maintenance.php --disable
echo '-------------------'
echo '-Backup finalizado-'
echo '-------------------'
date '+%A %T'

View file

@ -0,0 +1,43 @@
#!/bin/bash
#para que se arranque al logarse hay que modificar el fichero /etc/passwd y en vez de definir el shell como /bin/bash (por ejemplo) hay que definirlo como /bin/jaula.sh (por ejmeplo)
#si el usuario pudiese ejecutar ciertos comandos como por ejemplo un reboot habrá que añadirle al fichero sudoers, por ejemplo: testuser ALL=(ALL) NOPASSWD:ALL
while true
do
INPUT='/tmp/input'
dialog \
--title "SESION LIMITADA" \
--backtitle "SHELL SCRIPT CON LIMITACIONES DE EJECUCION DE COMANDOS" \
--menu "Escoja una opcion" \
0 100 5 \
LIST_LOGS "Ver directorio de logs" \
VER_LOG "Ver un log específico" \
TOP "Ver procesos del sistema" \
MOUNTS "Ver montajes" \
SALIR "Salir" 2>"${INPUT}"
SELECCIONADO=$(<"${INPUT}")
case ${SELECCIONADO} in
LIST_LOGS)
clear
ls -la /var/log | more;;
VER_LOG)
dialog --title "VER LOG" --inputbox "Nombre del log (sin path):" 2>${INPUT} 0 40
clear
LOG="/var/log/"$(cat $INPUT)
dialog --title "LOG A VER" --textbox "LOG: $LOG" 0 0
less $LOG;;
TOP)
top -d 1;;
MOUNTS)
df -h > /tmp/jaula.out
#sudo fdisk --list >> /tmp/jaula.out
less /tmp/jaula.out
rm /tmp/jaula.out;;
SALIR)
clear
exit;;
esac
rm ${INPUT}
done

View file

@ -0,0 +1,6 @@
#!/bin/sh
ps -eo rss,pid,user,command | sort -rn | head -$1 | awk '{ hr[1024**2]="GB"; hr[1024]="MB";
for (x=1024**3; x>=1024; x/=1024)
{ if ($1>=x) { printf ("%-6.2f %s ", $1/x, hr[x]); break }
} } { printf ("%-6s %-10s ", $2, $3) }
{ for ( x=4 ; x<=NF ; x++ ) { printf ("%s ",$x) } print ("\n") } '

18
php/ldap_test.php Normal file
View file

@ -0,0 +1,18 @@
<?php
// ejemplo de autenticación
$ldaprdn = 'USUARIO'; // ldap rdn or dn
$ldappass = 'PASSWORD'; // associated password
// conexión al servidor LDAP
$ldapconn = ldap_connect("DOMINIO",389)
or die("Could not connect to LDAP server.");
if ($ldapconn) {
// realizando la autenticación
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
// verificación del enlace
if ($ldapbind) {
echo "LDAP bind successful...";
} else {
echo "LDAP bind failed...".$ldapbind;
}
}
?>

28
php/obtenipcliente.php Normal file
View file

@ -0,0 +1,28 @@
<?php
$ip=get_client_ip();
//Obtiene la IP del cliente
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
echo "IP: ".$ip;
?>

2
php/test.php Normal file
View file

@ -0,0 +1,2 @@
<?php echo phpinfo() ?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,7 @@
Set-ExecutionPolicy Unrestricted
New-NetFirewallRule -DisplayName ichttpuser -Action Allow -Authentication NotRequired -Direction Inbound -Enabled True -InterfaceType Any -Protocol TCP -Program "%ProgramFiles% (x86)\inConcert\Agent\ICHttpUser.exe"
New-NetFirewallRule -DisplayName ichttpuser -Action Allow -Authentication NotRequired -Direction Inbound -Enabled True -InterfaceType Any -Protocol UDP -Program "%ProgramFiles% (x86)\inConcert\Agent\ICHttpUser.exe"
New-NetFirewallRule -DisplayName iciaxphone -Action Allow -Authentication NotRequired -Direction Inbound -Enabled True -InterfaceType Any -Protocol TCP -Program "%ProgramFiles% (x86)\inConcert\Agent\iciaxphone.exe"
New-NetFirewallRule -DisplayName iciaxphone -Action Allow -Authentication NotRequired -Direction Inbound -Enabled True -InterfaceType Any -Protocol UDP -Program "%ProgramFiles% (x86)\inConcert\Agent\iciaxphone.exe"
New-NetFirewallRule -DisplayName "SIPPhone Module" -Action Allow -Authentication NotRequired -Direction Inbound -Enabled True -InterfaceType Any -Protocol TCP -Program "%ProgramFiles% (x86)\inConcert\Agent\SIPPhone.exe"
New-NetFirewallRule -DisplayName "SIPPhone Module" -Action Allow -Authentication NotRequired -Direction Inbound -Enabled True -InterfaceType Any -Protocol UDP -Program "%ProgramFiles% (x86)\inConcert\Agent\SIPPhone.exe"

View file

@ -0,0 +1,10 @@
$U = Import-Csv usuarios.txt -Delimiter ' ' -Header 'NOMBRE', 'APELLIDO-1', 'APELLIDO-2'
#$U | Format-Table
$salida = @(foreach ($user in $U) {
$givenname = $user.NOMBRE
$surname = $user.'APELLIDO-1' + ' ' + $user.'APELLIDO-2'
$usuario = $givenname + ' ' + $surname
Echo $usuario
Get-aduser -filter {GivenName -eq $givenname -and Surname -like $surname} -Properties * | select SamAccountName,HomeDirectory
})
Echo $salida > salida.txt

View file

@ -0,0 +1,2 @@
Import-Module ActiveDirectory
Get-Content C:\Datos\usuarios.txt | Get-ADUser -Properties * | select UserPrincipalName,HomeDirectory | export-csv C:\Datos\salida.csv -Encoding utf8 -NoTypeInformation -Delimiter ","

View file

@ -0,0 +1,9 @@
$ipaddress = IP_Address_Server
$port = port
$connection = New-Object System.Net.Sockets.TcpClient($ipaddress, $port)
if ($connection.Connected) {
    Write-Host "Success"
}
else {
    Write-Host "Failed"
}

View file

@ -0,0 +1,14 @@
$threshold = 30 #Number of days to look for expiring certificates
$deadline = (Get-Date).AddDays($threshold) #Set deadline date
$lm = "Cert:\localmachine\"
$lmDir = Dir Cert:\localmachine\ | select name
foreach ($dir in $lmdir) {
$path = $lm + $dir.name
Dir $path | foreach {
If ($_.NotAfter -le $deadline) {
$_ | select @{label="directorio";Expression={$path}}, Issuer, Subject, NotAfter, @{Label="Expires In (Days)";Expression={($_.NotAfter - (Get-Date)).Days}}
}
}
}

View file

@ -0,0 +1,3 @@
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking

View file

@ -0,0 +1,13 @@
# poner los login entre comillas simples
$userOrigen = 'usrorigen' # LOGIN DEL USUARIO QUE TIENE LOS GRUPOS
$userDestino = 'usrdestino' # LOGIN DEL USUARIO AL QUE HAY QUE COPIAR LOS GRUPOS
$grupos = Get-ADPrincipalGroupMembership $userOrigen | select distinguishedName
# GUARDO LOS GRUPOS ORIGINALES DEL USUARIO DESTINO POR SI HUBIESE QUE RECUPERARLOS
$fichero = 'Grupos_originales_de_' + $userDestino + '.txt'
Get-ADPrincipalGroupMembership $userDestino | select distinguishedName | Out-File -FilePath $fichero
foreach ($grupo in $grupos) {
Write-Host ">> Añadiendo " $userDestino " al grupo " $grupo.distinguishedName
Add-ADGroupMember -Identity $grupo.distinguishedName -Members $userDestino
}

572
powershell/ejemplos.ps1 Normal file
View file

@ -0,0 +1,572 @@
#38 guardar texto o variables en un fichero
Escribir un texto en un archivo, sobreescribiéndolo en caso de que existiera.
$textoAGuardar | Out-File -FilePath $rutaDelArchivo
Escribir un texto en un archivo, sobreescribiéndolo en caso de que existiera incluso si es de sólo lectura.
$textoAGuardar | Out-File -FilePath $rutaDelArchivo -Force
Escribir un texto en un archivo, añadiendo el texto al final en caso de que existiera.
$textoAGuardar | Out-File -FilePath $rutaDelArchivo -Append
Escribir un texto en un archivo, sobreescribiéndolo en caso de que existiera con formato ASCII.
$textoAGuardar | Out-File -FilePath $rutaDelArchivo -Encoding ASCII
Escribir el contenido de un objeto en un archivo, sobreescribiéndolo en caso de que existiera.
Out-File -FilePath $rutaDelArchivo -Encoding ASCII -InputObject $textoAGuardar
#37 emular el comando top de Linux
while (1) { ps | sort -desc cpu | select -first 30; sleep -seconds 2; cls }
#36 uso de for
clear
$ints = @('fer','camila','dan')
for ($i=0; $i -le $ints.Length 1; $i++)
{Write-Host $ints[$i]}
#35 paso de parametros
$args
"no. de parametros: $($args.count)"
# 34 horoscopo chino
clear
$datos = @{0="mono";1="gallo";2="perro";3="cerdo";4="rata";5="buey";6="tigre";7="conejo";8="dragon";9="serpiente";10="caballo";11="cabra"}
$datos | Sort-Object
$anyo=Read-Host "Introduce año: "
$resto=$anyo%12
Write-Host "Te corresponde el signo de: "$datos.get_Item($resto)
#33 cuenta vocales
Clear-Host
$cadena=Read-Host "Introduce cadena"
Write-Host "introduciste " $cadena
$cont=0
$aux=""
for($i=0;$i -le $cadena.Length;$i++){
$c=$cadena[$i]
if($c -eq "a" -or $c -eq "e" -or $c -eq "i" -or $c -eq "o" -or $c -eq "u"){
$cont++
$aux+=","+$c
}
}
Write-Host "no. de vocales: "$cont", vocales obtenidas: "$aux
#32 uso de expresiones regulares
Clear-Host
"Fernando" -match "F.er"
"Ariel" -match ".riel"
"En un campo alegre" -match "E?a"
"mi gata" -match "m.g"
"mia" -match "m+a"
"mia" -match "m?a"
"mia" -match "m\.a"
"Fer" -match "\w*"
"Fer" -match "\w"
$correo="gatibal.gato@latinmail.com"
$correo.Replace("latinmail","gmail")
"gatibal.gato@gmail.com".Replace("@gmail.com","@yahoo.com.mx")
$cadena="Mi gato come mucho"
Write-Host "tamaño: " $cadena.Length
Write-Host "ahora: " $cadena.Remove(3)
#31 enviar correo
$filename = c:\scripts_scott\test9999.xls
$smtpserver = smtp.gmail.com
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($filename)
$smtp = new-object Net.Mail.SmtpClient($smtpServer )
$smtp.EnableSsl = $True
$smtp.Credentials = New-Object System.Net.NetworkCredential(username, password_here); # Put username without the @GMAIL.com or @gmail.com
$msg.From = username@gmail.com
$msg.To.Add(boss@job.com)
$msg.Subject = Monthly Report
$msg.Body = Good Morning, Last months LOGINS & GROUPCALLS FOR ALL GIDS IN SYSTEM IS ATTACHED
$msg.Attachments.Add($att)
$smtp.Send($msg)
#30 calcular valor futuro
clear-host
"----------------------------------"
" Menú "
"----------------------------------"
$valor=read-host "Valor: "
$tasa=read-host "Tasa:"
$periodo=read-host "Periodo:"
$resultado=0
#mostrar valores
write-host "valor : $valor"
write-host "tasa : $tasa"
write-host "periodo : $periodo"
""
""
"[Resultado]"
foreach ($n in 1..$periodo) {
$resultado=[math]::pow(1+$tasa/100,$n)
$resultado=$resultado*$valor
write-host "$resultado periodo --> $n"
}
#29 introducir datos
$nombre = Read-Host "Tu nombre: "
$password = Read-Host -assecurestring "Tu clave: "
#mostrar
write-host "Hola $nombre"
Clear-Host
$YearCalc = Read-Host "¿cuando naciste?"
$Now = (Get-Date -uformat "%Y") -$YearCalc
$Maybe = $Now -1
Write-Host "tu tienes $Maybe o $Now años"
#28 ejemplo de función con parámetros
$g=9.81
Function altura{
param($t)
if($t -eq 0){
return 0
} else {
return ($g*[System.Math]::Pow($t,2))/2
}
}
$result=altura(6.309)
write-host "$result"
#27 bucle foreach
$lista=200,250,300,350,400
write-host "lista [$lista]"
foreach($l in $lista){
if($l -eq 250){
"$l, valor encontrado"
} else {
$result=$l*2;
write-host "$l $l*2: $result"
}
}
#26 menú básico
clear-host
write-host "#############################"
write-host ""
write-host " Menu "
write-host ""
write-host "1. Ver version"
write-host "2. Ver fecha"
write-host "3. Ver ayuda"
write-host "4. Abrir bloc de notas"
write-host "5. Abrir calculadora"
write-host "6. Salir"
write-host "#############################"
$opc = Read-Host "Tu opcion: "
write-host ""
write-host "introduciste [$opc]"
#if(opc != 0 || opc >= 6)
if($opc -ne 0 -or $opc -ge 6){
switch($opc){
1 {write-host "version" -ForegroundColor Cyan
get-host
}
2 {write-host "fecha" -ForegroundColor Cyan
get-date
}
3 {write-host "ayuda" -ForegroundColor Cyan
get-help
}
4 {write-host "bloc de notas" -ForegroundColor Cyan
abreBloc
}
5 {write-host "calculadora" -ForegroundColor Cyan
abreCalc
}
6 {write-host "fin" -ForegroundColor Red
exit
}
}#fin switch
}
# Microsoft PowerShell script to create a simple function
# Author: Guy Thomas
# Version 2.1 May 2008 tested on PowerShell v 1.0
#function BatAvg
#{param ($Name, $Runs, $Outs)
#$Avg = [int]($Runs / $Outs*100)/100
#Write-Output "$Name's Average = $Avg, $Runs, $Outs "
#}
Function abreBloc{
start notepad
}
Function abreCalc{
start calc
}
#25
clear
"#############################################
# Powershell #
#############################################"
get-host
$cadena="pelo"
$archivo="C:\Users\fernando\Documents\Ejemplos\servicio.txt"
$fecha=(get-date)
$fecha
$nombre = Read-Host "Tu nombre es: "
$password = Read-Host -assecurestring "Tu password: "
write-host "Bienvenido $nombre"
"Te encuentras en:"
gl
"usuario:"
whoami
$cad=$cadena-replace("l","rr")
$cad
"contenido del archivo:"
get-content $archivo
$compara=whoami
if($nombre -eq $compara){"iguales"}else{"no iguales"}
function abre{
param($nombre)
if($nombre -eq "fernando"){"start notepad"}else{"start calc, nada igual"}
}
#invocar a la función
abre($nombre)
$numero= read-host "número: "
switch($numero){
1 {" abre"}
2 {" cierra"}
3 {" apaga"}
default {"inactivo"}
}
try{
"abriendo archivo, se ejecuto esto"
abre($nombre)
}catch{
"no se encuentra el archivo"
}
$cont=0
$maximo=10
while($cont -le $maximo){
write-host "$cont"
$cont+=1
}
$b=90
$a=700
$persistent = "False"
[System.Convert]::ToBoolean($persistent)
function comparar($b){
if($b -eq $a){
"real"
}else{
" no existe"
}
}
comparar($b)
$persistent.gettype()
#Get-Process | ForEach-Object {Write-Host $_.name -foregroundcolor cyan}
#write-host "Algo"
#############################################
#$a = (get-date).day
#$a = (get-date).dayofweek
#$a = (get-date).dayofyear
#$a = (get-date).hour
#$a = (get-date).millisecond
#$a = (get-date).minute
#$a = (get-date).month
#$a = (get-date).second
#$a = (get-date).timeofday
#$a = (get-date).year
#get-date -DisplayHint date
#$now=Get-Date -format "dd-MMM-yyyy HH:mm"
#get-date -format g
#(get-date).dayofyear
#$a = get-wmiobject win32_bios -computer SERVER64
#$a | format-list -property Name, @{Label="BIOS Date "; `
#Expression={$_.ConvertToDateTime($_.ReleaseDate)}}
#######################################################
#dir <enter>
#ls <enter>
#gci <enter>
Get-ChildItem <enter>
#asignar un alias
Set-Alias gs Get-Service <enter>
#exportar contenido a un txt
Export-Alias -Path Aliases.txt <enter>
#24
clear
Get-Content C:\servicio.txt
$a = Get-Content C:\Users\fernando\Documents\Ejemplos\servicio.txt
write-host "$a"
(Get-Content C:\Users\fernando\Documents\Ejemplos\servicio.txt)[0 .. 2]
$arch=get-content C:\Users\fernando\Documents\Ejemplos\servicio.txt
ForEach-Object {Write-Host $arch -foregroundcolor red}
foreach ($number in 1..10 ) { $number * 4}
# PowerShell foreach loop to display files in C:\Program files
$Path = "C:\Program Files\"
"{0,10} {1,-24} {2,-2}" -f `
" Size", "Last Accessed", "File Name "
Foreach ($file in Get-Childitem $Path -recurse -force) {
If ($file.extension -eq ".txt") {
"{0,10} {1,-24} {2,-2}" -f `
$file.length, $file.LastAccessTime, $file.fullname
}
}
# PowerShell foreach loop piping into block statement
Clear-Host
$Path = "C:\Program Files\"
Get-Childitem $Path -recurse -force | Foreach {
If ($_.extension -eq ".txt") {
Write-Host $_.fullname
}
}
$strResponse = Quit
do {$strResponse = Read-Host Are you sure you want to quit application? (Y/N)} until ($strResponse -eq Y)
New-Item -ItemType file freespace.txt
$date = ( get-date ).ToString('yyyyMMdd')
$file = New-Item -type file "$date-freespace.txt"
$date = ( get-date ).ToString('yyyyMMdd')
ForEach ($system in Get-Content "servicio.txt")
{Write-Host $system}
#23 función sencilla
function mensaje{
"hola"
}
mensaje
#22
$num1=9
$num2=4
"Valores booleanos"
$res=$num1 -gt $num2
Write-Host "$num1 -gt $num2 "$res
$res=$num1 -lt $num2
Write-Host "$num1 -lt $num2 "$res
$res=$num1 -eq $num2
Write-Host "$num1 -eq $num2 "$res
$res=$num1 -ne $num2
Write-Host "$num1 -ne $num2 "$res
$res=$num1 -le $num2
Write-Host "$num1 -le $num2 "$res
$res=$num1 -ge $num2
Write-Host "$num1 -ge $num2 "$res
#21 estructuras de control
Write-Host "uso de do{}while(cond)"
$i = 1
do {
Write-Host $i
$i++
} while ($i -le 5)
Write-Host "uso de while(cond){}"
$i = 1
while ($i -le 5) {
Write-Host $i
$i++
}
Write-Host "uso de do{}until(cond)"
$i = 1
do {Write-Host $i; $i++}
until ($i -gt 5)
$strResponse = Quit
do {$strResponse = Read-Host Are you sure you want to quit application? (Y/N)}
until ($strResponse -eq Y)
Write-Host "uso de for"
for ($i=1; $i -le 5; $i++)
{Write-Host $i}
$ints = @( 1, 2, 3, 4, 5)
for ($i=0; $i -le $ints.Length 1; $i++)
{Write-Host $ints[$i]}
Write-Host "uso de foreach"
$ints = @(1, 2, 3, 4, 5)
foreach ($i in $ints)
{Write-Host $i}
#20
$ubicacion=gl
Write-Host "te encuentras en:" $ubicacion
Get-Help -Name Get-Process
#19
$cadena="Fernando Carraro"
Write-Host "Hola "$cadena
$cadena -match "aro"
$cadena -match "er"
$cadena -match "nando"
#18 ver fecha
$fecha=Get-Date
write-host "hoy es "$fecha
#17 ver ubicación
$variable=gl
"estas en: "
$variable
#16 Pedir nombre y mostrarlo
$nombre=Read-Host "tu nombre "
"Hola "
$nombre
Write-Host "hola "$nombre
#15
write-host
write-host "ShowPrnH.ps1, Version 1.01"
write-host "Show available printers in HTML"
write-host "Written by Rob van der Woude"
write-host "http://www.robvanderwoude.com"
write-host
get-wmiobject -class Win32_Printer | convertto-html Name,Default,Network,PortName,DriverName,ServerName,ShareName -head "<title>All printers available on $env:computername</title>`n<style type=`"text/css`">`nbody { padding: 8px; line-height: 1.33 }`ntable { border-style: ridge }`ntd, th { padding: 10px; border-style: dotted; border-width: 1px }`nth { font-weight: bolder; text-align: center }`n</style>" | out-file -FilePath "showprnh.html" -Encoding "ASCII"
invoke-item "showprnh.html"
#14 una función
function ver{
"estas en: "
gl
}
ver
#13 operaciones básicas
$num1=99
$num2=32.33
"datos:"
$num1
$num2
$suma=$num1 + $num2
$resta=$num1 - $num2
$producto=$num1 * $num2
$division=$num1 / $num2
write-host "suma: $suma"
write-host "resta: $resta"
write-host "producto: $producto"
write-host "division: $division"
#12.
write-host "Datos del sistema:"
New-Object System.io.DriveInfo "C:" | Format-List *
$drive = New-Object System.io.DriveInfo "C:"
$drive.DriveFormat
$drive.VolumeLabel
#11. Cómo mostrar el nombre de los archivos y el tamaño cuyo tamaño sea 79 bytes en powershell ?
gci |select name,length | where {$_.length -eq 76}
#10. Cómo mostrar el nombre de los archivos y el tamaño ordenados por tamaño
gci |select name,length |sort length desc
#9. obtener una lista de archivos y guardarla en un archivo de texto *.txt
gci> listaArchivos.txt
#8. Crear una función
function mensaje{
"hola desde una función"
}
mensaje
#7. Operadores aritméticos y booleanos
$a=99
$b=2
Write-Host "a= $a y b= $b"
$result=($a -lt $b)
write-host "($a -lt $b): $result"
$result=($a -gt $b) -or ($b -lt $a)
write-host "($a -gt $b) -or ($b -lt $a): $result"
$result=($a -eq $a) -and ($b -lt $a)
write-host "($a -eq $b) -and ($b -lt $a): $result"
#6.Operaciones básica: suma, resta , producto y división
$a=34
$b=25
$suma= $a+$b
$resta= $a-$b
$producto= $a*$b
$division= $a/$b
write "$a + $b = $suma"
write "$a - $b = $resta"
write "$a * $b = $producto"
write "$a / $b = $division"
#5. Introducir datos
$nombre=Read-Host "tu nombre es: "
Write-Host "bienvenido $nombre"
#4. definir una variable
$miVariable="soy una variable"
Write-Host $miVariable
echo $miVariable
$miVariable
#3. hola mundo con echo
echo "hola mundo desde PowerShell"
#2. hola mundo con write-host
Write-Host "hola mundo desde PowerShell"
# 1. hola mundo con comillas
"Hola mundo desde PowerShell"

View file

@ -0,0 +1,2 @@
Import-Module ActiveDirectory
Get-Content usuarios.txt | Get-ADUser | select SamAccountName,DistinguishedName,Enabled | export-csv C:\Datos\scripts\salida.csv -Encoding utf8 -NoTypeInformation -Delimiter ","

View file

@ -0,0 +1,6 @@
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking
Get-MailboxStatistics usuario@dominio | fl TotalDeletedItemSize,DeletedItemCount,IsArchiveMailbox
Get-Mailbox usuario@dominio | fl RecoverableItemsQuota,RecoverableItemsWarningQuota

View file

@ -0,0 +1 @@
Get-ADPrincipalGroupMembership user | select name

View file

@ -0,0 +1 @@
Get-WmiObject -ComputerName (Get-Content "c:\temp\cores.csv") -class Win32_processor | select -property pscomputername,numberofcores

View file

@ -0,0 +1,6 @@
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking
Get-MailboxStatistics usuario@dominio | fl TotalItemSize,ItemCount,IsArchiveMailbox
Get-Mailbox usuario@dominio | fl IssueWarningQuota,ProhibitSendQuota,ProhibitSendReceiveQuota

View file

@ -0,0 +1,2 @@
Import-Module ActiveDirectory
Get-Aduser -Filter * -Properties DisplayName, mail, DistinguishedName | Select-Object DisplayName, mail, DistinguishedName | export-csv Usuarios_AD.csv -Encoding utf8 -NoTypeInformation -Delimiter ";"

View file

@ -0,0 +1 @@
Get-ADGroupMember Grupo -recursive | Get-Aduser -Properties CN, DisplayName, Enabled | Select-Object CN, DisplayName, Enabled | Format-Table -AutoSize > "Grupo.txt"

View file

@ -0,0 +1,14 @@
$servidores = Get-Content equipos.txt
foreach ($server in $servidores) {
Write-Host ">> Pingeando al equipo " $server
$testping = Test-Connection $server -Quiet
if ($testping -like "True") {
Write-Host " +" $server "Si responde"
"SI " + $server >> resultado_ping.txt
}
else {
Write-Host " -" $server "No responde"
"NO " + $server >> resultado_ping.txt
}
}

View file

@ -0,0 +1,37 @@
# Get all the provisioned packages
$Packages = (get-item 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications') | Get-ChildItem
# Filter the list if provided a filter
$PackageFilter = $args[0]
if ([string]::IsNullOrEmpty($PackageFilter))
{
echo "No filter specified, attempting to re-register all provisioned apps."
}
else
{
$Packages = $Packages | where {$_.Name -like $PackageFilter}
if ($Packages -eq $null)
{
echo "No provisioned apps match the specified filter."
exit
}
else
{
echo "Registering the provisioned apps that match $PackageFilter"
}
}
ForEach($Package in $Packages)
{
# get package name & path
$PackageName = $Package | Get-ItemProperty | Select-Object -ExpandProperty PSChildName
$PackagePath = [System.Environment]::ExpandEnvironmentVariables(($Package | Get-ItemProperty | Select-Object -ExpandProperty Path))
# register the package
echo "Attempting to register package: $PackageName"
Add-AppxPackage -register $PackagePath -DisableDevelopmentMode
}

View file

@ -0,0 +1,6 @@
#Import-Module ActiveDirectory
$admins = Get-ADGroupMember -identity Administradores -recursive | select name
foreach ($admin in $admins) {
Get-ADUser -identity $admin.Name | select SamAccountName,GivenName,SurName
}

View file

@ -0,0 +1 @@
Get-aduser -filter {GivenName -eq "Nombre" -and Surname -eq "Apellidos"}

View file

@ -0,0 +1,2 @@
Import-Module ActiveDirectory
Get-Content perfiles.txt | Get-ADUser -ErrorAction SilentlyContinue | Where {$_.Enabled -match "False"} | select samaccountname,DistinguishedName,Enabled | export-csv usuarios_inactivos_con_perfil.csv -Encoding utf8 -NoTypeInformation -Delimiter ","

View file

@ -0,0 +1,2 @@
Import-Module ActiveDirectory
Get-Content perfiles.txt | Get-ADUser 2>> "perfiles_huerfanos.txt" | Where {$_.Enabled -match "False"} | select samaccountname,DistinguishedName,Enabled | export-csv usuarios_inactivos_con_perfil.csv -Encoding utf8 -NoTypeInformation -Delimiter ","

View file

@ -0,0 +1,5 @@
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking
Get-Mailbox -Identity "usuario" | Format-List
Remove-PSSession $Session

View file

@ -0,0 +1,59 @@
$espacios = Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName (Get-Content "c:\temp\equipos.txt") | select -property PSComputerName, Name, FreeSpace, Size | % {$_.FreeSpace="{0:n2}" -f ($_.FreeSpace/1GB); $_.Size="{0:n2}" -f ($_.Size/1GB); $_};
Write-Host $espacios
for($i=0; $i -lt $espacios.Count; $i++) {
$total = $espacios[$i].Size;
$libre = $espacios[$i].FreeSpace;
$porcentaje = [math]::round(([int]$libre * 100) / [int]$total);
$color = 'GREEN';
if ([int]$porcentaje -lt 15) {
$color = 'YELLOW'; }
elseif ([int]$porcentaje -lt 5) {
$color = 'RED'; }
Write-Host $espacios[$i].PSComputerName -NoNewline; Write-Host ' ' -NoNewline; Write-Host $espacios[$i].Name -NoNewline; Write-Host ' ' -NoNewline;Write-Host $porcentaje% -ForegroundColor $color -NoNewline; Write-Host ' ' -NoNewline; Write-Host '(',TOTAL: $total, LIBRE: $libre,')';
}
<#
class Win32_LogicalDisk : CIM_LogicalDisk
{
uint16 Access;
uint16 Availability;
uint64 BlockSize;
string Caption;
boolean Compressed;
uint32 ConfigManagerErrorCode;
boolean ConfigManagerUserConfig;
string CreationClassName;
string Description;
string DeviceID;
uint32 DriveType;
boolean ErrorCleared;
string ErrorDescription;
string ErrorMethodology;
string FileSystem;
uint64 FreeSpace;
datetime InstallDate;
uint32 LastErrorCode;
uint32 MaximumComponentLength;
uint32 MediaType;
string Name;
uint64 NumberOfBlocks;
string PNPDeviceID;
uint16 PowerManagementCapabilities[];
boolean PowerManagementSupported;
string ProviderName;
string Purpose;
boolean QuotasDisabled;
boolean QuotasIncomplete;
boolean QuotasRebuilding;
string Size;
string Status;
uint16 StatusInfo;
boolean SupportsDiskQuotas;
boolean SupportsFileBasedCompression;
string SystemCreationClassName;
string SystemName;
boolean VolumeDirty;
string VolumeName;
string VolumeSerialNumber;
};
#>

View file

@ -0,0 +1,30 @@
# Script to wake up a computer.
#
# v1.0 - 2012-07-30 Pedro Castro
# usage:
# .\Ligar-Maquina.ps1 -mac 00:1D:92:51:4C:41
param(
[string]$mac = '18:60:24:AA:E1:42' #address of the network card (MAC address)
)
#checks the syntax of MAC address
if (!($mac -like "*:*:*:*:*:*") -or ($mac -like "*-*-*-*-*-*")){
write-error "mac address not in correct format"
break
}
write "mac: "$mac
#build magic package http://en.wikipedia.org/wiki/Wake-on-LAN#Magic_packet
$string=@($mac.split(":""-") | foreach {$_.insert(0,"0x")})
$target = [byte[]]($string[0], $string[1], $string[2], $string[3], $string[4], $string[5])
# The magic packet is a broadcast frame containing anywhere within its payload 6 bytes of all 255 (FF FF FF FF FF FF in hexadecimal)
$packet = [byte[]](,0xFF * 102)
# followed by sixteen repetitions of the target computer's 48-bit MAC address, for a total of 102 bytes.
6..101 |% { $packet[$_] = $target[($_%6)]}
# .NET framework lib para sockets
$UDPclient = new-Object System.Net.Sockets.UdpClient
$UDPclient.Connect(([System.Net.IPAddress]::Broadcast),4000)
$UDPclient.Send($packet, $packet.Length) | out-null

View file

@ -0,0 +1,26 @@
#! /usr/local/bin/python
from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
from_addr = "John Doe <john@doe.net>"
to_addr = "foo@bar.com"
subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
% ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()

26
python/send_email_ssl.py Normal file
View file

@ -0,0 +1,26 @@
#! /usr/local/bin/python
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
msg = MIMEMultipart()
msg['From'] = 'me@gmail.com'
msg['To'] = 'you@gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('me@gmail.com', 'mypassword')
mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string())
mailserver.quit()

View file

@ -0,0 +1,47 @@
#! /usr/local/bin/python
SMTPserver = 'smtp.att.yahoo.com'
sender = 'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']
USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
subject="Sent from Python"
import sys
import os
import re
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.quit()
except:
sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message

View file

@ -0,0 +1,67 @@
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(host, port, user, pwd, recipients, subject, body, html=None, from_=None):
""" copied and adapted from
https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python#12424439
returns None if all ok, but if problem then returns exception object
"""
PORT_LIST = (25, 587, 465)
FROM = from_ if from_ else user
TO = recipients if isinstance(recipients, (list, tuple)) else [recipients]
SUBJECT = subject
TEXT = body.encode("utf8") if isinstance(body, unicode) else body
HTML = html.encode("utf8") if isinstance(html, unicode) else html
if not html:
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
else:
# https://stackoverflow.com/questions/882712/sending-html-email-using-python#882770
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = ", ".join(TO)
# Record the MIME types of both parts - text/plain and text/html.
# utf-8 -> https://stackoverflow.com/questions/5910104/python-how-to-send-utf-8-e-mail#5910530
part1 = MIMEText(TEXT, 'plain', "utf-8")
part2 = MIMEText(HTML, 'html', "utf-8")
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
message = msg.as_string()
try:
if port not in PORT_LIST:
raise Exception("Port %s not one of %s" % (port, PORT_LIST))
if port in (465,):
server = smtplib.SMTP_SSL(host, port)
else:
server = smtplib.SMTP(host, port)
# optional
server.ehlo()
if port in (587,):
server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
# logger.info("SENT_EMAIL to %s: %s" % (recipients, subject))
except Exception, ex:
return ex
return None

View file

@ -0,0 +1,16 @@
ex = send_email(
host = 'smtp.gmail.com'
#, port = 465 # OK
, port = 587 #OK
, user = "xxx@gmail.com"
, pwd = "xxx"
, from_ = 'xxx@gmail.com'
, recipients = ['yyy@gmail.com']
, subject = "Test from python"
, body = "Test from python - body"
)
if ex:
print("Mail sending failed: %s" % ex)
else:
print("OK - mail sent"

View file

@ -0,0 +1,35 @@
#!/usr/bin/env python3
from email.message import EmailMessage
from getpass import getpass
from smtplib import SMTP_SSL
from sys import exit
smtp_server = 'smtp.gmail.com'
username = 'your_email_address@gmail.com'
password = getpass('Enter Gmail password: ')
sender = 'your_email_address@gmail.com'
destination = 'recipient_email_address@gmail.com'
subject = 'Sent from Python 3.x'
content = 'Hello! This was sent to you via Python 3.x!'
# Create a text/plain message
msg = EmailMessage()
msg.set_content(content)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = destination
try:
s = SMTP_SSL(smtp_server)
s.login(username, password)
try:
s.send_message(msg)
finally:
s.quit()
except Exception as E:
exit('Mail failed: {}'.format(str(E)))

View file

@ -0,0 +1,6 @@
@echo off
for /f %%a in (usuarios.txt) do (
echo consultando usuario %%a
rem dsquery user -name %%a >> grupos.txt
rem dsmod group BAJAS -addmbr %%a
)

2
windows/cambia_mtu.bat Normal file
View file

@ -0,0 +1,2 @@
rem el mtu por defecto es 1500
netsh interface ipv4 set subinterface interface=Ethernet mtu=%1 store=persistent

View file

@ -0,0 +1,6 @@
SERVICIOS ARRANCADOS:
PsExec64.exe \\$nombre_ip$ net start
TAREAS PROGRAMAS:
PsExec64.exe \\$nombre_ip$ schtasks

Some files were not shown because too many files have changed in this diff Show more