使用java执行linux的sheel命令

来源:互联网 发布:数据为王颠覆营销 编辑:程序博客网 时间:2024/05/16 01:47

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();
   }
  }
 }
}

原创粉丝点击