java 通过ssh 执行命令

Wesley13
• 阅读 765

java 里面的开源 ssh lib

1、Jsch

2、SSHJ

JSCH 里面的概念

1、Linux OpenSSH 验证方式对应的 jsch auth method

/etc/sshd_config 文件中

# 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 文档中写到

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.

我们在使用jsch 的时候就要注意几点

//StrictHostKeyChecking 选项可用于控制对主机密钥未知或已更改的计算机的登录。
session.setConfig("StrictHostKeyChecking", "no");
//设置首选的Auth Method
session.setConfig("PreferredAuthentications","publickey,keyboard-interactive,password");

我们如果使用sshj 就可以这样

//调用 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();
        }
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
待兔 待兔
2星期前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Stella981 Stella981
2年前
Opencv中Mat矩阵相乘——点乘、dot、mul运算详解
Opencv中Mat矩阵相乘——点乘、dot、mul运算详解2016年09月02日00:00:36 \牧野(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fme.csdn.net%2Fdcrmg) 阅读数:59593
Stella981 Stella981
2年前
Appscan的下载安装
1、下载Appscan:http://download2.boulder.ibm.com...2AppScan\_Setup.exe(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fdownload2.boulder.ibm.com%2Fsar%2FCMA%2FRAA%2F00jq2
Wesley13 Wesley13
2年前
P2P技术揭秘.P2P网络技术原理与典型系统开发
Modular.Java(2009.06)\.Craig.Walls.文字版.pdf:http://www.t00y.com/file/59501950(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fwww.t00y.com%2Ffile%2F59501950)\More.E
Stella981 Stella981
2年前
Jenkins+Ansible+Gitlab自动化部署三剑客
JenkinsAnsibleGitlab自动化部署三剑客小中大showerlee2016031113:00Ansible(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fwww.
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Easter79 Easter79
2年前
Swift项目兼容Objective
!456.jpg(http://static.oschina.net/uploads/img/201509/13172704_1KcG.jpg"1433497731426906.jpg")本文是投稿文章,作者:一叶(博客(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2F00red
Easter79 Easter79
2年前
The Complete Guide To Rooting Any Android Phone
PhoneWhitsonGordon(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fwww.lifehacker.com.au%2Fauthor%2Fwhitsongordon%2F)7April,20118:00AMShare(https://ww
Stella981 Stella981
2年前
Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法
Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法参考文章:(1)Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.codeprj.com%2Fblo