java 經過ssh 執行命令

java 裏面的開源 ssh lib

一、Jschjava

二、SSHJlinux

JSCH 裏面的概念

一、Linux OpenSSH 驗證方式對應的 jsch auth method

/etc/sshd_config 文件中git

# Authentication:
PubkeyAuthentication         //對應的是 publickey 公鑰認證
PasswordAuthentication yes   //對應的是 password 密碼驗證
ChallengeResponseAuthentication yes  //對應的是 keyboard-interactive 鍵盤交互

# Kerberos options             
KerberosAuthentication yes  //對應的是kerberos 驗證
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
GSSAPIAuthentication yes   //對應的 gssapi-with-mic 驗證
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

OpenSHH 文檔中寫到github

The methods available for authentication are: GSSAPI-based authentication, host-based authentication, public key authentication, challenge-response authentication, and password authentication. Authentication methods are tried in the order specified above, thoughPreferredAuthentications can be used to change the default order.shell

咱們在使用jsch 的時候就要注意幾點api

//StrictHostKeyChecking 選項可用於控制對主機密鑰未知或已更改的計算機的登陸。
session.setConfig("StrictHostKeyChecking", "no");
//設置首選的Auth Method
session.setConfig("PreferredAuthentications","publickey,keyboard-interactive,password");

咱們若是使用sshj 就能夠這樣bash

//調用 sshClient 的這個方法,裏面能夠實現多個驗證方式
public void auth(String username, AuthMethod... methods)
            throws UserAuthException, TransportException {
        checkConnected();
        auth(username, Arrays.<AuthMethod>asList(methods));
    }
//例子
 		DefaultConfig defaultConfig = new DefaultConfig();
        final SSHClient client = new SSHClient(defaultConfig);
        String host = "127.0.0.1";
        String user = "king";
        String password = "123456";
        client.setTimeout(60000);
        client.loadKnownHosts();
        client.addHostKeyVerifier(new PromiscuousVerifier());
        client.connect(host);
        PasswordFinder pwdf = PasswordUtils.createOneOff(password.toCharArray());
        PasswordResponseProvider provider = new PasswordResponseProvider(pwdf);
		//鍵盤交互
        AuthKeyboardInteractive authKeyboardInteractive = new AuthKeyboardInteractive(provider);
		//密碼驗證
        AuthPassword authPassword = new AuthPassword(pwdf);
        client.auth(user, authKeyboardInteractive, authPassword);

jsch 例子

JSch jSch = new JSch();
		//設置JSch 的日誌,能夠看到具體日誌信息
        JSch.setLogger(new Logger() {
            @Override
            public boolean isEnabled(int level) {
                return true;
            }
            @Override
            public void log(int level, String message) {
                System.out.println("logger:" + message);
            }
        });
        com.jcraft.jsch.Session session = jSch.getSession("king", "127.0.0.1");
        session.setPassword("123456");
		//忽略第一次鏈接時候 hostkey 檢查
        session.setConfig("StrictHostKeyChecking", "no");
        //設置首選的身份驗證方式
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        session.connect(60000);
		//開啓shell,shell 具備上下文交互,執行命令不會立刻退出
        ChannelShell shell = (ChannelShell) session.openChannel("shell");
		//開始 exec 相似linux bash -c exec 執行完命令立刻退出
        //ChannelExec exec = (ChannelExec)session.openChannel("exec");
        //exec.setCommand("");
        shell.setPtyType("dumb");
        shell.setPty(true);
        shell.connect(60000);
        boolean connected = shell.isConnected();
        OutputStream outputStream = shell.getOutputStream();
        InputStream inputStream = shell.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
		//經過流寫入命令
        outputStream.write("pwd\n cd /home\nls\npwd\n".getBytes());
        outputStream.flush();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }

sshj 例子

DefaultConfig defaultConfig = new DefaultConfig();
        final SSHClient client = new SSHClient(defaultConfig);
        String host = "127.0.0.1";
        String user = "king";
        String password = "123456";
        client.setTimeout(60000);
        client.loadKnownHosts();
        client.addHostKeyVerifier(new PromiscuousVerifier());
        client.connect(host);
        try {
            client.authPassword(user, password);
            final SessionChannel session = (SessionChannel) client.startSession();
            session.allocateDefaultPTY();
			//這裏的session 相似 jsch 裏面的exec ,能夠直接執行命令。
			//session.exec("pwd");
            SessionChannel shell = (SessionChannel) session.startShell();
            try {
                OutputStream outputStream = shell.getOutputStream();
                outputStream.write("pwd\n".getBytes());
                outputStream.flush();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(shell.getInputStream(), "utf-8"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            client.disconnect();
        }
相關文章
相關標籤/搜索