import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.swing.JOptionPane;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class ExecSheelTool {
public static final int SSH2PORT = 22;
public static final int PASSWORD = 0;
public static final int PASSWORDVALIDTIMES = 0;
public static final int FILE = 1;
private static Session session;
private static Channel channel;
/**
*
* @param host 連接主機名
* @param port 連接端口
* @param username 連接用戶名
* @param auth 連接認證信息,當method爲0時,auth爲用戶密碼;但method爲1時,auth爲私鑰文件
* @param method 連接認證方式,0爲密碼認證,1爲私鑰文件認證
* @throws Exception 異常
*/
private static void getSession(String host, Integer port, String username, String auth, int method) throws Exception{
if(port == null){
port = SSH2PORT;
}
JSch jsch = new JSch();
if(method == FILE){
jsch.addIdentity(auth);
}
session = jsch.getSession(username, host, port);
if(method == PASSWORD){
int times = 0;
while(auth == null || "".equals(auth)){
auth = JOptionPane.showInputDialog("Please enter the password!");
times++;
if(times == PASSWORDVALIDTIMES){
throw new Exception();
}
}
session.setPassword(auth);
}
session.setTimeout(2000);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
}
private static void getChannel(String command) throws JSchException, IOException{
channel = session.openChannel("exec");
ChannelExec execChannel = (ChannelExec)channel;
execChannel.setCommand(command);
}
public static InputStream execute(String host, int port, String username, String password, String command, int method) throws Exception {
if(session == null){
getSession(host, port, username, password, method);
}
getChannel(command);
InputStream in = channel.getInputStream();
channel.connect();
return in;
}
/**
* 將輸入流轉化爲字符串
* @param is 輸入流
* @return 字符串
* @throws Exception 異常
*/
public static String toString(InputStream is) throws Exception {
StringBuffer sb = new StringBuffer();
int c = -1;
while((c = is.read()) != -1){
sb.append((char)c);
}
return sb.toString();
}
public static void release(){
if(session != null){
if(session.isConnected()){
session.disconnect();
}
}
if(channel != null){
if(channel.isConnected()){
channel.disconnect();
}
}
}
}