Archive for the 'Code' Category

Quick N Dirty way to Map Commands to remote servers via ssh

Saturday, October 10th, 2009

You may be running several independent but similar servers at the same time and wasting time by executing commands in all of them one by one.

Wouldn’t it be nice to send a command to all of them at once? or to monitor all of them at once.

The following script can be used as a building block to more complex automation tasks for a small size set of servers. (If you’re managing over 50 servers, I’d probably consider looking a different way to arrange servers (map/reduce cluster), but if you’re doing something below that number this might suffice)

#!/usr/bin/python                                                                                                                                                                                                                                                      

#########################################################
# Author: Angel Leon (gubatron@gmail.com) - October 2009
#
# Invokes a command locally and invokes the same command
# in all machines under the specified username, servers
#
# Requirement: Have a public ssh_key for that user on all
# the other machines so you don't have to authenticate
# on all the other machines.
#########################################################
import sys
import os

# set the username that has access to all the machines here
user='safeuser'

# add all your server names here
servers=['server1.mydomain.com','server2.mydomain.com','server3.mydomain.com']

if __name__ == "__main__":
  if len(sys.argv) < 2:
    print "Usage: ssh_map_command "
    sys.exit(0)

  cmd= ' '.join(sys.argv[1:])

  #Execute locally first
  print cmd
  os.system(cmd)

  #Execute for all the servers in the list
  for server in servers:
    remote_cmd="ssh %s@%s %s" % (user,server,cmd)
    print remote_cmd
    os.system(remote_cmd)
    print

Save as ssh_map_command and chmod +x it.

Sample uses
Check the average load of all machines at once (then use output to mitigate high load issues)

$ ssh_map_command uptime

Send HUP signal to all your web servers (put it in an alias or other script… and that’s how you start building more complex scripts)

$ ssh_map_command ps aux | grep [l]ighttpd | kill -HUP `awk {'print $2'}`

Check if processes are alive, check memory usage on processes across different machines, grep remote all logs at once, svn up on all machines, rsync from one to many, hey, you can even tail -f and grep all the logs at once, you can go nuts with this thing. Depends on what you need to do.

Requirements

Security Advisory
Make sure only the desired user has read/write/execute access to it and keep your private ssh keys safe (preferably only read and execute for the owner, and no permissions whatsoever to anybody else chmod 500 ssh_mod_map), if possible change them as often as possible, for it may become a big security whole if an attacker can manage to write code on this script, specially if you have cronjobs invoking it. Your attacker would only need to change code here to mess up all of your machines.

Disclaimer and Call for Knowledge
Please, if someone knows of a standard way to map commands to multiple servers, please let me know in the comment section, in my case I needed a solution and I wrote a quick and dirty python script and tried to secure it as best as I could, by no means I’m saying that this is the best solution to mapping commands, in fact I believe it might be the least efficient way, however it works good enough for my personal needs.

Post on Twitter
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Google Buzz (aka. Google Reader)

Ubuntu/Debian Quick Reference: How To Change Your Server’s UTC Timezone on the command line

Saturday, October 10th, 2009

Just Type…
sudo dpkg-reconfigure tzdata

…and follow the instructions on screen.

The process should look something like the following:


Select your Region


Select a city on your time zone


You’re done.

Tip
You can always check the status of your configuration using
sudo debconf-show tzdata

You could for example map that command via ssh to several machines and grep for “*”, that way you could easily spot servers with wrong timezones very quickly.

Post on Twitter
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Google Buzz (aka. Google Reader)

Check the Top 10 Linux Commands you can’t live without

Monday, September 28th, 2009

Type the following on your cmd line (or make into an alias)

cat ~/.bash_history | sort | uniq -c | sort -r | head

In my case they are (for this week)

ls
fg
svnSync (script I created)
stats_fetch; stats_display (other scripts)
cd
crontab -e
ps aux | grep
ssh_map_command (another script)
python
emacs -nw
Post on Twitter
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Google Buzz (aka. Google Reader)

HTML 5 is out and about

Saturday, July 11th, 2009

I believe that the <canvas>, <audio>and <video> tags will make the web a pretty exciting place. A lot of Flash components will be rewritten or converted into Javascript+HTML5 Object components making available more reusable elements for a graphical and interactive web, all being open sourced (javascript) and with no extra plugins needed.

