October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories

October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Best SSH Commands / Tricks

 Best SSH Commands / Tricks

 

OpenSSH is a FREE version of the SSH connectivity tools that technical users of the Internet rely on. Users of telnet, rlogin, and ftp may not realize that their password is transmitted across the Internet unencrypted, but it is. OpenSSH encrypts all traffic (including passwords) to effectively eliminate eavesdropping, connection hijacking, and other attacks. The encryption that OpenSSH provides has been strong enough to earn the trust of Trend Micro and other providers of cloud computing.Additionally, OpenSSH provides secure tunneling capabilities and several authentication methods, and supports all SSH protocol versions.

1) Copy ssh keys to user@host to enable password-less ssh logins.

ssh-copy-id user@host

To generate the keys use the command ssh-keygen

2) Start a tunnel from some machine’s port 80 to your local post 2001

ssh -N -L2001:localhost:80 somemachine

Now you can acces the website by going to http://localhost:2001/

3) Output your microphone to a remote computer’s speaker

dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp

This will output the sound from your microphone port to the ssh target computer’s speaker port. The sound quality is very bad, so you will hear a lot of hissing.

4) Compare a remote file with a local file

ssh user@host cat /path/to/remotefile | diff /path/to/localfile –

Useful for checking if there are differences between local and remote files.

5) Mount folder/filesystem through SSH

sshfs name@server:/path/to/folder /path/to/mount/point

Install SSHFS from http://fuse.sourceforge.net/sshfs.html
Will allow you to mount a folder security over a network.

6) SSH connection through host in the middle

ssh -t reachable_host ssh unreachable_host

Unreachable_host is unavailable from local network, but it’s available from reachable_host’s network. This command creates a connection to unreachable_host through “hidden” connection to reachable_host.

7) Copy from host1 to host2, through your host
ssh root@host1 “cd /somedir/tocopy/ && tar -cf – .” | ssh root@host2 “cd /samedir/tocopyto/ && tar -xf -”

Good if only you have access to host1 and host2, but they have no access to your host (so ncat won’t work) and they have no direct access to each other.

8) Run any GUI program remotely

ssh -fX @

The SSH server configuration requires:

X11Forwarding yes # this is default in Debian

And it’s convenient too:

Compression delayed

9) Create a persistent connection to a machine

ssh -MNf @

Create a persistent SSH connection to the host in the background. Combine this with settings in your ~/.ssh/config:
Host host
ControlPath ~/.ssh/master-%r@%h:%p
ControlMaster no
All the SSH connections to the machine will then go through the persisten SSH socket. This is very useful if you are using SSH to synchronize files (using rsync/sftp/cvs/svn) on a regular basis because it won’t create a new socket each time to open an ssh connection.

10) Attach screen over ssh

ssh -t remote_host screen -r

Directly attach a remote screen session (saves a useless parent bash process)

11) Port Knocking!

knock 3000 4000 5000 && ssh -p user@host && knock 5000 4000 3000

Knock on ports to open a port to a service (ssh for example) and knock again to close the port. You have to install knockd.
See example config file below.
[options]
logfile = /var/log/knockd.log
[openSSH]
sequence = 3000,4000,5000
seq_timeout = 5
command = /sbin/iptables -A INPUT -i eth0 -s %IP% -p tcp –dport 22 -j ACCEPT
tcpflags = syn
[closeSSH]
sequence = 5000,4000,3000
seq_timeout = 5
command = /sbin/iptables -D INPUT -i eth0 -s %IP% -p tcp –dport 22 -j ACCEPT
tcpflags = syn

12) Remove a line in a text file. Useful to fix

ssh-keygen -R

In this case it’s better do to use the dedicated tool

13) Run complex remote shell cmds over ssh, without escaping quotes

ssh host -l user $(

Much simpler method. More portable version: ssh host -l user “cat cmd.txt

14) Copy a MySQL Database to a new Server via SSH with one command

mysqldump –add-drop-table –extended-insert –force –log-error=error.log -uUSER -pPASS OLD_DB_NAME | ssh -C user@newhost “mysql -uUSER -pPASS NEW_DB_NAME”

Dumps a MySQL database over a compressed SSH tunnel and uses it as input to mysql – i think that is the fastest and best way to migrate a DB to a new server!

15) Remove a line in a text file. Useful to fix “ssh host key change” warnings

sed -i 8d ~/.ssh/known_hosts

16) Copy your ssh public key to a server from a machine that doesn’t have ssh-copy-id

cat ~/.ssh/id_rsa.pub | ssh user@machine “mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys”

If you use Mac OS X or some other *nix variant that doesn’t come with ssh-copy-id, this one-liner will allow you to add your public key to a remote machine so you can subsequently ssh to that machine without a password.

17) Live ssh network throughput test

yes | pv | ssh $host “cat > /dev/null”

connects to host via ssh and displays the live transfer speed, directing all transferred data to /dev/null
needs pv installed
Debian: ‘apt-get install pv’
Fedora: ‘yum install pv’ (may need the ‘extras’ repository enabled)

18) How to establish a remote Gnu screen session that you can re-connect to

ssh -t user@some.domain.com /usr/bin/screen -xRR

Long before tabbed terminals existed, people have been using Gnu screen to open many shells in a single text terminal. Combined with ssh, it gives you the ability to have many open shells with a single remote connection using the above options. If you detach with “Ctrl-a d” or if the ssh session is accidentally terminated, all processes running in your remote shells remain undisturbed, ready for you to reconnect. Other useful screen commands are “Ctrl-a c” (open new shell) and “Ctrl-a a” (alternate between shells). Read this quick reference for more screen commands: http://aperiodic.net/screen/quick_reference

19) Resume scp of a big file

rsync –partial –progress –rsh=ssh $file_source $user@$host:$destination_file

It can resume a failed secure copy ( usefull when you transfer big files like db dumps through vpn ) using rsync.
It requires rsync installed in both hosts.
rsync –partial –progress –rsh=ssh $file_source $user@$host:$destination_file local -> remote
or
rsync –partial –progress –rsh=ssh $user@$host:$remote_file $destination_file remote -> local

20) Analyze traffic remotely over ssh w/ wireshark

ssh root@server.com ‘tshark -f “port !22? -w -’ | wireshark -k -i –

This captures traffic on a remote machine with tshark, sends the raw pcap data over the ssh link, and displays it in wireshark. Hitting ctrl+C will stop the capture and unfortunately close your wireshark window. This can be worked-around by passing -c # to tshark to only capture a certain # of packets, or redirecting the data through a named pipe rather than piping directly from ssh to wireshark. I recommend filtering as much as you can in the tshark command to conserve bandwidth. tshark can be replaced with tcpdump thusly:
ssh root@example.com tcpdump -w – ‘port !22? | wireshark -k -i –

21) Have an ssh session open forever

autossh -M50000 -t server.example.com ‘screen -raAd mysession’

Open a ssh session opened forever, great on laptops losing Internet connectivity when switching WIFI spots.

22) Harder, Faster, Stronger SSH clients

ssh -4 -C -c blowfish-cbc

We force IPv4, compress the stream, specify the cypher stream to be Blowfish. I suppose you could use aes256-ctr as well for cypher spec. I’m of course leaving out things like master control sessions and such as that may not be available on your shell although that would speed things up as well.

23) Throttle bandwidth with cstream

tar -cj /backup | cstream -t 777k | ssh host ‘tar -xj -C /backup’

