`
-Jan-sep-
  • 浏览: 11217 次
  • 性别: Icon_minigender_1
  • 来自: 石家庄
社区版块
存档分类
最新评论

远程调用其他主机sh脚本工具

阅读更多
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.n3r.quartz.glass.log.joblog.JobLogs;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by jansep_wangcx on 2018/5/31
 * 远程调用其他主机sh脚本工具
 */

public class ShToOtherUtil {

    /**
     *
     * @param ip
     * @param name
     * @param pass
     * @param port 端口,默认22
     * @param shpath sh脚本地址
     * @return
     */
    public static boolean ExeShell(String ip,String name,String pass,
                                   int port,String shpath){

        try{
            Session session = null;
            JSch jsch = new JSch(); // 创建JSch对象
            if(port==22){
                session = jsch.getSession(name, ip);
            }else{
                session = jsch.getSession(name, ip,port);
            }

            session.setPassword(pass);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
          //  session.connect(30000);
            session.connect();

            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand("sh " + shpath);
            channelExec.setInputStream(null);
            channelExec.setErrStream(System.err);
            channelExec.connect();

            BufferedReader input = new BufferedReader(new InputStreamReader(channelExec
                    .getInputStream()));


            String line;
            while ((line = input.readLine()) != null) {
                JobLogs.info("InputStream:"+line);
            }

        }catch (JSchException e) {
            JobLogs.error("ssh连接出错",e);
            return false;
        }catch (IOException e) {
            JobLogs.error("sh脚本执行出错",e);
            return false;
        }


        return true;
    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics