Archivos de la categoría ‘fast-tip’

I never liked have to install agents for different tasks like Backups or monitoring. I think that is always enough with SSH. In this post I will introduce some concepts that I am using as an alternative to the NRPE for nagios.

Time ago I explained how to setup SSH for remote monitor servers in Nagios, using the ControlMaster feature to reuse the connection.

In that post I was using runit to keep the connections alive.

But in OpenSSH 5.6 a new feature has been released:

* Added a ControlPersist option to ssh_config(5) that automatically
starts a background ssh(1) multiplex master when connecting. This
connection can stay alive indefinitely, or can be set to
automatically close after a user-specified duration of inactivity.

And this is COOL! We can just use some options in the check_by_ssh plugin to automatically create the session. The options are:

  • -i /etc/nagios/nagiosssh.id_rsa: Private ssh key generated with ssh-keygen.
  • -o ControlMaster=auto: Create the control master socket automatically
  • -o ControlPersist=yes: Enable Control persist. It will spam a ssh process in background that will keep the connection (can be stopped with -O exit)
  • -o ControlPath=/var/run/nagiosssh/$HOSTNAME$: Path to the control socket. We can create a dir in /var/run/nagiosssh.
  • -l nagiosssh -H $HOSTNAME$: User and host were we are connecting.

So, the command definition can be:


define command{
command_name    check_users_ssh
command_line    $USER1$/check_by_ssh \
-o ControlMaster=auto \
-o ControlPath=/var/run/nagios/$HOSTNAME$ \
-o ControlPersist=yes \
-i $USER6$ -H $HOSTADDRESS$ -l $USER5$ \
'check_users -w $ARG1$ -c $ARG2$'
}

Note: You have to define the USER variables in resources.cfg.

Then we only need to create the proper user in the remote host. To improve the security, you can:

  • Use bash in restricted mode:
    1. Create the user ‘nagiosssh’ with shell=/home/nagiosssh/rbash
    2. Create a script /home/nagiosssh/rbash:
      #!/bin/sh
      # Restricted shell for the client.
      # Sets the path to checks
      PATH=/home/icingassh/checks exec /bin/bash --restricted "$@"
    3. Create the directory /home/icingassh/checks  and link here all the desired checks.
  • Restrict the ssh connection setting options in .ssh/authorized_keys. For example:

    no-agent-forwarding,no-port-forwarding,no-pty,no-X11-forwarding,from="10.10.10.10" ssh-rsa AAAAB3NzaC1...

Maybe in some days I upload a chef recipe to setup this.

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

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

cat << "TOP"
 __,-----------------------------------------------------------------------,__
/  \\                                                                       \ \
TOP

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

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

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