this bzips a folder and transfers it over the network to “host” at 777k bit/s.
cstream can do a lot more, have a look http://www.cons.org/cracauer/cstream.html#usage
for example:
echo w00t, i’m 733+ | cstream -b1 -t2

24) Transfer SSH public key to another machine in one step

ssh-keygen; ssh-copy-id user@host; ssh user@host

This command sequence allows simple setup of (gasp!) password-less SSH logins. Be careful, as if you already have an SSH keypair in your ~/.ssh directory on the local machine, there is a possibility ssh-keygen may overwrite them. ssh-copy-id copies the public key to the remote host and appends it to the remote account’s ~/.ssh/authorized_keys file. When trying ssh, if you used no passphrase for your key, the remote shell appears soon after invoking ssh user@host.

25) Copy stdin to your X11 buffer

ssh user@host cat /path/to/some/file | xclip

Have you ever had to scp a file to your work machine in order to copy its contents to a mail? xclip can help you with that. It copies its stdin to the X11 buffer, so all you have to do is middle-click to paste the content of that looong file :)

Have Fun

Please comment if you have any other good SSH Commands OR Tricks.

Password Protect any WebApp folder in Tomcat-6.x

The following steps were tested with Tomcat 6.0.29. I think they should work with all currently running Tomcat versions out there. If it didn’t work out for your version, please let me know. Okay so lets start: First of all, we need to enable the MemoryRealm. You can do so by adding this line to the server.xml file inside your tomcats conf directory.
<Realm className="org.apache.catalina.realm.MemoryRealm" />

If you wonder what you’re activating here, please read the Catalina doc:

http://tomcat.apache.org/tomcat-4.0-doc/catalina/docs/api/org/apache/catalina/realm/MemoryRealm.html

Then, you want to add a user and a role for your webapp inside the tomcat-users.xml file, which can be found in the same directory.

<role rolename="myrole"/>
<user username="myuser" password="mypassword" roles="myrole"/>

If you would like to share your users over multiple webapps, you might want to create one role per webapp and add these roles to the corresponding users. Multiple roles are being defined by simply writing them all inside the roles attribute, separated by a ‘,’.

The next step will be to add the login information inside the webapp you want to protect. Open your webapp’s web.xml file. If the webapp was already deployed, please keep in mind that a redeploy might invalidate or overwrite the settings you’re about to set. So here we go; Write the following lines in your web.xml (located inside the web-app element).

<security-constraint>
  <web-resource-collection>
    <web-resource-name>mywebapp</web-resource-name>
    <url-pattern>/*</url-pattern>
  </web-resource-collection>
  <auth-constraint>
    <role-name>myrole</role-name>
  </auth-constraint>
</security-constraint>

<login-config>
  <auth-method>BASIC</auth-method>
  <realm-name>mywebapp</realm-name>
</login-config>

Make sure that the role-name attribute fits the one you picked in the tomcat-users.xml file. You might also only protect the nasty parts of your application using the URL pattern. However using ‘/*’, the mechanism will protect the whole web application. The basic auth-method is just the simple base64 encoded user:password in the http request header stuff. If you want a more decent solution, read this page for more available auth methods:

Integrating Tomcat and Apache on Red Hat Linux

Referance:  http://www.meritonlinesystems.com/docs/apache_tomcat_redhat.html

1.0 Introduction

Java servlets are a powerful tool for building websites and web based applications. One skill that every Java web developer should have is the ability to install and configure the Tomcat servlet engine. Many thanks to the Apache Software Foundation for providing this mature, stable, open source software. It was recently voted the Best Application Server of 2003 by InfoWorld readers.

This article discusses how to integrate Tomcat with the Apache web server on Red Hat Linux 9 or Red Hat Enterprise Linux 3. The goal is to provide a simple, stable configuration that will allow users to gain confidence using Tomcat in a development environment. Setting up a production Tomcat server is outside the scope of this article.

Please note the following conventions:

  • All commands are issued as root unless otherwise noted.
  • {YOUR_DOMAIN} and {YOUR_APPLICATION} are placeholder values that should be customized to your setup. For example, {YOUR_DOMAIN} might be “localhost.test” and {YOUR_APPLICATION} might be “test”.

2.0 Installing Apache

I chose to install Apache using the Red Hat RPM. Using the RPM instead of compiling Apache from source simplifies system administration in the following ways:

  • Updates and bug fixes can be installed automatically from the Red Hat Network.
  • Startup and shutdown scripts are already configured and available.

I recommend using the Red Hat up2date command line utility to install Red Hat RPMs. It eliminates a multitude of headaches by ensuring the software you install is the correct version and you have the right dependencies installed on your system.

Install the following Red Hat RPMs if they are not already installed:

  • httpd: the Apache web server
  • httpd-devel: development tools that will be needed to create the mod_jk connector

To install these packages using up2date, make sure you are connected to the Internet, and enter the following:

 

up2date -i httpd httpd-devel

You should now be able to start/stop/restart Apache as follows:

 

service httpd start
service httpd stop
service httpd restart

Verify that Apache is working by starting Apache and typing http://localhost/ into your browser. You should see the default Apache install page with links to documentation.

3.0 Installing Tomcat

The only requirements to run Tomcat are that a Java Development Kit (JDK), also called a Java Software Development Kit (SDK), be installed and the JAVA_HOME environment variable be set.

3.1 Java SDK

I chose to install Sun’s Java 2 Platform, Standard Edition, which can be downloaded from http://java.sun.com/j2se/). I chose the J2SE v1.4.2 SDK Linux self-extracting binary file.

Change to the directory where you downloaded the SDK and make the self-extracting binary executable:

 

chmod +x j2sdk-1_4_2-linux-i586.bin

Run the self-extracting binary:

 

./j2sdk-1_4_2-linux-i586.bin

There should now be a directory called j2sdk1.4.2 in the download directory. Move the SDK directory to where you want it to be installed. I chose to install it in /usr/java. Create /usr/java if it doesn’t exist. Here is the command I used from inside the download directory:

 

mv j2sdk1.4.2 /usr/java

Set the JAVA_HOME environment variable, by modifying /etc/profile so it includes the following:

 

JAVA_HOME="/usr/java/j2sdk1.4.2"
export JAVA_HOME

/etc/profile is run at startup and when a user logs into the system, so you will need to log out and log back in for JAVA_HOME to be defined.

 

exit
su -

Check to make sure JAVA_HOME is defined correctly using the command below. You should see the path to your Java SDK.

 

echo $JAVA_HOME

3.2 Tomcat Account

You will install and configure Tomcat as root; however, you should create a dedicated group and user account for Tomcat to run under as follows:

 

groupadd tomcat
useradd -g tomcat tomcat

3.3 Download Tomcat

Download the latest release binary build from http://www.apache.org/dist/jakarta/tomcat-5/. Since Tomcat runs directly on top of a standard JDK, I cannot think of any reason to building it from source. There are a number of different download formats. I chose the gnu zipped tar file (jakarta-tomcat-5.0.28.tar.gz).

3.4 Tomcat Standalone

Unzip Tomcat by issuing the following command from your download directory:

 

tar xvzf jakarta-tomcat-5.0.28.tar.gz

This will create a directory called jakarta-tomcat-5.0.28. Move this directory to wherever you would like to install Tomcat. I chose /usr/local. Here is the command I issued from inside the download directory:

 

mv jakarta-tomcat-5.0.28 /usr/local/

The directory where Tomcat is installed is referred to as CATALINA_HOME in the Tomcat documentation. In this installation CATALINA_HOME=/usr/local/jakarta-tomcat-5.0.28.

I recommend setting up a symbolic link to point to your current Tomcat version. This will save you from having to make changes to startup and shutdown scripts each time you upgrade Tomcat. It also allows you to keep several versions of Tomcat on your system and easily switch amongst them. Here is the command I issued from inside /usr/local to create a symbolic link called /usr/local/jakarta-tomcat that points to /usr/local/jakarta-tomcat-5.0.28:

 

ln -s jakarta-tomcat-5.0.28 jakarta-tomcat

Change the group and owner of the /usr/local/jakarta-tomcat and /usr/local/jakarta-tomcat-5.0.28 directories to tomcat:

 

chown tomcat.tomcat /usr/local/jakarta-tomcat
chown -R tomcat.tomcat /usr/local/jakarta-tomcat-5.0.28

It is not necessary to set the CATALINA_HOME environment variable. Tomcat is smart enough to figure out CATALINA_HOME on its own.

You should now be able to start and stop Tomcat from the CATALINA_HOME/bin directory by typing ./startup.sh and ./shutdown.sh respectively. Test that Tomcat is working by starting it and typing http://localhost:8080 into your browser. You should see the Tomcat welcome page with links to documentation and sample code. Verify Tomcat is working by running some of the examples.

4.0 Installing the Connector

4.1 Connector Benefits

At this point, Apache and Tomcat should be working separately in standalone mode. You can run Tomcat in standalone mode as an alternative to Apache. In fact, in some cases, it is said that Tomcat standalone is faster than serving static content from Apache and dynamic content from Tomcat. However, there are the following compelling reasons to use Apache as the front end:

  1. You can use Apache to buffer slow connections. Tomcat uses java.io, which uses a thread for each request, so Tomcat can run out of connections as the number of slow requests grows. This could be an issue if your application supports a large number of dial-up users.
  2. You can use a connector such as mod_jk to load balance amongst several Tomcat instances.
  3. You can take advantage of Apache features such as cgi and PHP.
  4. You can take advantage of Apache modules such as mod_rewrite, mod_headers, and mod_expire.
  5. You can isolate virtual hosts in their own Tomcat instances.

The increased functionality obtained by using Apache on the front end can outweigh the effort required to install and configure a connector.

4.2 Selecting a Connector

Development on the mod_jk2 connector was discontinued on 11/15/2004; therefore, you no longer have to decide between the mod_jk and mod_jk2 connectors. Use the mod_jk connector. It has been around a long while and is very stable.

4.3 Building the mod_jk Connector

The mod_jk connector is the communication link between Apache and Tomcat. It listens on a defined port for requests from Apache and forwards those requests to Tomcat.

Install the following Red Hat RPMs if they are not already installed:

  • libtool
  • automake
  • autoconf

Download the jk connector source from http://www.apache.org/dist/jakarta/tomcat-connectors/jk/. I used jakarta-tomcat-connectors-1.2.8-src.tar.gz.

Unzip the contents of the file into your download directory as follows:

 

tar xvzf jakarta-tomcat-connectors-1.2.8-src.tar.gz

This will create a folder called jakarta-tomcat-connectors-1.2.8-src. Move this folder to wherever you store source files on your system. I chose /usr/src. Here is the command I issued from inside the download directory:

 

mv jakarta-tomcat-connectors-1.2.8-src /usr/src

I refer to the folder where the connector source is installed as CONN_SRC_HOME. In my case CONN_SRC_HOME = /usr/src/jakarta-tomcat-connectors-1.2.8-src.

Change to directory CONN_SRC_HOME/jk/native and run the buildconf.sh script as follows:

 

./buildconf.sh

This will create the CONN_SRC_HOME/jk/native/configure file. Run the configure script with the path to the apxs file on your system. If you installed Apache using the Red Hat RPM, apxs should be located at /usr/sbin/apxs.

 

./configure --with-apxs=/usr/sbin/apxs

Build mod_jk with the following command:

 

make

If you see missing object errors, try this alternate command:

 

make LIBTOOL=/etc/httpd/build/libtool

If all went well, the mod_jk.so file was successfully created. Manually copy it to Apache’s shared object files directory:

 

cp CONN_SRC_HOME/jk/native/apache-2.0/mod_jk.so /etc/httpd/modules

5.0 Creating the Application Directories

Both Apache and Tomcat application files will be installed under the /home/tomcat/webapps directory. This setup will allow you to easily upgrade Tomcat and back up your application files.

Create your application directories as follows:

 

mkdir /home/tomcat/webapps
mkdir /home/tomcat/webapps/{YOUR_DOMAIN}
mkdir /home/tomcat/webapps/{YOUR_DOMAIN}/logs
mkdir /home/tomcat/webapps/{YOUR_DOMAIN}/{YOUR_APPLICATION}
mkdir /home/tomcat/webapps/{YOUR_DOMAIN}/{YOUR_APPLICATION}/WEB-INF
mkdir /home/tomcat/webapps/{YOUR_DOMAIN}/{YOUR_APPLICATION}/WEB-INF/classes

Set directory permissions as follows:

 

chmod 755 /home/tomcat/webapps
chmod 755 /home/tomcat/webapps/{YOUR_DOMAIN}
chmod 755 /home/tomcat/webapps/{YOUR_DOMAIN}/{YOUR_APPLICATION}

6.0 Configuring Tomcat

6.1 workers.properties

The workers.properties file contains information so mod_jk can connect to the Tomcat worker processes.

Place the following workers.properties file in the /etc/httpd/conf directory:

 

# workers.properties - ajp13
#
# List workers
worker.list=wrkr
#
# Define wrkr
worker.wrkr.port=8009
worker.wrkr.host=localhost
worker.wrkr.type=ajp13
worker.wrkr.cachesize=10
worker.wrkr.cache_timeout=600
worker.wrkr.socket_timeout=300

Notes

  1. There is an example workers.properties file located in the CONN_SRC_HOME/jk/conf directory. The example file provides a lot of useful information and insight into the workers.properties file, but it contains so much information that it can be confusing. I recommend using it as a learning tool but creating your own workers.properties file from scratch.
  2. The configuration above assumes Apache and Tomcat are located on the same box and requests are forwarded to Tomcat using type ajp13 workers. Type ajp13 workers forward requests to out-of-process Tomcat workers using the ajpv13 protocol over TCP/IP sockets.
  3. The name of the worker in the JkMount directive in httpd.conf must match the name of the worker in worker.list (“wrkr” in the configuration above).

6.2 server.xml

The CATALINA_HOME/conf/server.xml file contains Tomcat server configuration information. The default server.xml is great for verifying that Tomcat works in standalone mode and for viewing the examples that come with the application, but it contains so much information that it can be confusing. I recommend saving it for future reference and creating a new server.xml.

Save the default server.xml as follows:

 

mv CATALINA_HOME/conf/server.xml CATALINA_HOME/conf/server.xml.orig

Copy the following into a new server.xml file:

 

<Server port="8005" shutdown="0fbb9aebcbfbef203eca71b6be367859" debug="0">

	<Service name="Tomcat-Apache">

		<Connector address="127.0.0.1"
			port="8009"
			minProcessors="5"
			maxProcessors="75"
			enableLookups="false"
			protocol="AJP/1.3"
			debug="0"/>

		<Engine name="appserver"
			debug="0"
			defaultHost="{YOUR_DOMAIN}">

			<Host name="{YOUR_DOMAIN}"
				appBase="/home/tomcat/webapps"
				autoDeploy="false"
				deployOnStartup="false"
				unpackWARs="false"
				deployXML="true"
				debug="0"/>

		</Engine>

	</Service>

</Server>

If you do keep the default server.xml, make sure you comment out any other connectors besides mod_jk that are listening on port 8009. The default file comes with the Coyote/JK2 connector enabled for the Tomcat-Standalone service. This will conflict with the mod_jk connector in your Tomcat-Apache service. You should comment this connector out. It isn’t needed when you connect directly to Tomcat in standalone mode (port 8080), so I’m not sure why this connector is enabled by default.

The Connector address defines the interface that Tomcat will listen on for mod_jk requests from Apache. In my configuration, Apache and Tomcat reside on the same box, so I have set the address to the loopback address. The default is for Tomcat to listen on all interfaces, so restricting it to the loopback interface improves security.

The Server shutdown property is the text string that is sent over a socket connection to stop Tomcat. The default value is “SHUTDOWN”. The shutdown port is always on the loopback interface, which provides host-level protection. However, there is the possibility that the host could be compromised and someone could send the command SHUTDOWN to all ports and knock Tomcat offline. To prevent this, replace the default value with one that is difficult to guess. Do not use the example string above. Create your own by feeding random bytes into md5sum as follows:

 

head -1024c /dev/random | md5sum

Change the permissions on server.xml to prevent unprivileged users from reading the shutdown string:

 

chmod 600 CATALINA_HOME/conf/server.xml

6.3 Configuring the Context

It is recommended that contexts be defined in separate files, not in server.xml. The context configuration directory has the same name as the Engine in server.xml.

Create the context configuration directory as follows:

 

mkdir CATALINA_HOME/conf/appserver

The host context configuration directory has the same name as the corresponding Host in server.xml.

Create the context configuration directory for your domain as follows:

 

mkdir CATALINA_HOME/conf/appserver/{YOUR_DOMAIN}

Create the context configuration file as follows:

 

touch CATALINA_HOME/conf/appserver/{YOUR_DOMAIN}/{YOUR_APPLICATION}.xml

Copy the following text into {YOUR_APPLICATION}.xml:

 

<Context path=""
	docBase="{YOUR_APPLICATION}"
	reloadable="true"
	debug="0"/>

Setting the Context reloadable property to true tells Tomcat to automatically load new and changed application class files found in /WEB-INF/classes and /WEB-INF/lib. This feature is very useful during development. However, it is recommended to set reloadable to false in production environments because monitoring class file changes requires significant server resources.

6.4 log4j

Download the latest log4j and install log4j.jar in CATALINA_HOME/common/lib.

Download the latest commons logging and install commons-logging.jar in CATALINA_HOME/common/lib.

Create a file called log4j.properties as follows and place it in the CATALINA_HOME/common/classes directory:

 

log4j.rootLogger=WARN, R
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=/usr/local/jakarta-tomcat/logs/tomcat.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{DATE} - %p %c - %m%n
log4j.logger.org.apache.catalina=WARN, R

7.0 Configuring Apache

Apache is configured with directives placed in the main Apache configuration file, /etc/httpd/conf/httpd.conf. In addition, Apache 2 has configuration files for perl, php, and ssl located in /etc/httpd/conf.d/.

Rename the /etc/httpd/conf.d/ssl.conf file to ssl.conf.bak. The default Red Hat Apache 2 installation comes with ssl support enabled. If ssl is needed, you can re-enable it after you have successfully integrated Apache and Tomcat.

7.1 httpd.conf

You will notice that there are three sections labeled in the httpd.conf file supplied by Red Hat: (1) Global Environment, (2) Main Server Configuration, and (3) Virtual Hosts.

Add the following to the bottom of the existing LoadModule directives in the Global Environment section:

 

LoadModule jk_module modules/mod_jk.so

Add the following to the bottom of the Main Server Configuration section:

 

JkWorkersFile "/etc/httpd/conf/workers.properties"
JkLogFile "/etc/httpd/logs/mod_jk.log"
JkLogLevel info
JkLogStampFormat "[%a %b %d %H:%M:%S %Y]"

Set up a Virtual Host directive in the Virtual Hosts section of httpd.conf. Below is an example of how to set up the {YOUR_DOMAIN} website so Tomcat handles all jsp pages and requests with “servlet” in the path:

 

NameVirtualHost 127.0.0.1:80

<VirtualHost 127.0.0.1:80>
	ServerAdmin webmaster@{YOUR_DOMAIN}
	ServerName {YOUR_DOMAIN}
	DocumentRoot /home/tomcat/webapps/{YOUR_DOMAIN}/{YOUR_APPLICATION}
	ErrorLog /home/tomcat/webapps/{YOUR_DOMAIN}/logs/error_log
	CustomLog /home/tomcat/webapps/{YOUR_DOMAIN}/logs/access_log common
	JkMount /*.jsp wrkr
	JkMount /servlet/* wrkr
	# Deny direct access to WEB-INF
	<LocationMatch ".*WEB-INF.*">
		AllowOverride None
		deny from all
	</LocationMatch>
</VirtualHost>

The argument for the NameVirtualHost directive must match exactly the argument for the VirtualHost directive (127.0.0.1:80).

The JkMount directive specifies url patterns of requests that will be forwarded to Tomcat for processing.

You can test your Apache configuration by typing the following:

 

httpd -t -D DUMP_VHOSTS

You should get something like the following response:

 

127.0.0.1:80           is a NameVirtualHost
         default server {YOUR_DOMAIN} (/etc/httpd/conf/httpd.conf:1056)
         port 80 namevhost {YOUR_DOMAIN} (/etc/httpd/conf/httpd.conf:1056)
Syntax OK

8.0 Setting Up {YOUR_DOMAIN}

{YOUR_DOMAIN} does not need to be a domain name with a DNS entry. For testing purposes, you can set up any domain you want in the /etc/hosts file of the machine that you will be using to access your application.

The example below shows the entry for {YOUR_DOMAIN} when running Apache and Tomcat on a single machine, typical for a development computer.

 

127.0.0.1	{YOUR_DOMAIN}

9.0 Testing Apache

We will create and install a simple Hello World html page so we can test to make sure Apache handles requests for static html pages.

9.1 Hello World HTML

Copy the following text into a file called HelloWorld.html and install the file in the /home/tomcat/webapps/{YOUR_DOMAIN}/{YOUR_APPLICATION} directory.

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World HTML!</title>
</head>
<body>
<h1>Hello World HTML!</h1>
</body>
</html>

If Apache has not been restarted since you added your virtual host, do so as follows:

 

service httpd restart

You should now be able to type http://{YOUR_DOMAIN}/HelloWorld.html into your browser and see the always-exciting “Hello World” message.

10.0 Testing Tomcat

We will create and install a simple Hello World jsp page and servlet so we can test to make sure Apache forwards servlet requests to Tomcat for handling.

10.1 Hello World JSP

Copy the following text into a file called HelloWorld.jsp and install the file in the /home/tomcat/webapps/{YOUR_DOMAIN} directory.

 

<%@ page contentType="text/html;charset=WINDOWS-1252"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Hello World JSP</title>
</head>
<body>
<h1><% out.println(" Hello World JSP!"); %></h1>
</body>
</html>

10.2 Hello World Servlet

Copy the following into a file called HelloWorld.java:

 

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld
    extends HttpServlet {
    public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
                throws IOException, ServletException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		out.println("Hello World Servlet!");

	}

}

Compile the source into a class file as follows:

 

javac -classpath /usr/local/jakarta-tomcat/common/lib/servlet.jar HelloWorld.java

This will create a file called HelloWorld.class. Copy the HelloWorld.class file to the /home/tomcat/webapps/{YOUR_DOMAIN}/{YOUR_APPLICATION}/WEB-INF/classes directory.

10.3 Tomcat Application

The web.xml file is where a servlet name is mapped to a URL pattern so Tomcat can run your servlet when requested. Below is the web.xml file that runs the HelloWorld servlet whenever the URL http://{YOUR_DOMAIN}/servlet/HelloWorld is entered in the browser:

 

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

	<servlet>
		<servlet-name>HelloWorld</servlet-name>
		<servlet-class>HelloWorld</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>HelloWorld</servlet-name>
		<url-pattern>/servlet/HelloWorld</url-pattern>
	</servlet-mapping>

</web-app>

Restart Tomcat as follows:

 

/CATALINA_HOME/bin/shutdown.sh
/CATALINA_HOME/bin/startup.sh

Restart Apache as follows:

 

service httpd restart

You should now be able to type the following into your browser and see the always-exciting “Hello World” message:

http://{YOUR_DOMAIN}/HelloWorld.jsp

http://{YOUR_DOMAIN}/servlet/HelloWorld

11.0 Advanced Configuration

The following steps are not mandatory, but are suggested for a better, tighter Tomcat installation.

11.1 Tomcat Startup Script

If you want to automatically start Tomcat when your system boots and manage it using the service command as we do Apache, you must create an initialization script.

Copy the following text into a file called tomcat and install the file in the /etc/rc.d/init.d directory.

 

#!/bin/sh
#
# Startup script for Tomcat Servlet Engine
#
# chkconfig: 345 86 14
# description: Tomcat Servlet Engine
# processname: tomcat
# pidfile: /usr/local/jakarta-tomcat/bin/tomcat.pid
#

# User under which tomcat will run
TOMCAT_USER=tomcat

RETVAL=0

# start, debug, stop, and status functions
start() {
    # Start Tomcat in normal mode
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
    if [ $SHUTDOWN_PORT -ne 0 ]; then
        echo "Tomcat already started"
    else
        echo "Starting tomcat..."
        chown -R $TOMCAT_USER:$TOMCAT_USER /usr/local/jakarta-tomcat/*
        chown -R $TOMCAT_USER:$TOMCAT_USER /home/tomcat/*
        su -l $TOMCAT_USER -c '/usr/local/jakarta-tomcat/bin/startup.sh'
	SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
        while [ $SHUTDOWN_PORT -eq 0 ]; do
            sleep 1
            SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
        done	
        RETVAL=$?
        echo "Tomcat started in normal mode"
        [ $RETVAL=0 ] && touch /var/lock/subsys/tomcat
    fi
}

debug() {
    # Start Tomcat in debug mode
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
    if [ $SHUTDOWN_PORT -ne 0 ]; then
        echo "Tomcat already started"
    else
        echo "Starting tomcat in debug mode..."
        chown -R $TOMCAT_USER:$TOMCAT_USER /usr/local/jakarta-tomcat/*
        chown -R $TOMCAT_USER:$TOMCAT_USER /home/tomcat/*
        su -l $TOMCAT_USER -c '/usr/local/jakarta-tomcat/bin/catalina.sh jpda start'
	SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
        while [ $SHUTDOWN_PORT -eq 0 ]; do
            sleep 1
            SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
        done	
        RETVAL=$?
        echo "Tomcat started in debug mode"
        [ $RETVAL=0 ] && touch /var/lock/subsys/tomcat
    fi
}

stop() {
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
    if [ $SHUTDOWN_PORT -eq 0 ]; then
        echo "Tomcat already stopped"
    else
        echo "Stopping tomcat..."
        su -l $TOMCAT_USER -c '/usr/local/jakarta-tomcat/bin/shutdown.sh'
	SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
        while [ $SHUTDOWN_PORT -ne 0 ]; do
            sleep 1
            SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
        done
	RETVAL=$?
        echo "Tomcat stopped"
        [ $RETVAL=0 ] && rm -f /var/lock/subsys/tomcat /usr/local/jakarta-tomcat/bin/tomcat.pid
    fi
}

status() {
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
    if [ $SHUTDOWN_PORT -eq 0 ]; then
        echo "Tomcat stopped"
    else
        MODE="normal"
        JPDA_PORT=`netstat -vatn|grep LISTEN|grep 8000|wc -l`
        if [ $JPDA_PORT -ne 0 ]; then
            MODE="debug"
        fi
	echo "Tomcat running in $MODE mode"
    fi
}

case "$1" in
  start)
        start
        ;;
  debug)
        debug
        ;;
  stop)
        stop
        ;;
  restart)
        stop
        start
        ;;
  redebug)
        stop
        debug
        ;;
  status)
  	status
	;;
  *)
	echo "Usage: $0 {start|debug|stop|restart|redebug|status}"
	exit 1
esac

exit $RETVAL

Add the startup script to your system as follows:

 

chkconfig --add tomcat

The path of the file that contains the pid of the catalina startup java process can be set with the CATALINA_PID environment variable. CATALINA_HOME/bin/catalina.sh automatically calls a file called setenv.sh if it exists, so this is a good place to set environment variables.

Create setenv.sh as follows:

 

cd CATALINA_HOME/bin
touch setenv.sh
chmod 644 setenv.sh

Copy the following text into setenv.sh:

 

CATALINA_PID=/usr/local/jakarta-tomcat/bin/tomcat.pid

Now you will be able to start/stop/restart/status Tomcat using the following commands:

 

service tomcat start
service tomcat stop
service tomcat restart
service tomcat status

If you want Tomcat to start automatically when your system boots, you need to add tomcat to your runlevel as follows:

 

chkconfig --level 5 tomcat on

Runlevel 5 is the X Window System, typical for a development computer. Runlevel 3 is typical for a dedicated web server.

Apache and Tomcat can be started and restarted in any order. In the past (specifically with the 1.2.5 connector), if Tomcat was restarted, Apache would have to be restarted. This was because the AJP13 protocol maintains open sockets between Apache and Tomcat, and when Tomcat was restarted the connections would be hung in CLOSE_WAIT status until Apache was restarted. This has been fixed starting with the 1.2.6 connector.

11.2 Development Setup

During development, you will need access to your tomcat application directory. Add the user account under which you will be doing development to the tomcat group in /etc/group. For example, this is what the tomcat entry might look like in /etc/group if you do development under the yourname account:

 

tomcat:x:502:yourname

Make sure the tomcat group has permission to publish files (e.g. using ant) to your Tomcat application in /home/tomcat/webapps/{YOUR_DOMAIN}. Issue the following commands as root:

 

chmod g+x /home/tomcat
chmod -R g+rw /home/tomcat

12.0 Troubleshooting

12.1 Log Files To Watch

/home/tomcat/webapps/{YOUR_DOMAIN}/logs/error_log

Look here for clues to Apache httpd.conf configuration issues, for example VirtualHost setup.

CATALINA_HOME/logs/catalina.out

Look here for clues to Tomcat server.xml configuration issues. This file is written to when Tomcat starts and stops. It also catches System.out and System.err.

CATALINA_HOME/logs/tomcat.log

Look here for clues to all Tomcat issues. This is the main Tomcat log file.

/etc/httpd/logs/mod_jk.log

Look here for clues to mod_jk configuration issues.

12.2 Monitoring Connections

The following command can be used to monitor the Apache, Tomcat, and mod_jk connections:

 

netstat -vatn | grep 80

Below is output from running this command. Line numbers have been added to the beginning of each line for discussion purposes.

 

1 tcp        0      0 127.0.0.1:8005          0.0.0.0:*               LISTEN
2 tcp        0      0 127.0.0.1:8009          0.0.0.0:*               LISTEN
3 tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN
4 tcp        0      0 127.0.0.1:8009          127.0.0.1:34449         ESTABLISHED
5 tcp        0      0 127.0.0.1:34449         127.0.0.1:8009          ESTABLISHED

Notes

  1. Line 1 shows Tomcat listening on port 8005 for the shutdown command.
  2. Line 2 shows Tomcat listening on port 8009 for requests from Apache.
  3. Line 3 shows Apache listening on port 80 for user requests.
  4. Line 4 shows the Tomcat end of a mod_jk connection.
  5. Line 5 shows the Apache end of a mod_jk connection.

Multicast on linux

Multicast on linux

 

# setup the routes
ip route add 224.0.0.0/4 dev eth0

# try to ping the multicast aware hosts on your lan with 2 pings
ping -c 2 224.0.0.1
# 100% packet loss

# stop ignoring broadcasts
sudo echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts

# try to ping the multicast aware hosts on your lan with 2 pings
ping -c 2 224.0.0.1
# 100% packet success!

# make your change permanent
echo "net.ipv4.icmp_echo_ignore_broadcasts = 0" >> /etc/sysctl.conf

Comfortable environment On Linux Shell

Comfortable environment On Linux Shell

After installing new Linux or Unix system I like to edit /etc/profile or $HOME/.bash_profile and add following lines:

alias vi=”vim -o”
alias ll=”ls -l”
alias la=”ls -la”
export EDITOR=vi
First line is to use vim instead of vi. Second and third lines will create two aliases for ls -l and ls -la commands. And forth line is to use vi always as system editor.

List number of file handles (open files) for each process

List number of file handles (open files) for each process

Here is a simple script that will show you a number of file handles (open files) used by each process on your Linux system:

ps -e|grep -v TTY|awk {‘print “echo -n \”Process: “$4″\tPID: “$1″\tNumber of FH: \”; lsof -p “$1″|wc -l”‘} > out; . ./out

Find directory with biggest number of files / directories

Find directory with biggest number of files / directories

Today we had a problem related with a number of files in a directory. We needed to find directories with a biggest number of files / directories in it. Here is a small shell script that will list directories and a number of files/directories in each directory.

find . -type d|awk {‘print “echo -n “$1″.\”\t\”; ls “$1″|wc -l”‘} > /tmp/do; . /tmp/do|sort -k 2 -n -r |more

Explaining it a little bit:

“find . -type d” – find all directories bellow current directory
“awk {‘print “echo -n “$1″.\”\t\”; ls “$1″|wc -l”‘} > /tmp/do” – generate a script that will print a directory name (echo -n), make ls in this directory and count a number of lines from ls (wc -l)
“. /tmp/do” – execute generated script
“sort -k 2 -n -r” – sort the result using second column (-k 2) as numerical (-n) and in reverse order (-r)

Rebooting linux without reboot command

Rebooting linux without reboot command

Just a sample of how you can reboot or shutdown linux without issuing reboot command, so called hard reboot. That means that system will just make a reset as if you pressed a reset button, without running any shutdown scripts, etc. A kind of dangerous staff, but can be helpful in some occasions.

echo 1 > /proc/sys/kernel/sysrq

echo b > /proc/sysrq-trigger
If you want to force shutdown machine try this.
echo 1 > /proc/sys/kernel/sysrq
echo o > /proc/sysrq-trigger

Encrypt Files Using GnuPG

Encrypt Files Using GnuPG

HowTo we will discuss to encypt files using GnuPG. Encryption is a method which protect data stored on your computer or sending over the network from compromise. It can be used to ensure and verify data comes from a rightful owner, and also to maintain confidentiality of the data. We will used a tool GnuPG (GNU Privacy Guard) to encrypt individual files or validate files.

GnuPG is an opensource implementation of the OpenPGP public key encryption system. Public Key Encryption uses asymmetric encryption, in which a matching pair of public and private keys are used to encrypt or decrypt. A person who accomplished this has to generate two keys i.e Private Key and Public Key.

Private Key is the one kept by owner secretly and what is encrypt by private key can decrypt by the one who has the matching public key or what is encrypt by the public key by anyone can decrypt by the private key owner. Beside encryption it also verify that messages comes from the holder of the private or public keys.

1) Generate Keys

Use following command to generate Public and Private Keys.

gpg –gen-key

It will ask series of questions, you can answer as per your need but this is what I used for example.

Please select what kind of key you want:
(1) RSA and RSA (default)
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
Your selection? Press Enter to have default RSA

RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048) Press Enter

Please specify how long the key should be valid.
0 = key does not expire
= key expires in n days
w = key expires in n weeks
m = key expires in n months
y = key expires in n years
Key is valid for? (0) Press Enter
Key does not expire at all
Is this correct? (y/N) y

 

You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
“Heinrich Heine (Der Dichter) ”

Real name: Mohan Ramadoss
Email address: rmohan@rmohan.com
Comment: Press Enter
You selected this USER-ID:
“Mohan Ramadoss”

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o

 

You need a Passphrase to protect your secret key.
fedorahat@123

Use following commands to list your keys. You need to note the key-id to export your key. In below you can see the key-id after pub2048R which is ABF9DEAB.

 

gpg –list-keys
/home/rmohan/.gnupg/pubring.gpg
——————————-
pub 2048R/ABF9DEAB 2012-02-16
uid Mohan Ramadoss
sub 2048R/68DA88B7 2012-02-16
It will create a file named mohan-public.key on current location. Now transfer this file to your partner which you need to have it to decrypt or verify your files.

Where -a is to put output in text rather than binary format. key-id will ensure we are using same key.

scp mohan-public.key test@192.168.10.12:

Now let your partner to import your public key.

gpg –import mohan-public.key

gpg –list-keys
/home/rmohan/.gnupg/pubring.gpg
——————————-
pub 2048R/ABF9DEAB 2012-02-16
uid Mohan Ramadoss
sub 2048R/68DA88B7 2012-02-16

2). Export Public Key

Use following command to export your public key.

    gpg -a -o mohan-public.key –export ABF9DEAB

It will create a file named mohan-public.key on current location. Now transfer this file to your partner which you need to have it to decrypt or verify your files.

Where -a is to put output in text rather than binary format. key-id will ensure we are using same key.

    scp mohan-public.key test@192.168.10.12:

Now let your partner to import your public key.

gpg –import mohan-public.key

3) Encrypt and Decrypt the File.

Lets now test it by encrypting one file by test using mohan public key and then decrypt it.

echo ‘This text is encrpted and can only be view by using sohail public key’ > decrypt.txt

  gpg –encrypt -a -r ABF9DEAB decrypt.txt

It will create encrypted file with appended .asc extension. where -r will require to pub recipient name or key-id to whom this encryption has done.

ls
   decrypt-me.txt.asc

Now transfer this file to your partner computer.

    scp test@192.168.10.12:decrypt.txt.asc .

Now decrypt the file on your computer.

First see what it contain.

cat decrypt.txt.asc

—–BEGIN PGP MESSAGE—–
Version: GnuPG v1.4.11 (GNU/Linux)

hQEMAy7GnyBo2oi3AQgAg1m/6bcLj+RZ4IKSr0HitWWyWc3mkIUkZ6KAMJnY2kSx
JmZ6e0Sc+D/D9CUy0cmD6PGQcO2LjfQvTKpPvups9Ug3mr9JCqJyjfeDb59uiKN1
8cvq2U0/OVppLb+yf4Z19OryuCdX2MlDdkmhlUaNbftWOA3YlYubi5Db0Fwl+e+X
nt6SZv51XnQ1wM3fsGN0q5+DAfPsIYtmRkDHvMkkdojkdO8Oxnj4LNu3/iFhgNTl

—–END PGP MESSAGE—–

Now decrypt and save output on a file named decrypted.txt, note it will require passphrase which you used while creating keys.

    gpg –decrypt decrypttxt.asc > decrypted.txt

You need a passphrase to unlock the secret key for
user: “Mohan Ramadoss”
2048-bit RSA key, ID 68DA88B7, created 2012-02-16 (main key ID ABF9DEAB)

gpg: encrypted with 2048-bit RSA key, ID 68DA88B7, created 2012-02-16
“Mohan Ramadoss”

cat decrypted.txt

This text is encrypted using mohan public key and can only be decrypt by mohan

For more options you can see man pages of gpg using following command.

man gpg

For any question please comment.

 

Quick’n easy gpg cheatsheet

If you found this page, hopefully it’s what you were looking for. It’s just a brief explanation of some of the command line functionality from gnu privacy guard (gpg). Please email me if you find any errors (scout3801@gmail.com ).

Filenames are italicized (loosely, some aren’t, sorry), so if you see something italicized, think “put my filename there.”

I’ve used User Name as being the name associated with the key. Sorry that isn’t very imaginative. I *think* gpg is pretty wide in it’s user assignments, ie. the name for my private key is Charles Lockhart, but I can reference that by just putting in Lockhart. That doesn’t make any sense, sorry.

to create a key:
gpg –gen-key
generally you can select the defaults.

to export a public key into file public.key:
gpg –export -a “User Name” > public.key

This will create a file called public.key with the ascii representation of the public key for User Name. This is a variation on:
gpg –export
which by itself is basically going to print out a bunch of crap to your screen. I recommend against doing this.
gpg –export -a “User Name”
prints out the public key for User Name to the command line, which is only semi-useful

to export a private key:
gpg –export-secret-key -a “User Name” > private.key

This will create a file called private.key with the ascii representation of the private key for User Name.
It’s pretty much like exporting a public key, but you have to override some default protections. There’s a note (*) at the bottom explaining why you may want to do this.

to import a public key:
gpg –import public.key

This adds the public key in the file “public.key” to your public key ring.

to import a private key:
gpg –allow-secret-key-import –import private.key

This adds the private key in the file “private.key” to your private key ring. There’s a note (*) at the bottom explaining why you may want to do this.

to delete a public key (from your public key ring):
gpg –delete-key “User Name”
This removes the public key from your public key ring.
NOTE! If there is a private key on your private key ring associated with this public key, you will get an error! You must delete your private key for this key pair from your private key ring first.

to delete an private key (a key on your private key ring):
gpg –delete-secret-key “User Name”
This deletes the secret key from your secret key ring.

To list the keys in your public key ring:
gpg –list-keys

To list the keys in your secret key ring:
gpg –list-secret-keys

To generate a short list of numbers that you can use via an alternative method to verify a public key, use:
gpg –fingerprint > fingerprint
This creates the file fingerprint with your fingerprint info.

To encrypt data, use:
gpg -e -u “Sender User Name” -r “Receiver User Name” somefile

There are some useful options here, such as -u to specify the secret key to be used, and -r to specify the public key of the recipient.
As an example: gpg -e -u “Charles Lockhart” -r “A Friend” mydata.tar
This should create a file called “mydata.tar.gpg” that contains the encrypted data. I think you specify the senders username so that the recipient can verify that the contents are from that person (using the fingerprint?).
NOTE!: mydata.tar is not removed, you end up with two files, so if you want to have only the encrypted file in existance, you probably have to delete mydata.tar yourself.
An interesting side note, I encrypted the preemptive kernel patch, a file of 55,247 bytes, and ended up with an encrypted file of 15,276 bytes.

To decrypt data, use:
gpg -d mydata.tar.gpg
If you have multiple secret keys, it’ll choose the correct one, or output an error if the correct one doesn’t exist. You’ll be prompted to enter your passphrase. Afterwards there will exist the file “mydata.tar”, and the encrypted “original,” mydata.tar.gpg.

NOTE: when I originally wrote this cheat sheet, that’s how it worked on my system, however it looks now like “gpg -d mydata.tar.gpg” dumps the file contents to standard output. The working alternative (worked on my system, anyway) would be to use “gpg -o outputfile -d encryptedfile.gpg”, or using mydata.tar.gpg as an example, I’d run “gpg -o mydata.tar -d mydata.tar.gpg”. Alternatively you could run something like “gpg -d mydata.tar.gpg > mydata.tar” and just push the output into a file. Seemed to work either way.

Ok, so what if you’re a paranoid bastard and want to encrypt some of your own files, so nobody can break into your computer and get them? Simply encrypt them using yourself as the recipient.

I haven’t used the commands:
gpg –edit-key
gpg –gen-revoke

  • –gen-revoke creates a revocation certificate, which when distributed to people and keyservers tells them that your key is no longer valid, see http://www.gnupg.org/gph/en/manual/r721.html
  • –edit-key allows you do do an assortment of key tasks, see http://www.gnupg.org/gph/en/manual/r899.html

 

 

Sharing Secret Keys

NOTE!: the following use cases indicate why the secret-key import/export commands exist, or at least a couple ideas of what you could do with them. HOWEVER, there’s some logistics required for sharing that secret-key. How do you get it from one computer to another? I guess encrypting it and sending it by email would probably be ok, but I wouldn’t send it unencrypted with email, that’d be DANGEROUS.

Use Case *.1 : Mentioned above were the commands for exporting and importing secret keys, and I want to explain one reason of why maybe you’d want to do this. Basically if you want one key-pair for all of your computers (assuming you have multiple computers), then this allows you export that key-pair from the original computer and import it to your other computers. 

Use Case *.2 : Mentioned above were the commands for exporting and importing secret keys, and I want to explain one reason of why maybe you’d want to do this. Basically, if you belonged to a group, and wanted to create a single key-pair for that group, one person would create the key-pair, then export the public and private keys, give them to the other members of the group, and they would all import that key-pair. Then a member of the group or someone outside could use the group public key, encrypt the message and/or data, and send it to members of the group, and all of them would be able to access the message and/or data. Basically you could create a simplified system where only one public key was needed to send encrypted stuffs to muliple recipients.

Clustering Tomcat Server

Clustering Tomcat Server
A cluster of two Tomcat is a more Tomcats that are hosted in the same Java application. The main function of cluster Tomcat is to perform replication of open sessions in each cluster of Tomcat, so Tomcat each contain their sessions and their attributes, as well as the attributes of the other sessions and Tomcats. Each Tomcat cluster is called a node.

With the Tomcat cluster can achieve high availability, so that if a cluster node fails, the requests coming to this node are forwarded to another active node. All this without the user noticing, because your session is active on other cluster nodes.

The figure below shows the architecture of the cluster of Tomcat:

 

 

Tomcat cluster configuration
I will take into consideration that you have two instances of Tomcat, Apache and Java installed on your server. Below is a description of the environment that will be used in this small project, it is worth remembering that it is only a test project:

Two instances of virtual machines in VirtualBox;
Each VM with 512MB RAM and 8GB HD;
Each VM operating system with CentOS 5.7 (Final).

Note: This configuration can be performed on any Linux server.

requirements:

To perform the replication sessions between nodes in the cluster a few points should be checked:

All session attributes must implement java.io.Serializable;
Having the application web.xml <distributable/> the attribute or set a property in the context of the application configuration file server.xml;
Configure the load balancer with sticky session option active, to keep the same user requests a system going to the same cluster node, except when this node fails.

Starting the configuration:

The configuration of the Tomcats to the cluster is made from editing the server.xml file, located in the conf (<product the tomcat> / conf / server.xml) for each Tomcat.

What should be done is uncomment the whole tag and add cluster configuration adapting the parameters to the hosting environment. Just below the cluster configuration:

 

<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
                 channelSendOptions="8">
 
          <Manager className="org.apache.catalina.ha.session.DeltaManager"
                   expireSessionsOnShutdown="false"
                   notifyListenersOnReplication="true"/>
 
          <Channel className="org.apache.catalina.tribes.group.GroupChannel">
            <Membership className="org.apache.catalina.tribes.membership.McastService"
                        address="228.0.0.4"
                        port="45564"
                        frequency="500"
                        dropTime="3000"/>
            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                      address="auto"
                      port="4000"
                      autoBind="100"
                      selectorTimeout="5000"
                      maxThreads="6"/>
 
            <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
              <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
            </Sender>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
          </Channel>
 
          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
                 filter=""/>
          <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>
 
          <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
                    tempDir="/tmp/war-temp/"
                    deployDir="/tmp/war-deploy/"
                    watchDir="/tmp/war-listen/"
                    watchEnabled="false"/>
 
          <ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
          <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
        </Cluster>  

 

In each Tomcat cluster have the same tag with a small difference in the configuration:

 

 

 

we have to identify each node in the same file “server.xml”. In Tomcat The Tomcat and B will need to make some changes to the nodes can communicate:

 

 

Note: Changes are highlighted in bold, but these changes are an example of configuration, not necessarily have to use these same values, can be done with other values.After making these settings, simply start the Tomcats that they begin to replicate its sessions, or begin working on the cluster.To start the Tomcats just enter the directory bin / in each Tomcat and run the following command:

sh startup.sh
Load Balancing
he service is able to forward requests to multiple servers within a cluster, so that each cluster node is not overloaded, thus ensuring the use level of all computing resources within the cluster.In this project, the Apache will be responsible for balancing the load between two Tomcats. Apache will receive the requests coming from the customer and by the amount of requests sent to each Tomcat, it will be transferred to each of them.The figure below shows the architecture of Tomcat cluster with load balancing:

Configuring the Load Balancer
As was said in previous posts, responsible for load balancing Apache. To do this using Apache mod_proxy and mod_proxy_balancer. With mod_proxy Apache works as a proxy FTP, HTTP and SSL. Mod_proxy_balancer already provides a service load balancing for HTTP, FTP and ajp13. The mod_proxy_balancer depends on the use of mod_proxy.Currently there are two methods of load balancing:For quantities of requests, where each cluster node will receive a request at a time so that none of us get overwhelmed.
For traffic, where a dedicated balancer cluster node to which the request for travel on much information while the other requests will be sent to other servers.

The scenario will be where the cluster configuration will be described below:

Server IP = 192.168.56.101
Application to be used in this example is a system to ask for lunch which was developed at the company I work. The system is jBroca.

The configuration of the load balancer will be made in the configuration file of the Apache “httpd.conf”. In CentOS Apache configuration file is located inside the / etc / httpd / conf /.

Insert this at the end of httpd.conf:

<VirtualHost 192.168.56.101:80>
ServerName 192.168.56.101
ProxyRequests Off<Proxy 192.168.56:80>
Order deny,allow
Allow from all
</Proxy>ProxyPass /teste balancer://balancer lbmethod=byrequests stickysession=JSESSIONID nofailover=off
ProxyPassReverse /teste http://192.168.56.101:8080/jbroca
ProxyPassReverse /teste http://192.168.56.101:8081/jbroca

<Proxy balancer://balancer>

BalancerMember http://192.168.56.101:8080/jbroca route=node01 loadfactor=1
BalancerMember http://192.168.56.101:8081/jbroca route=node02 loadfactor=1

</Proxy>

<Location /balancer-manager>

setHandler balancer-manager
Order Deny,Allow
Deny from all
Allow from 192.168.56.101

</Location>

</VirtualHost>

In this section we setup a virtualhost which will be responsible for receipt of requests for the url 192.168.56.101/jbroca. Below is a description of each item in this configuration:ServerName: determines the name of the virtual host, in this case 192.168.56.101/jbroca.
ProxyRequest off: Determines that Apache will not be used as a proxy server or a reverse proxy.
ProxyPass / test balancer :/ / balancer lbmethod = byrequests stickysession nofailover = JSESSIONID = off: any request for use in the context / test will use the load balancer balancer to meet demand.
lbmethod = byrequests: is where you define the type of load balancing, in which case load balancing is per request.
stickysession = JSESSIONID: defines that Apache will direct requests for the same section to the same server.
nofailover = off: defines that all servers within the cluster will be able to overcome the failure of a server cluster that become inactive, the Apache server this will divert requests to another server.The following options are settings used to correct the responses from the servers in the cluster that are balanced, based on the request coming from the client:

ProxyPassReverse / jbroca http://192.168.56.101:8080/jbroca
ProxyPassReverse / jbroca http://192.168.56.101:8081/jbroca

Now is where we declare to the load balancer cluster members and their respective characteristics:

<Proxy Balancer://balancer>
BalancerMember http://192.168.56.101:8080/jbroca route = node01 loadfactor = 1
BalancerMember http://192.168.56.101:8081/jbroca route = node02 loadfactor = 1
</ Proxy>

The last option enables the load balancer management for browsers 192.168.56.101 domain. To view the balancer-manager in the browser just type:

http://192.168.56.101/balancer-manager

<Location /balancer-manager>
SetHandler balancer-manager
Order Deny, Allow
Deny from all
Allow from 192.168.56.101
</ Location>

With this, the Apache is configured to perform load balancing, routing requests to both servers within the cluster.

To test whether all configuration is correct, start the Tomcats and start the Apache server starts correctly, your cluster is working and just access the browser to check if the balancer is working properly. In the example above go to:

http://192.168.56.101/jbroca

Access to different browsers and make sure the balancer is actually directing the requests to each server. In this example that was used, the address bar shows that the requests are balanced:

http://192.168.56.101/jbroca/autenticarUsuario.do; jsessionid = 9225E01A70F0A90B2283244B2CF554D3.node01
http://192.168.56.101/jbroca/autenticarUsuario.do; jsessionid = 4B2BF75B6B2F99EAB791D512E52AC626.node02

The return address shows requests divided in two Tomcats cluster. The balancer-manager also shows that the requests are balanced.

We end here, hope you all have managed to understand what I had to pass. The application will not be available to be used only in the company I work, then the application you develop and test applications running on the cluster.

Thank you all.