Archivos de la categoría ‘script’

I am playing with git and github. I think that I will upload to this repository (http://github.com/keymon/snippets) all my small scripts and stuff.

Here goes one script to split, compress and asymetrically crypt big files. It is really usefull to upload or send big files to support.

It uses dd to split the files, gzip to compress them and gpg to optionally crypt. It will also uncompress or check the stripes.

(más…)

# Dividir ficheros en directorios para gravar DVDs

SIZE=0
COUNT=0
for i in *.gz; do
 FSIZE=$(ls -l $i | awk '{print $5}')
 SIZE=$(($SIZE+$FSIZE/1024))

 echo "Moviendo $i ($FSIZE) a dvd$COUNT/ ($SIZE)"
 if [ "$SIZE" -gt "$((4500*1024))" ]; then
 COUNT=$(($COUNT+1))
 SIZE=0
 fi
 [ -d  dvd$COUNT ] || mkdir -p dvd$COUNT
 mv $i dvd$COUNT/
done

The AIX service secldapclntd «Provides and manages connection between the AIX LDAP load module of the local host and LDAP Security Information Server, and handles transactions from the LDAP load module to the LDAP Security Information Server.»

This services fails too often. Each new version of AIX, brings new failures in this services. Failures appear more often if the LDAP server has a lot of users and groups.

When it fails:

  • sometimes does not reply, its hung
  • sometimes it consumes all CPU and lasts a lot to reply
  • sometimes it simply dies with a core.

This script will check and monitor it and restart it if necesary.

You can test this script stoping the service:

kill -STOP $(ps -fea| grep -v grep |grep /usr/sbin/secldapclntd| awk '{print $2}' )

You can add an entry to cron to execute it:

if crontab -l | grep /usr/local/bin/check-secldapclntd.sh; then
   echo "Already configured."
else
  crontab -l > /tmp/$$.crontab
  cat >> /tmp/$$.crontab <<EOF
# Check secldapclntd each 5 minutes
5,10,15,20,25,30,35,40,45,50,55 * * * * /usr/local/bin/check-secldapclntd.sh check-and-restart > /dev/null
EOF
  crontab /tmp/$$.crontab
  rm /tmp/$$.crontab
fi

And here goes the script (/usr/local/bin/check-secldapclntd.sh):

Sometimes we need to allow some users to remotelly execute commands in a server via ssh, but we want to restrict the commands to execute. There are some solutions around, like restricted shell or wrappers, but we can implement a simply solution using bash and sudo.

The idea is to use the restricted shell functionality in bash. We will simply:

  • Create a new user for this prupose
  • Asign it a script that will restrict the $PATH variable
  • Link there the needed commands (or create scripts that call sudo)
  • Set asymetric keys in ssh.

Here you have all commands for Linux or AIX, but it will work anyway (except the creation of the user).

# You have to set this variables before execute any command
# ---------------------------------------------------
# If we will use sudo for commands or only links
USE_SUDO=yes
# User restricted and commands to link or sudo
RESTRICTED_USER=jailuser
RESTRICTED_COMMANDS="
/somepath/somecommand1
/somepath/somecommand1
/somepath/somecommand1
"
# Remote host where execute commands
REMOTE_HOST=ahost
# final user to execute commands (sudo)
DEST_USER=arealuser
# ---------------------------------------------------



case `uname` in
AIX)
# Add shell script as new user
chsec -f /etc/security/login.cfg -s usw -a shells=$(lssec -f /etc/security/login.cfg -s usw -a shells | cut -f 2 -d =),/home/$RESTRICTED_USER/bin/rbash
mkdir /home/$RESTRICTED_USER/bin

# Create user
mkuser groups=sshcon maxexpired=-1 loginretries=-1 $RESTRICTED_USER

# Do not need to change password
pwdadm -c $RESTRICTED_USER
;;
# At this moment only debian
Linux)
adduser –shell /home/$RESTRICTED_USER/bin/rbash –disabled-password –no-create-home $RESTRICTED_USER
;;
esac

# Create shell script for restricted mode
cat >/home/$RESTRICTED_USER/bin/rbash <<EOF
#!/usr/bin/bash -e
export PATH=/home/$RESTRICTED_USER/bin
f=\$1
if [ «\$1» != «» ]; then
shift
exec /bin/bash \$f «\$*»
else
exec /bin/bash \$*
fi
EOF
chmod +x /home/$RESTRICTED_USER/bin/rbash

