package com.po;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.InteractiveCallback;
import com.trilead.ssh2.KnownHosts;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;
public class SshCommandUtil {
private static SshCommandUtil sshUtil = null;
private static String knownHostPath = "knownHost";
private static KnownHosts database = new KnownHosts();
private SshCommandUtil() throws IOException{
String path = System.getProperty("user.home")+"/.gridview";
File knownHostFile = new File(path);
if (!knownHostFile.exists()) {
knownHostFile.mkdir();
}
knownHostPath = path+"/"+knownHostPath;
File knownHostFileR = new File(knownHostPath);
if (! knownHostFileR.exists()) {
knownHostFileR.createNewFile();
}
database.addHostkeys(knownHostFileR);
}
public synchronized static SshCommandUtil getinstance() throws IOException{
if (null == sshUtil) {
sshUtil = new SshCommandUtil();
}
return sshUtil;
}
public Result exeCommand(String hostName,int port,String userName,String password,String command){
Result result = new Result();
Connection con = new Connection(hostName,port);
try{
String[] hostKeyAlgos = database.getPreferredServerHostkeyAlgorithmOrder(hostName);
if (null != hostKeyAlgos){
con.setServerHostKeyAlgorithms(hostKeyAlgos);
}
con.connect(new ServerHostKeyVerifier(){
@Override
public boolean verifyServerHostKey(String hostName, int port,
String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
int result = database.verifyHostkey(hostName, serverHostKeyAlgorithm, serverHostKey);
switch(result) {
case KnownHosts.HOSTKEY_IS_OK:
return true;
case KnownHosts.HOSTKEY_HAS_CHANGED:
break;
case KnownHosts.HOSTKEY_IS_NEW:
break;
default:
throw new IllegalStateException();
}
String hashedHostName = KnownHosts.createHashedHostname(hostName);
//hashedHostName = hostName;
database.addHostkey(new String[]{hashedHostName}, serverHostKeyAlgorithm, serverHostKey);
KnownHosts.addHostkeyToFile(new File(knownHostPath),new String[]{hashedHostName}, serverHostKeyAlgorithm, serverHostKey);
return true;
}
});
}catch(IOException e) {
e.printStackTrace();
result.setStatus(false);
result.setErrMsg(e.getMessage());
return result;
}
Session session = null;
boolean isAuthenticated = false;
try{
final String pwd = password;
if (con.isAuthMethodAvailable(userName,"keyboard-interactive")) {
isAuthenticated = con.authenticateWithKeyboardInteractive(userName, new InteractiveCallback(){
@Override
public String[] replyToChallenge(String name, String instruction,
int numPrompts, String[] prompt, boolean[] echo)
throws Exception {
String[] result = new String[numPrompts];
for (int i=0; i < numPrompts;i++) {
result[i] = pwd;
}
return result;
}
});
} else if (con.isAuthMethodAvailable(userName,"publickey")) {
isAuthenticated = con.authenticateWithPublicKey(userName,new char[0], password);
} else {
isAuthenticated = con.authenticateWithPassword(userName, password);
}
if (!isAuthenticated) {
System.out.println(hostName+" Authentication failed.");
result.setStatus(false);
result.setErrMsg(hostName+" Authentication failed.");
return result;
}
session = con.openSession();
session.execCommand(command);
StringBuilder errsb = new StringBuilder();
InputStream stdErr = new StreamGobbler(session.getStderr());
BufferedReader reader = new BufferedReader(new InputStreamReader(stdErr));
while(true) {
String line = reader.readLine();
if (null == line) {
break;
}
errsb.append(line+"\n");
}
result.setErrMsg(errsb.toString());
StringBuilder successsb = new StringBuilder();
InputStream stdOut = new StreamGobbler(session.getStdout());
reader = new BufferedReader(new InputStreamReader(stdOut));
while(true) {
String line = reader.readLine();
if (null == line) {
break;
}
successsb.append(line+"\n");
}
result.setSuccessMsg(successsb.toString());
if (errsb.length() <= 0) {
result.setStatus(true);
} else {
result.setStatus(false);
}
}catch(IOException e) {
e.printStackTrace();
result.setStatus(false);
result.setErrMsg(e.getMessage());
return result;
}finally{
if (null != session) {
session.close();
session = null;
}
if (null != con) {
con.close();
con = null;
}
}
return result;
}
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
SshCommandUtil ssh = SshCommandUtil.getinstance();
Result result = ssh.exeCommand("10.0.31.231",22,"root","sugon123","cat /proc/cpuinfo");
System.out.println(result);
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.InteractiveCallback;
import com.trilead.ssh2.KnownHosts;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;
public class SshCommandUtil {
private static SshCommandUtil sshUtil = null;
private static String knownHostPath = "knownHost";
private static KnownHosts database = new KnownHosts();
private SshCommandUtil() throws IOException{
String path = System.getProperty("user.home")+"/.gridview";
File knownHostFile = new File(path);
if (!knownHostFile.exists()) {
knownHostFile.mkdir();
}
knownHostPath = path+"/"+knownHostPath;
File knownHostFileR = new File(knownHostPath);
if (! knownHostFileR.exists()) {
knownHostFileR.createNewFile();
}
database.addHostkeys(knownHostFileR);
}
public synchronized static SshCommandUtil getinstance() throws IOException{
if (null == sshUtil) {
sshUtil = new SshCommandUtil();
}
return sshUtil;
}
public Result exeCommand(String hostName,int port,String userName,String password,String command){
Result result = new Result();
Connection con = new Connection(hostName,port);
try{
String[] hostKeyAlgos = database.getPreferredServerHostkeyAlgorithmOrder(hostName);
if (null != hostKeyAlgos){
con.setServerHostKeyAlgorithms(hostKeyAlgos);
}
con.connect(new ServerHostKeyVerifier(){
@Override
public boolean verifyServerHostKey(String hostName, int port,
String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
int result = database.verifyHostkey(hostName, serverHostKeyAlgorithm, serverHostKey);
switch(result) {
case KnownHosts.HOSTKEY_IS_OK:
return true;
case KnownHosts.HOSTKEY_HAS_CHANGED:
break;
case KnownHosts.HOSTKEY_IS_NEW:
break;
default:
throw new IllegalStateException();
}
String hashedHostName = KnownHosts.createHashedHostname(hostName);
//hashedHostName = hostName;
database.addHostkey(new String[]{hashedHostName}, serverHostKeyAlgorithm, serverHostKey);
KnownHosts.addHostkeyToFile(new File(knownHostPath),new String[]{hashedHostName}, serverHostKeyAlgorithm, serverHostKey);
return true;
}
});
}catch(IOException e) {
e.printStackTrace();
result.setStatus(false);
result.setErrMsg(e.getMessage());
return result;
}
Session session = null;
boolean isAuthenticated = false;
try{
final String pwd = password;
if (con.isAuthMethodAvailable(userName,"keyboard-interactive")) {
isAuthenticated = con.authenticateWithKeyboardInteractive(userName, new InteractiveCallback(){
@Override
public String[] replyToChallenge(String name, String instruction,
int numPrompts, String[] prompt, boolean[] echo)
throws Exception {
String[] result = new String[numPrompts];
for (int i=0; i < numPrompts;i++) {
result[i] = pwd;
}
return result;
}
});
} else if (con.isAuthMethodAvailable(userName,"publickey")) {
isAuthenticated = con.authenticateWithPublicKey(userName,new char[0], password);
} else {
isAuthenticated = con.authenticateWithPassword(userName, password);
}
if (!isAuthenticated) {
System.out.println(hostName+" Authentication failed.");
result.setStatus(false);
result.setErrMsg(hostName+" Authentication failed.");
return result;
}
session = con.openSession();
session.execCommand(command);
StringBuilder errsb = new StringBuilder();
InputStream stdErr = new StreamGobbler(session.getStderr());
BufferedReader reader = new BufferedReader(new InputStreamReader(stdErr));
while(true) {
String line = reader.readLine();
if (null == line) {
break;
}
errsb.append(line+"\n");
}
result.setErrMsg(errsb.toString());
StringBuilder successsb = new StringBuilder();
InputStream stdOut = new StreamGobbler(session.getStdout());
reader = new BufferedReader(new InputStreamReader(stdOut));
while(true) {
String line = reader.readLine();
if (null == line) {
break;
}
successsb.append(line+"\n");
}
result.setSuccessMsg(successsb.toString());
if (errsb.length() <= 0) {
result.setStatus(true);
} else {
result.setStatus(false);
}
}catch(IOException e) {
e.printStackTrace();
result.setStatus(false);
result.setErrMsg(e.getMessage());
return result;
}finally{
if (null != session) {
session.close();
session = null;
}
if (null != con) {
con.close();
con = null;
}
}
return result;
}
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
SshCommandUtil ssh = SshCommandUtil.getinstance();
Result result = ssh.exeCommand("10.0.31.231",22,"root","sugon123","cat /proc/cpuinfo");
System.out.println(result);
}
}