Some places where we can already see (or will) the use of HTML 5 tags and javascript on those elements are:

  • GMail Mobile for iPhone and Android
  • Yahoo! Pipes
  • Bespin, a code editor created by Mozilla lab, they basically rewrote the text editing component using the canvas tag so that its a high performance text editing component, with a nice look, selection highlighting, new scrollbars, command support, it can be extended with your own commands (reminds me of emacs)
  • Google Waves
  • Some blogs that are already using the <article>, <nav>, <footer> and other new HTML 5 tags
  • YouTube is getting ready for the video tag
Post on Twitter
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Google Buzz (aka. Google Reader)

How to make a Quick & Dirty HexViewer – Updated

Monday, April 20th, 2009

After I received comments from ispak on Flickr I made a few fixes.

ispak pointed out that it was a bad idea reading one byte at the time, also I had a gay ass try/catch that didn’t catch any exception :p

So now I read 16 byte chunks, and I also take care of the file ending. The previous version used to print the file ending with a bunch of null bytes. Now it stops reading at the end, and formats the output accordingly.

Here’s the new source:

//HexViewer.java
import java.io.*;

public final class HexViewer {
    public final static void printFile(String filePath) {
        try {
            File f = new File(filePath);
            BufferedInputStream bis =
                new BufferedInputStream(new FileInputStream(f));

            byte[] chunk = null;
            int readStatus = 0;
            while (true) {
                chunk = new byte[16];
                readStatus = bis.read(chunk, 0, 16);
                char[] line = new char[16];

                if (readStatus == -1)
                    break;

                for (byte i=0; i < readStatus; i++) {
                    int readByte = (chunk[i] < 0) ? (-1 * (int) chunk[i]) : chunk[i];
                    String paddingZero = (readByte < 16) ? "0" : "";
                    System.out.print(paddingZero + Integer.toHexString(readByte).toUpperCase() + " ");
                    line[i] = (readByte >= 33 && readByte <= 126) ? (char) readByte : '.';
                }

                //We add some padding to print the text line right below the one above.
                String padding = new String();
                if (readStatus < 16) {
                    for (byte i=0; i < 16-readStatus; i++) {
                        padding += "   ";
                    }
                }

                System.out.println(padding + new String(line));
            }
        } catch (Exception e1) { e1.printStackTrace(); }
    }

    public final static void main(String[] args) {
        if (args.length == 0)
            return;

        printFile(args[0]);
    }
}

HexViewer - r2

And see how it now handles file endings when the file size is not a multiple of 16 :p

Picture 2

Post on Twitter
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Google Buzz (aka. Google Reader)

How to make your own Quick & Dirty Hex File Viewer in Java

Saturday, April 18th, 2009

Update: You might want to read this new version of the code instead. Thanks ispak

I was playing with a hex editor recently and then I thought it would be pretty easy to make a program to output what you see on a text editor. Here’s a quick & dirty Hex Visor I wrote in like 5 minutes with Java. It shows 15 bytes per line, and on the right side it prints all the visible characters of the ascii table, the non-visible ones are replaced with “.”

Enjoy:

//HexViewer.java
import java.io.*;

public final class HexViewer {
    public final static void printFile(String filePath) {
        File f;
        try {
            f = new File(filePath);
        } catch (Exception e) {
            return;
        }

        try {

            FileInputStream fis = new FileInputStream(f);
            while (fis.available() > 0) {
                char[] line = new char[16];
                for (int i=0; i < 16; i++) {
                    int readByte = fis.read();
                    String paddingZero = (readByte < 16) ? "0" : "";
                    System.out.print(paddingZero + Integer.toHexString(readByte) + " ");
                    line[i] = (readByte >= 33 && readByte <= 126) ? (char) readByte : '.';
                }
                System.out.println(new String(line));
            }
        } catch (Exception e1) { e1.printStackTrace(); }
    }

    public final static void main(String[] args) {
        if (args.length == 0)
            return;

        printFile(args[0]);
    }
}

Usage:

java HexViewer <path to file> | less

java HexViewer Desktop/Puppet.wmv | less

