Skip to main content

Java execute remote ssh command jcraft jsch example

JSch is a famous Java implementation of SSHv2. Below is an example of a running simple ifconfig command on a linux host from a webapp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="java.util.*" %>
<%@ page import="*" %>
<%@ page import="com.jcraft.jsch.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<title>Remote Ssh</title>
String sshHost = "sshhost";
int sshPort = 22;
String sshUserName = "username";
String sshPassword = "password";
String sshCommand ="ifconfig";
InputStream in = null;
FileOutputStream fos=new FileOutputStream("/tmp/ErrLog");
com.jcraft.jsch.Session jschsess = null;

try {
JSch jsch = new JSch();
Properties conf = new Properties();
conf.put("StrictHostKeyChecking", "no");
jschsess = jsch.getSession( sshUserName , sshHost);
Channel channel = jschsess.openChannel("exec");
byte[] tmp = new byte[1024];
while (true) {
        while (in.available() > 0) {
            int i =, 0, 1024);
            if (i < 0)
                out.print(new String(tmp, 0, i));
        if (channel.isClosed()) {
             if(in.available() > 0) {
                int i =, 0, 1024);
                out.print(new String(tmp, 0, i));
             if (channel.getExitStatus() == 0) {
             out.println("Command has been posted to the server.");
        try {
              } catch (Exception ee) {}
} catch (Exception e) {
        out.println("Error. " + e.toString());

If your ssh command need tty terminal "((ChannelExec)channel).setPty(true);" should be used.


Popular posts from this blog

Find and replace with sed command in Linux

Find and replace feature is always handy. It can turn into a torture when it comes to change or delete a simple constant string in a text file. There is a handy tool in linux for doing these kind of tihngs. Actually sed is not a text editor but it is used outside of the text file to make changes.

Sending Jboss Server Logs to Logstash Using Filebeat with Multiline Support

In addition to sending system logs to logstash, it is possible to add a prospector section to the filebeat.yml for jboss server logs. Sometimes jboss server.log has single events made up from several lines of messages. In such cases Filebeat should be configured for a multiline prospector.
Filebeat takes lines do not start with a date pattern (look at pattern in the multiline section "^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}" and negate section is set to true) and combines them with the previous line that starts with a date pattern.

server.log file excerpt where DatePattern: yyyy-MM-dd-HH and ConversionPattern: %d %-5p [%c] %m%n
Logstash filter: