欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-29 20:26:56
...
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;
    }

}

 

相关标签: java 脚本 ssh