JSch – Java – SSH Example

Problem Statement: We have one application running in 10 servers. How to grep for exception or key word in all of them with one single command?
Solution: Use JSch and pass the command to all 10 servers and print the data on java console.
Download JSch jar from following site and put it in classpath.
http://www.jcraft.com/jsch/

<dependency>
     <groupId>com.jcraft</groupId>
     <artifactId>jsch</artifactId>
     <version>0.1.51</version>
</dependency>
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class JavaTelnetExample {

	public static void main(String[] arg) {
		try {
			JSch jsch = new JSch();
			Session session = jsch.getSession("userid", "hostname", 22);
			session.setPassword("password");
			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);

			session.connect();
			System.out.println("==>" + executeCommand(session, "date"));
			System.out.println("==>" + executeCommand(session, "ls"));
			System.out.println("==>" + executeCommand(session, "who"));
			System.out.println("==>" + executeCommand(session, "tail -50 /path/abcd.log"));

			session.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String executeCommand(Session session, String command)
			throws Exception {
		ChannelExec channel = (ChannelExec) session.openChannel("exec");
		channel.setCommand(command);
		channel.setInputStream(null);
		channel.setErrStream(System.err);
		channel.connect();

		InputStream in = channel.getInputStream();

		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String line;
		StringBuffer sb = new StringBuffer();
		while ((line = br.readLine()) != null) {
				sb.append(line + 'n');
		}
		channel.disconnect();

		return sb.toString();
	}
}

Telnet Vs SSH: http://www.differencebetween.net/technology/internet/difference-between-telnet-and-ssh/

Splunk Log Management: http://www.splunk.com/

-o-

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s