Java使用Jsch执行Shell命令

发布时间 2023-08-27 10:28:01作者: 我不是萌新

JSch是SSH2的纯Java实现 。

JSch允许您连接到sshd服务器并使用端口转发,X11转发,文件传输等,您可以将其功能集成到您自己的Java程序中。JSch获得BSD格式许可证。

最初,我们开发这些东西的动机是允许我们的纯Java X服务器 WiredX的用户享受安全的X会话。所以,我们的努力主要是为了实现用于X11转发的SSH2协议。当然,我们现在也有兴趣添加端口转发,文件传输,终端仿真等其他功能。

官网上有很详细说明和例子:

官网:http://www.jcraft.com/jsch/

下面记两种执行命令的方式,仅作为备忘:

import com.jcraft.jsch.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class SSH {
    private static final String USER = "mengxin";
    private static final String PASSWORD = "*****";
    private static final String HOST = "172.16.0.128";
    private static final int DEFAULT_SSH_PORT = 22;

    public static void main(String[] arg) {
        Session session = null;
        Channel channel = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(USER, HOST, DEFAULT_SSH_PORT);
            session.setPassword(PASSWORD);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(30000);   // making a connection with timeout.
            channel = session.openChannel("shell");
            channel.setInputStream(System.in);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            channel.setOutputStream(baos);
            channel.connect(3 * 1000);
            System.out.println(baos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("finally...");
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}

import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

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

public class SSH {
    public static void main(String[] args) throws Exception{
        SSH sshUtil = new SSH("172.16.0.128", "mengxin", "******");

        String res = sshUtil.runShell("ip add\n", "utf-8");
        System.out.println(res);
        sshUtil.close();
    }
    private Channel channel;
    private Session session = null;
    private int timeout = 60000;

    public SSH(final String ipAddress, final String username, final String password) throws Exception {

        JSch jsch = new JSch();
        this.session = jsch.getSession(username, ipAddress, 22);
        this.session.setPassword(password);
        this.session.setConfig("StrictHostKeyChecking", "no");
        this.session.setTimeout(this.timeout);
        this.session.connect();
        this.channel = this.session.openChannel("shell");
        this.channel.connect(1000);
    }

    public String runShell(String cmd, String charset) throws Exception {
        String temp = null;

        InputStream instream = null;
        OutputStream outstream = null;
        try {
            instream = this.channel.getInputStream();
            outstream = this.channel.getOutputStream();
            outstream.write(cmd.getBytes(charset));
            outstream.flush();
            TimeUnit.SECONDS.sleep(2);
            if (instream.available() > 0) {
                byte[] data = new byte[instream.available()];
                int nLen = instream.read(data);

                if (nLen < 0) {
                    throw new Exception("network error...桌面有错误");
                }

                temp = new String(data, 0, nLen, "UTF-8");
            }
        }  finally {
            if (outstream != null) {
                outstream.close();
            }
            if (instream != null) {
                instream.close();
            }
        }
        return temp;
    }

    public void close() {
        this.channel.disconnect();
        this.session.disconnect();
    }
}