cat << "BOTTON"
\__//                                                                        //
   `------------------------------------------------------------------------``
BOTTON

)

Based to this post, http://linux-tips.org/article/78/syntax-highlighting-in-less my fast tip to allow syntax highlight in less:

cat <<EOF >> ~/.bash_profile

# Syntax Highlight for less
#
# Check if source highlite is intalled http://www.gnu.org/software/src-highlite/
# Set SRC_HILITE_LESSPIPE for custom location
# 
# To install: 
#   sudo yum install source-highlight
#
SRC_HILITE_LESSPIPE=${SRC_HILITE_LESSPIPE:-$(which src-hilite-lesspipe.sh 2> /dev/null)}
if [ -x "$SRC_HILITE_LESSPIPE" ]; then
	export LESSOPEN="| $SRC_HILITE_LESSPIPE  %s"
	export LESS="${LESS/ -R/}  -R" # Set LESS option in raw mode (avoid repeating it)
fi
EOF

In this case I needed to patch lftp.

First we set the configuration to support the overlay path (This is done once)


export PORTDIR_OVERLAY="$EPREFIX/usr/local/portage"
cat <<EOF >>$EPREFIX/etc/make.conf
# Overlay
PORTDIR_OVERLAY="$PORTDIR_OVERLAY"
EOF

And then, for any package, we just have to copy the ebuild and its files, and add the new patch (copying the file and updating the ebuild):


# To create a overlay version of any package, just change this variables
pkg=net-ftp/lftp
pkgvers=lftp-4.3.1

# Copy the ebuild
mkdir -p $PORTDIR_OVERLAY/$pkg
cp $EPREFIX/usr/portage/$pkg/$pkgvers.ebuild  $PORTDIR_OVERLAY/$pkg
cp -R $EPREFIX/usr/portage/$pkg/files   $PORTDIR_OVERLAY/$pkg/files

# Do any change.
# e.p. a Simple modification: add patches and add them to the ebuild:
#  cp lftp-solaris-2.10-socket.patch $PORTDIR_OVERLAY/$pkg/files/lftp-solaris-2.10-socket.patch
#  joe $EPREFIX/usr/portage/$pkg/$pkgvers.ebuild
#    +> Add to src_prepare(): epatch "${FILESDIR}/${PN}-solaris-2.10-socket.patch"

# Sign the ebuild
ebuild $PORTDIR_OVERLAY/$pkg/$pkgvers.ebuild digest

If you are behind a proxy that allows HTTPS connections, you can use github via SSH without problems. To do so, you have to use the great tool connect.c ( http://bent.latency.net/bent/git/goto-san-connect-1.85/src/connect.html). As described in its homepage, this program tunnels a connection using a proxy, to allow SSH to connect to servers using a proxy.

You can configure connect as the ProxyCommand for ssh.github.com and github.com hosts in ~/.ssh/config. You can also set the Port to 443 aswell.

Basicly the process will be:

export PROXY=proxy:80

http_proxy=http://$PROXY wget http://www.taiyo.co.jp/~gotoh/ssh/connect.c -O /tmp/connect.c
gcc /tmp/connect.c -o ~/bin/connect 

cat >> ~/.ssh/config  <<EOF

Host ssh.github.com github.com
  Port 443
  HostName ssh.github.com
  IdentityFile $HOME/.ssh/id_rsa
  ProxyCommand $HOME/bin/connect -H proxy:80 %h %p

EOF

And ready!!

git clone git@github.com:keymon/facter.git facter

Easy, isn’t it?

Check connect.c documentation if you need to use an authenticated user in proxy.

When you create a “Virtual Target Disk” or VTD on a VIOS, there is not documented way to define or change the LUN number that it shows to the client partition. But there are situation where you might need to update it:
  1. In a dual VIOS environment, to have the same LUNs in both clients (easier to administrate)-
  2. In a redudant configuration, when you need to start lpars on different hardware, using SAN disks. For instance, we use this configuration for our Backup datacenter where we have al the SAN disks mirrored.

In this post I comment how to update this LUN. The idea is basicly:

  • Set the VTD device to Defined in the VIOS
  • Update the ODM database. You have to update the attribute ‘LogicalUnitAddr’ in ObjectClass ‘CuAt’
  • Perform a ‘cfgmgr’ on the virtual host adapter (vhostX). This will enable the VTD device and reload the LUN number. Perform an cfgmgr on the VTD device does not work.

So, with commands:

$ oem_setup_env
# bash

# lsmap -vadapter vhost21
SVSA            Physloc                                      Client Partition ID
--------------- -------------------------------------------- ------------------
vhost21         U9117.MMA.XXXXXXX-V2-C34                     0x00000016

VTD                   host01v01
Status                Available
LUN                   0x8200000000000000
Backing device        hdiskpower0
Physloc               U789D.001.BBBBBBB-P1-C3-T2-L75

# ioscli mkvdev -vadapter vhost21 -dev host01v99 -vdev hdiskpower1
cfgmgr -l vhost21

# lsmap -vadapter vhost21
SVSA            Physloc                                      Client Partition ID
--------------- -------------------------------------------- ------------------
vhost21         U9117.MMA.XXXXXXX-V2-C34                     0x00000016

VTD                   host01v01
Status                Available
LUN                   0x8200000000000000
Backing device        hdiskpower0
Physloc               U789D.001.JJJJJJJ-P1-C3-T2-L75

VTD                   host01v99
Status                Available
LUN                   0x8300000000000000
Backing device        hdiskpower1
Physloc               U789D.001.JJJJJJJ-P1-C3-T2-L77

# rmdev -l host01v99
host01v99 Defined

# odmget -q "name=host01v99 and attribute=LogicalUnitAddr"  CuAt
CuAt:
  name = "host01v99"
  attribute = "LogicalUnitAddr"
  value = "0x8300000000000000"
  type = "R"
  generic = "D"
  rep = "n"
  nls_index = 6

# odmchange -o CuAt -q "name = host01v99 and attribute = LogicalUnitAddr" <<"EOF"
CuAt:
  name = "host01v99"
  attribute = "LogicalUnitAddr"
  value = "0x8100000000000000"
  type = "R"
  generic = "D"
  rep = "n"
  nls_index = 6
EOF

# odmget -q "name=host01v99 and attribute=LogicalUnitAddr"  CuAt
CuAt:
  name = "host01v99"
  attribute = "LogicalUnitAddr"
  value = "0x8100000000000000"
  type = "R"
  generic = "D"
  rep = "n"
  nls_index = 6

# cfgmgr -l vhost21
# lsmap -vadapter vhost21
SVSA            Physloc                                      Client Partition ID
--------------- -------------------------------------------- ------------------
vhost21         U9117.MMA.XXXXXXX-V2-C34                     0x00000016

VTD                   host01v01
Status                Available
LUN                   0x8200000000000000
Backing device        hdiskpower0
Physloc               U789D.001.JJJJJJJ-P1-C3-T2-L75

VTD                   host01v99
Status                Available
LUN                   0x8100000000000000
Backing device        hdiskpower1
Physloc               U789D.001.JJJJJJJ-P1-C3-T2-L77

In the client partition, you can scan for the new disk, and it will have the LUN 0x81:

root@host01:~/# cfgmgr -l vio0
root@host01:~/# lscfg -vl hdisk5
  hdisk5           U9117.MMA.XXXXXXX-V22-C3-T1-L8100000000000000  Virtual SCSI Disk Drive

Note: Actually I changed the output of these commands to remove information of my company.

Update: I created an script to do this: change_vtd_lun.sh

Redescubriendo reStructuredText

Publicado: noviembre 2, 2010 en fast-tip, Misc, Technical
Etiquetas:, , ,

reStructuredText

Estoy “redescubriendo” el reStructuredText (también conocido como rst o ReST).

Se trata de un lenguaje de markut (como HTML o SGML) pero human friendly. Similar al lenguaje de los wikis. Consulta la pagina de reStructuredText en la wikipedia para más detalles.

Parece tonto, pero la verdad es que se puede usar para muchas cosas, como lenguaje franco para textos con formato simple: Documentación, sistema de ticketing, manuales…

Pero se puede ir más lejos:

Y aquí vemos cómo generé este post (sin esta parte, para no hacer un post recursivamente infinito :)):

    cat <<EOF | ./rst2wp
    reStructuredText
    ----------------

    Estoy *"redescubriendo"* el reStructuredText_ (también conocido como *rst* o *ReST*).

    Se trata de un lenguaje de markut (como HTML o SGML) pero *human friendly*. Similar al lenguaje de los wikis. Consulta `la pagina de reStructuredText en la wikipedia <http://en.wikipedia.org/wiki/ReStructuredText>`_ para más detalles.

    Parece tonto, pero la verdad es que se puede usar para muchas cosas, como *lenguaje franco* para textos con formato simple: Documentación, sistema de ticketing, manuales...

    Pero se puede ir más lejos:

    - entradas en blog (este post está echo con ReST), usando `este pequeño script en python <http://unmaintainable.wordpress.com/2008/03/22/using-rst-with-wordpress/>`_...

    Si vamos más lejos, `hay quien usa un gestor de versiones junto este script <http://tadhg.com/wp/2009/07/14/blog-workflow-with-restructuredtext/>`_ !. Esto hace rondar una idea por la cabeza... ¿no molaría disponer de un blog en el que pudieras gestionar directamente con git?

    - O incluso presentaciones!, como comentan en esta página del propio docutils:

    * Original en Rest: http://docutils.sourceforge.net/docs/user/slide-shows.txt

    * En HTML normal: http://docutils.sourceforge.net/docs/user/slide-shows.txt

    * Como presentación en `S5 <http://meyerweb.com/eric/tools/s5/>`_: http://docutils.sourceforge.net/docs/user/slide-shows.s5.html::

Y aquí vemos cómo generé este post (sin esta parte, para no hacer un post recursivamente infinito :))::

     cat <<EOF | ./rst2wp
    EOF


I am a Google reader user, and I never find the “Share in google reader” icon . I wanted to add it to my blog, but I did not find this anywhere… so I will post that. It is quite easy: go to your site preferences, options, sharing settings and click in “Add a new service”.

You have  to fill the new formulary with:

And you now can use it…

The same for other platforms

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.

Hoy he perdido algo de tiempo con una soberana tonteria: Creé un script para ejecutar en el /etc/cron.daily llamado “script.sh”… y nunca se ejecutaba. Revisé todo arriba y abajo, y finalmente ejecuté:

run-parts --report -v  --test /etc/cron.daily

y no salí el script… ¿que era? al final se me ocurrió quitarle el ‘.sh’ del final… y voilá.

Y la cosa no acabó ahí. Otra definición en /etc/cron.d/zabbix.cron no cargaba… el mismo problema, sobraba el ‘.’.

En fins…