Posts etiquetados ‘bash’

Hace un porrón de años escribí esto… creo que aún estaba en el instituto :)

Básicamente funciona así (se ve mal por culpa de wordpress que quita los espacios… paso de rayarme):

$ fortune | ./
/  \\                                                                       \ \
\__/|       Many a writer seems to think he is never profound except         |/
 __ |       when he can't understand his own meaning.                        |
/  \|       -- George D. Prentice                                            |\
\__//                                                                        //
# Poner en el cron:
# 33 *     * * *     root   (cat /etc/motd_base ; /usr/games/fortune | /usr/local/bin/ > /etc/motd; chmod 644 /etc/motd

fmt -w 60 | (
read a;
read b;
read c;

cat << "TOP"
/  \\                                                                       \ \

printf "\\__/|       %-65s|/\n" "$a"
read c;

while read c; do
	printf "    |       %-65s|\n" "$a";

printf " __ |       %-65s|\n" "$a";
printf "/  \\|       %-65s|\\ \n" "$b";

cat << "BOTTON"
\__//                                                                        //


How to define “hotkeys” in bash

Publicado: septiembre 20, 2010 en fast-tip, linux/unix, sysadmin, trick
Etiquetas:, , ,

For instance, I will define a hotkey to get manual page of current command without execute it (ideal for F1).

First, you get the code of the “hotkey” you want to use by pressing “Ctrl+U+<hotkey>”. For example:

* Ctrl+L: ^L
* Ctrl+J: ^J
* F1: ^[OP

This code may vary from terminal to terminal.

First you define an function, called single-man, to execute man of the first argument:

single-man() { man $1; }

Then, you add a line like this one in your .inputrc:

 "^[OP" "\C-A\C-K single-man \C-Y\C-M\C-Y"

What the hell does this? Well, when “F1” is pressed, in will simulate the press of “Ctrl+A”, that goes to the begining of the line, “Ctrl+K” that copies current line to clipboard, “Ctrl+Y” that pastes the clipboard, “Ctrl+M” that press Enter and Ctrl+Y that pastes the clipboard one more time.

I use this trick since several years ago.

BSoD for linux/unix/console

Publicado: junio 7, 2010 en fast-tip, humor, Personal, script
Etiquetas:, , ,

I do not remember where I got this, but it is fun. I will put it in the motd of my hosts on April Fools’ day.

This script will display on a console a windows like BSoD (Blue Script of Day):

                                    Linux ws         An exception 0E has occurred at 0028:C0018DBA in VxD IFSMGR(01) +        0000340A.  This was called from 0028:C0034118 in VxD NDIS(01) +        00000D7C.  It may be possible to continue normally.         *  Press any key to attempt to continue        *  Press CTRL+ALT+DEL to restart your computer. You will           lose any unsaved information in all applications                             Press Any key to continue. (más…)

AIX LDAP integration is not up to expectations. Its cache daemon, secldapclntd,
has a lot of problems:it often crashes, queries are slow, etc…

To mitigate problems, one workaround could be create the most important users locally,
using the KRB5files repository.

With this idea, this script will query a set of given groups from the AIX LDAP
registry using the AIX command line tools (lsuser, lsgroup), and it will create
them locally (mkgroup, mkuser).

To make it work, the host must be integrated with remote repository and must be able to resolve users and groups with LDAP method. You need LDAP method and KRB5files method configured. It can be easily changed to use other methods.

This script also supports nested groups from Active Directory.

I am playing with git and github. I think that I will upload to this repository ( 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.


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
# User restricted and commands to link or sudo
# Remote host where execute commands
# final user to execute commands (sudo)
# ---------------------------------------------------

case `uname` in
# 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
# At this moment only debian
adduser –shell /home/$RESTRICTED_USER/bin/rbash –disabled-password –no-create-home $RESTRICTED_USER

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

# Configure the commands
if [ “$USE_SUDO” == “yes” ]
# Sudoers
[ “$sudocmd” ] || sudocmd=“NOPASSWD:$i” && sudocmd=“$sudocmd,NOPASSWD:$i”
sudocmd=“$RESTRICTED_USER ALL=($DEST_USER) $sudocmd”
echo “Add this line to /etc/sudoers: ‘$sudocmd'”

cmdfile=$(basename $i)
cat > /home/$RESTRICTED_USER/bin/$cmdfile <<EOF
exec sudo -u $DEST_USER $i \$@
chmod +x /home/$RESTRICTED_USER/bin/$cmdfile

# Link commands

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
ssh -T -o IdentitiesOnly yes -o StrictHostKeyChecking=no -i id_rsa \
    $RESTRICTED_USER@$REMOTE_HOST \$(basename \$0) \$@
    cmdfile=$(basename $i)
    ln -s .$RESTRICTED_USER.$REMOTE_HOST.cmd $cmdfile

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>

Easy, isn’t it?

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:

./ <usuario>

Por ejemplo:

$ ./ 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.