Jsch执行交互式命令

用Jsch写个SSH小工具,被朋友吐槽,用ansible就好了,干嘛要用java去做批量的机器控制,ansible确实不错,但是不知道该怎么进行应用集成,我的定位ansible他是一个运维工具,并不能实现我的需求,所以自己用java写个。讲个直白点的例子,你程序中做ftp上传,你会去调用ansible吗,这不可能啊。但是你可以用jsch的sftp来做,apache也是这么做的。可以参考下:commons-vfs2-2.0.jar:SftpFileProvider

package com.qimo.omsa.demo;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO
 * @Author 姚仲杰#80998699
 * @Date 2021/5/15 13:02
 */
public class SSH {
    
    private Session session;
    private ChannelShell shell;
    private String username = "root";
    private String host = "127.0.0.1";
    private String password = "xxxxxx";
    
    public SSH(String username, String host, String password) {
        this.username = username;
        this.host = host;
        this.password = password;
    }
    public Session getSession(){
        return this.session;
    }
    public void connect() {
        JSch ssh = new JSch();
        try {
            this.session = ssh.getSession(this.username, this.host);
            this.session.setPassword(this.password);
            this.session.setServerAliveCountMax(0);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            this.session.connect(30000);
            UserInfo user = new RootUser();
            this.session.setUserInfo(user);
            System.out.println("连接成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public int shellCmd(String... cmds) {
        ChannelShell channel = null;
        InputStream in = null;
        OutputStream os = null;
        int returnCode = -1;
        try {
            System.out.println("执行如下命令:\n" + String.join("\n", cmds));
            channel = (ChannelShell) session.openChannel("shell");
            in = channel.getInputStream();
            channel.setPty(true);
            channel.connect();
            os = channel.getOutputStream();
            for (String cmd : cmds) {
                os.write((cmd + "\r\n").getBytes());
                os.flush();
                TimeUnit.SECONDS.sleep(2);
            }
            os.write(("exit" + "\r\n").getBytes());
            os.flush();
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) {
                        break;
                    }
                    System.out.println(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    if (in.available() > 0) {
                        continue;
                    }
                    returnCode = channel.getExitStatus();
                    System.out.println("exit-status: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                os.close();
                in.close();
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            channel.disconnect();
        }
        return returnCode;
    }
    //测试
    public static void main(String[] args) throws Exception {
        SSH ssh = new SSH("root", "10.189.0.10.", "123456");
        ssh.connect();
        String[] cmds=new String[]{
			"cd /home"
			,"netstat -nltp"
			,"ls"
		}
    }
}

以上代码是通过代码交互,当然你也可以通过控制台进行交互,只需要重定向channel的输入输出流即可,如下:

channel.setInputStream(System.in);
channel.setOutputStream(System.out);
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值