Sunday, May 01, 2016

Lifesaver Snippets

Universal JDBC CLI Client

I work on the Unix/Linux boxes running Java application servers regularly. One of the problems I always face is that access to the server is restricted, yet occasionally I have the need to access the most protected resources of all - the database. Without direct access to the database server, all my GUI database client tools are useless. What is available to me is only the JVM in an SSH session.

I find that, while I can't install any database tools on the servers without going through a lot of bureaucratic red tapes, I can usually make use of what is already available on the server to do my work. With only h2, the JDBC driver and some shell script, I am able to connect to the database and get the data I want. Here's how.

First, put all the jar files into the same folder. You should at least have h2 and the JDBC driver in the folder. Create a script h2shell:

#!/bin/bash

CP=.
for j in *.jar; do
  CP=$CP:$j
done

java -Xmx512m -classpath $CP org.h2.tools.Shell "$@"

Make the script executable:

chmod +x h2shell

Next, create a helper script with the database connection properties. Let's call the script mydb:

#!/bin/bash

./h2shell -url url -user username -password password

Make the script executable too:

chmod +x mydb

You can now connect to the DB by running mydb:

./mydb

telnet substitute

Due to the security policy of one of my clients, they remove the telnet program from all of their servers. telnet is one of common tools to test network connectivity. I found a crude alternative by writing some Python scripts.

import telnetlib

t = telnetlib.Telnet('some.host', port)
print t.read_eager()
t.write(message)
print t.read_all()
t.close()

Besides telnetlib, Python has a lot of other wonderful modules such as urllib, socket.