30 26 b2 75 8e 66 cf 11 a6 d9 00 aa 00 62 ce 6c 0&.u.f.......b.l
74 14 00 00 00 00 00 00 07 00 00 00 01 02 a1 dc t...............
ab 8c 47 a9 cf 11 8e e4 00 c0 0c 20 53 65 68 00 ..G.........Seh.
00 00 00 00 00 00 f4 10 68 f9 49 76 2e 43 b5 9f ........h.Iv.C..
09 0a 2d 19 45 7c 32 3a 24 00 00 00 00 00 70 ee ..-.E|2:$.....p.
14 06 fb da c7 01 28 01 00 00 00 00 00 00 00 8c ......(.........
bb 53 00 00 00 00 10 88 dd 52 00 00 00 00 b8 0b .S.......R......
00 00 00 00 00 00 02 00 00 00 40 1f 00 00 40 1f ..........@...@.
00 00 90 50 02 00 b5 03 bf 5f 2e a9 cf 11 8e e3 ...P....._......
00 c0 0c 20 53 65 61 10 00 00 00 00 00 00 11 d2 ....Sea.........
d3 ab ba a9 cf 11 8e e6 00 c0 0c 20 53 65 06 00 ............Se..
33 10 00 00 a9 46 43 7c e0 ef fc 4b b2 29 39 3e 3....FC|...K.)9>
de 41 5c 85 27 00 00 00 00 00 00 00 01 00 0c 65 .A\.'..........e
00 6e 00 2d 00 61 00 75 00 00 00 5d 8b f1 26 84 .n.-.a.u...]..&.
45 ec 47 9f 5f 0e 65 1f 04 52 c9 1a 00 00 00 00 E.G._.e..R......
00 00 00 02 01 ea cb f8 c5 af 5b 77 48 84 67 aa ..........[wH.g.
8c 44 fa 4c ca 62 01 00 00 00 00 00 00 06 00 00 .D.L.b..........
00 01 00 0c 00 02 00 02 00 00 00 49 00 73 00 56 ...........I.s.V
00 42 00 52 00 00 00 00 00 00 00 01 00 34 00 00 .B.R.........4..
00 06 00 00 00 44 00 65 00 76 00 69 00 63 00 65 .....D.e.v.i.c.e
00 43 00 6f 00 6e 00 66 00 6f 00 72 00 6d 00 61 .C.o.n.f.o.r.m.a
00 6e 00 63 00 65 00 54 00 65 00 6d 00 70 00 6c .n.c.e.T.e.m.p.l
00 61 00 74 00 65 00 00 00 4c 00 31 00 00 00 00 .a.t.e...L.1....
00 02 00 0c 00 02 00 02 00 00 00 49 00 73 00 56 ...........I.s.V
00 42 00 52 00 00 00 01 00 00 00 02 00 34 00 00 .B.R.........4..
00 0c 00 00 00 44 00 65 00 76 00 69 00 63 00 65 .....D.e.v.i.c.e
00 43 00 6f 00 6e 00 66 00 6f 00 72 00 6d 00 61 .C.o.n.f.o.r.m.a
00 6e 00 63 00 65 00 54 00 65 00 6d 00 70 00 6c .n.c.e.T.e.m.p.l
00 61 00 74 00 65 00 00 00 4d 00 50 00 40 00 4d .a.t.e...M.P.@.M
00 4c 00 00 00 00 00 01 00 2e 00 03 00 04 00 00 .L..............
00 57 00 4d 00 2f 00 57 00 4d 00 41 00 44 00 52 .W.M./.W.M.A.D.R
00 43 00 50 00 65 00 61 00 6b 00 52 00 65 00 66 .C.P.e.a.k.R.e.f
00 65 00 72 00 65 00 6e 00 63 00 65 00 00 00 a7 .e.r.e.n.c.e....
3f 00 00 00 00 01 00 34 00 03 00 04 00 00 00 57 ?......4.......W
00 4d 00 2f 00 57 00 4d 00 41 00 44 00 52 00 43 .M./.W.M.A.D.R.C
00 41 00 76 00 65 00 72 00 61 00 67 00 65 00 52 .A.v.e.r.a.g.e.R
00 65 00 66 00 65 00 72 00 65 00 6e 00 63 00 65 .e.f.e.r.e.n.c.e
00 00 00 b0 06 00 00 74 d4 06 18 df ca 09 45 a4 .......t......E.
ba 9a ab cb 96 aa e8 a4 0d 00 00 00 00 00 00 00 ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................

This how it looks on a full blown hex editor like HexEdit:
Same file on HexEdit

The Code of HexViewer.java on emacs:
HexViewer.java on emacs

Screenshot of the output:
HexViewer in action

Homework
Hack the code so that it ouputs the first column shown on the HexEdit screenshot. That column represents the byte position of each row. It's basically a counter incremented 16 units at the time, and shown in Hex.

Post on Twitter
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Google Buzz (aka. Google Reader)