jav a通过ssh调用程序

项目需要操控远程节点,在远程节点有脚本需要执行

package ssh;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class Sshd
{
    
    public static void main(String[] args) throws Exception
    {
        String charset = "UTF-8";
        String user = "root";
        String passwd = "111111";
        String host = "localhost";
        String command = "sh /root/shell/test.sh arg1 arg2 arg3";
        
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        
        channel.connect();
        InputStream in = channel.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
        String buf = null;
        while ((buf = reader.readLine()) != null)
        {
            System.out.println(buf);
        }
        reader.close();
        channel.disconnect();
        session.disconnect();
    }
    
}
原文地址:https://www.cnblogs.com/fangtest/p/3793815.html