RSS

Archivio mensile:gennaio 2015

shell commands on SSH enabled System using JSch library

package com.corejsf.java;

import java.io.BufferedReader;
import java.io.Console;
import java.io.InputStream;

import java.io.InputStreamReader;

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

public class SSHCommandExecutor {

/**
* @param args
*/
public static void main(String[] args) {
String host = “”;
String user = “”;
String password = “”;
String command1 = “”;
Channel channel = null;

// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

try {

java.util.Properties config = new java.util.Properties();
config.put(“StrictHostKeyChecking”, “no”);
JSch jsch = new JSch();
System.out.print(“Host : “);
host = br.readLine();
System.out.print(“UserName : “);
user = br.readLine();
System.out.print(“Password : “);
password = br.readLine();
System.out.print(“Command : “);
command1 = br.readLine();
Session session = jsch.getSession(user, host, 22);
session.setPassword(new String(password));
session.setConfig(config);
session.connect();
System.out.println(“Connected”);

channel = session.openChannel(“exec”);
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);

InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));

}
if (channel.isClosed()) {
System.out.println("exit-status: "
+ channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}

channel.disconnect();
session.disconnect();
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}

}

}

 
Lascia un commento

Pubblicato da su gennaio 9, 2015 in Linux