概念:JSch是SSH2的纯Java实现。JSch允许连接到sshd服务器并使用端口转发,X11转发,文件传输等,并且可以将其功能集成到您自己的Java程序中。

说白了就是以java的方式通过jsch连接,来对服务器进行操作。

maven地址:

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.55</version>
    </dependency>

1.以shell交互式的命令操作

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
/**
 * @Description todo
 * @Author Administrator
 * @Date 2019/11/15 9:59
 **/
public class TestSqoop {
    private static final String USER="root";
    private static final String PASSWORD="";
    private static final String HOST="";
    private static final int DEFAULT_SSH_PORT=22;
    public static void main(String[] arg){
        try{
            JSch jsch=new JSch();
            Session session = jsch.getSession(USER,HOST,DEFAULT_SSH_PORT);
            session.setPassword(PASSWORD);

            UserInfo userInfo = new UserInfo() {
                public String getPassphrase() {
                    System.out.println("getPassphrase");
                    return null;
                }
                public String getPassword() {
                    System.out.println("getPassword");
                    return null;
                }
                public boolean promptPassword(String s) {
                    System.out.println("promptPassword:"+s);
                    return false;
                }
                public boolean promptPassphrase(String s) {
                    System.out.println("promptPassphrase:"+s);
                    return false;
                }
                public boolean promptYesNo(String s) {
                    System.out.println("promptYesNo:"+s);
                    return true;//notice here!
                }
                public void showMessage(String s) {
                    System.out.println("showMessage:"+s);
                }
            };
            session.setUserInfo(userInfo);
            session.connect(30000);   // making a connection with timeout.
            Channel channel=session.openChannel("shell");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            //channel.connect();
            channel.connect(3*1000);
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

2.以脚本文件的形式,实现的是一个sqoop抽取数据转到hive的作用

import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Vector;
/**
 * @Description todo
 * @Author Administrator
 * @Date 2019/11/15 11:12
 **/
public class TestSqoop2 {
    private String ipAddress;
    private String username;
    private String password;
    public static final int DEFAULT_SSH_PORT = 22;
    private Vector<String> stdout;
    public TestSqoop2(final String ipAddress, final String username, final String password) {
        this.ipAddress = ipAddress;
        this.username = username;
        this.password = password;
        stdout = new Vector<String>();
    }
    public int execute(final String command) {
        int returnCode = 0;
        JSch jsch = new JSch();
        MyUserInfo userInfo = new MyUserInfo();
        try {
            // Create and connect session.
            Session session = jsch.getSession(username, ipAddress, DEFAULT_SSH_PORT);
            session.setPassword(password);
            session.setUserInfo(userInfo);
            session.connect();
            // Create and connect channel.
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader(channel
                    .getInputStream()));
            channel.connect();
            System.out.println("The remote command is: " + command);

            // Get the output of remote command.
            String line;
            while ((line = input.readLine()) != null) {
                stdout.add(line);
            }
            input.close();
            // Get the return code only after the channel is closed.
            if (channel.isClosed()) {
                returnCode = channel.getExitStatus();
            }
            // Disconnect the channel and session.
            channel.disconnect();
            session.disconnect();
        } catch (JSchException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnCode;
    }

    public Vector<String> getStandardOutput() {
        return stdout;
    }

    public static void main(final String [] args) {
        TestSqoop2 sshExecutor = new TestSqoop2("", "root", "");
        sshExecutor.execute("sudo -u hdfs \\\n" +
                "sqoop import \\\n" +
                "--connect 'jdbc:sqlserver://192.168.0.20:1433;username=SA;password=;database=test' \\\n" +
                "--hive-import \\\n" +
                "--hive-database default \\\n" +
                "--hive-table k \\\n" +
                "--query 'select x1.name,x1.score,x2.subject from x1 left join x2 on x1.tid=x2.id  and $CONDITIONS' \\\n" +
                "--target-dir /usr/3 \\\n" +
                "-m 1");
        Vector<String> stdout = sshExecutor.getStandardOutput();
        for (String str : stdout) {
            System.out.println(str);
        }
    }
}

自定义的userInfo类

import com.jcraft.jsch.UserInfo;

/**
 * @Description todo
 * @Author Administrator
 * @Date 2019/11/15 11:35
 **/
public class MyUserInfo implements UserInfo {
    private String password;
    private String passphrase;
    public String getPassphrase() {
        System.out.println("MyUserInfo.getPassphrase()");
        return null;
    }
    public String getPassword() {
        System.out.println("MyUserInfo.getPassword()");
        return null;
    }
    public boolean promptPassphrase(final String arg0) {
        System.out.println("MyUserInfo.promptPassphrase()");
        System.out.println(arg0);
        return false;
    }
    public boolean promptPassword(final String arg0) {
        System.out.println("MyUserInfo.promptPassword()");
        System.out.println(arg0);
        return false;
    }
    public boolean promptYesNo(final String arg0) {
        System.out.println("MyUserInfo.promptYesNo()");
        System.out.println(arg0);
        if (arg0.contains("The authenticity of host")) {
            return true;
        }
        return false;
    }
    public void showMessage(final String arg0) {
        System.out.println("MyUserInfo.showMessage()");
    }
}