# Configure the commands
if [ «$USE_SUDO» == «yes» ]
# Sudoers
for i in $RESTRICTED_COMMANDS; do
[ «$sudocmd» ] || sudocmd=«NOPASSWD:$i» && sudocmd=«$sudocmd,NOPASSWD:$i»
done
sudocmd=«$RESTRICTED_USER ALL=($DEST_USER) $sudocmd»
echo «Add this line to /etc/sudoers: ‘$sudocmd'»

for i in $RESTRICTED_COMMANDS; do
cmdfile=$(basename $i)
cat > /home/$RESTRICTED_USER/bin/$cmdfile <<EOF
#!/bin/sh
exec sudo -u $DEST_USER $i \$@
EOF
chmod +x /home/$RESTRICTED_USER/bin/$cmdfile
done

else
# Link commands
ln -sf $RESTRICTED_COMMANDS /home/$RESTRICTED_USER/bin/
fi

Optionally, in origin server, we create a key and the adapters commands. We can create a common script and link to it the other commands.

# Create key
ssh-keygen -i rsa_id

# Define commands
cat > .$RESTRICTED_USER.$REMOTE_HOST.cmd <<EOF
#!/bin/sh
ssh -T -o IdentitiesOnly yes -o StrictHostKeyChecking=no -i id_rsa \
    $RESTRICTED_USER@$REMOTE_HOST \$(basename \$0) \$@
EOF
for i in $RESTRICTED_COMMANDS; do
    cmdfile=$(basename $i)
    ln -s .$RESTRICTED_USER.$REMOTE_HOST.cmd $cmdfile
done

Finally we add the public key in destination server

mkdir /home/$RESTRICTED_USER/.ssh
cat > /home/$RESTRICTED_USER/.ssh/authorized_keys <<EOF
<here goes your public key id_rsa.pub>
EOF
chown -R $RESTRICTED_USER /home/$RESTRICTED_USER/.ssh

Easy, isn’t it?

I want to use SSH to remotelly monitor some hosts. The problem with ssh is the overhead related to the creation of new connections.

But we can use the functionality of Control Master from OpenSSH (seehttp://www.revsys.com/writings/quicktips/ssh-faster-connections.html). Using it, ssh will connect only once reusing the connection.

This is great for monitoring scripts.

To use Control Master, you have to execute something like:

ssh -o "ControlMaster=yes" -o "ControlPath=/somepath/ssh-%r@%h:%p" -N user@host

The idea: create a remote user in each monitored host, stablish persistent ssh connection and use Control Master for the monitoring scripts. To deamonize and control the ssh master connections, I will use runit

(más…)

Los usuarios-administradores de servicios que corren en mi máquina muchas veces tienen que ejecutar programas gráficos. Por supuesto, les tengo prohibido entrar con usuarios de sistema o servicios, y les obligo a usar sudo para convertirse en el usuario de turno.

Para simplificarles la vida, he hecho este script que propaga las credenciales X11, a un usuario destino usando sudo.

De esta forma podemos entrar en una máquina con nuestro usuario corporativo con las X11 activas (p.ej. con Xming) y poder usar el sistema gráfico con un usuario de sistema, como oracle o was.

En inglés: Script to propagate xauth (x11) credentials to other user using sudo.

El script:

Para eso sólo hay que ejecutar:

./xauth-propagate-to-user.sh <usuario>

Por ejemplo:

$ ./xauth-propagate-to-user.sh pepito
Testing the display 'localhost:17.0'. Close the graphical program 'xclock' when displayed
(...)
Exporting dcdcorejees1/unix:12 to user pepito.
myuser's password for sudo: *****
WARNING, sudo does not propagate the $DISPLAY variable. It must be set manually:
 'sudo -H -u pepito DISPLAY=localhost:17.0 <command>'
Testing the display 'localhost:17.0' for user 'pepito'. Close the graphical program 'xclock' when displayed
(...)
It works!!!
To execute any command as 'pepito', use this command line:
 'sudo -H -u pepito DISPLAY=localhost:17.0 <command> [<args>]'

So. to work with a shell with 'pepito', execute this command:'
 'sudo -H -u pepito DISPLAY=localhost:17.0 sh'

Luego, durante esa sesión, podremos convertirnos al usuario de turno y ejecutar comandos que requieran entorno gráfico.

IMPORTANTE: en el sudo debe indicarse la opción –H, para que establezca el $HOME al del usuario destino.