java使用jsch连接ssh服务并远程执行命令、上传、下载操作

java使用jsch连接ssh服务并远程执行命令、上传、下载操作

关键依赖:jsch-0.1.54.jar

第一,使用用户名和密码连接
	/**
     * 使用用户名和密码连接
     */
    @Test
    public void test1() throws JSchException {
        //创建一个ssh通讯核心类
        JSch jSch = new JSch();

        //传主机、端口、用户名获得一个会话
        Session session = jSch.getSession("admin", "your host", 22);

        //不进行严格模式检查
        Properties config = new Properties();
        config.put("StrictHostKeyChecking","no");

        //设置密码
        session.setPassword("your password");
        session.setConfig(config);

        //连接会话
        session.connect();

        log.debug("是否连接:" + session.isConnected());
        log.debug("会话:" + session);

        //断开连接
        session.disconnect();

        log.debug("是否连接:" + session.isConnected());

    }

在这里插入图片描述

第二,使用用户名和密钥连接
	/**
     * 使用用户名和私钥连接
     * @throws JSchException
     */
    @Test
    public void test2() throws JSchException {
        //创建一个ssh通讯核心类
        JSch jSch = new JSch();

        //设置私钥路径
        jSch.addIdentity("D:\\hehui\\jsch\\admin_private.ppk");

        //传主机、端口、用户名获得一个会话
        Session session = jSch.getSession("admin", "your host", 22);

        //不进行严格模式检查
        Properties config = new Properties();
        config.put("StrictHostKeyChecking","no");

        session.setConfig(config);

        //连接会话
        session.connect();

        log.debug("是否连接:" + session.isConnected());
        log.debug("会话:" + session);

        //断开连接
        session.disconnect();

        log.debug("是否连接:" + session.isConnected());

    }

在这里插入图片描述

第三,远程执行命令
	/**
     * 远程执行命令
     * @throws JSchException
     * @throws IOException
     */
    @Test
    public void test3() throws JSchException, IOException {

        log.debug("会话:\r\n" + session);

        ChannelExec channelExec = (ChannelExec)session.openChannel("exec");

        channelExec.setCommand("df -h");
        channelExec.connect();

        InputStream inputStream = channelExec.getInputStream();

        //命令执行结果
        String result = IOUtils.toString(inputStream);

        log.debug("执行结果:\r\n" + result);

    }

在这里插入图片描述
在这里插入图片描述

第四,文件上传
	/**
     * 文件上传
     */
    @Test
    public void test4() {
        try {
            //使用ssh会话开启一个sftp文件传输的通道,Channel为抽象类
            Channel channel = session.openChannel("sftp");

            //强转为ChannelSftp
            ChannelSftp channelSftp = (ChannelSftp) channel;

            //连接该通道
            channelSftp.connect();

            String filePath = "D:\\hehui\\jsch\\apache-tomcat-9.0.35.tar.gz";

            String fileName = "apache-tomcat-9.0.35.tar.gz";

            //服务文件夹路径,只支持绝对路径
            String serverDir = "/home/admin/jsch/";

            AtomicReference<String> dir = new AtomicReference<>("/");

            Stream.of(serverDir.split("\\/")).forEach(p -> {
                try {
                    if (StringUtils.isNotEmpty(p)) {
                        String existDir = dir.get();
                        if (StringUtils.equals(existDir,"/")) {
                            dir.set(existDir + p);
                        } else {
                            dir.set(existDir + "/" + p);
                        }
                        channelSftp.cd(dir.get());
                    }

                } catch (SftpException e1) {
                    log.debug("创建目录:" + p);
                    try {
                        channelSftp.mkdir(dir.get());
                        channelSftp.cd(dir.get());
                    } catch (SftpException e2) {
                        log.error("error:",e2);
                        throw new RuntimeException(e2);
                    }
                }
            });

            FileInputStream in = new FileInputStream(filePath);

            //上传
            channelSftp.put(in,fileName);

            //关闭传输通道
            channelSftp.disconnect();

        } catch (JSchException e) {
            log.error("error",e);
        } catch (FileNotFoundException e) {
            log.error("error:",e);
        } catch (SftpException e) {
            log.error("error",e);
        }
    }

在这里插入图片描述
在这里插入图片描述

第五,文件下载
	/**
     * 文件下载
     */
    @Test
    public void test5(){
        try {
            //使用ssh会话开启一个sftp文件传输的通道,Channel为抽象类
            Channel channel = session.openChannel("sftp");

            //强转为ChannelSftp
            ChannelSftp channelSftp = (ChannelSftp) channel;

            //连接该通道
            channelSftp.connect();

            String serverDir = "/home/admin/jsch/";
            String serverFile = "apache-tomcat-9.0.35.tar.gz";

            FileOutputStream out = new FileOutputStream("D:\\hehui\\jsch\\apache-tomcat-9.0.35_download.tar.gz");

            channelSftp.cd(serverDir);

            channelSftp.get(serverFile,out);

            //关闭通道
            channelSftp.disconnect();

        } catch (JSchException e) {
            log.error("error:",e);
        } catch (FileNotFoundException e) {
            log.error("error:",e);
        } catch (SftpException e) {
            log.error("error:",e);
        }
    }

在这里插入图片描述
在这里插入图片描述

全部Demo

package com.day0707;

import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;

/**
 * JSch(java ssh channel)java连接ssh服务示例
 * 远程执行命令、上传、下载
 * @author hehui
 * @date 2020/7/7
 */
public class JSchDemo {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private Session session = null;

    @Before
    public void open() throws JSchException {
        log.debug("开启会话");
        //创建一个ssh通讯核心类
        JSch jSch = new JSch();

        //设置私钥路径
        jSch.addIdentity("D:\\hehui\\jsch\\admin_private.ppk");

        //传主机、端口、用户名获得一个会话
        Session session = jSch.getSession("admin", "your host", 22);

        //不进行严格模式检查
        Properties config = new Properties();
        config.put("StrictHostKeyChecking","no");

        session.setConfig(config);

        //连接会话
        session.connect();

        this.session = session;
    }

    @After
    public void close(){
        log.debug("关闭会话");
        //关闭连接
        this.session.disconnect();
    }

    /**
     * 使用用户名和密码连接
     */
    @Test
    public void test1() throws JSchException {
        //创建一个ssh通讯核心类
        JSch jSch = new JSch();

        //传主机、端口、用户名获得一个会话
        Session session = jSch.getSession("admin", "your host", 22);

        //不进行严格模式检查
        Properties config = new Properties();
        config.put("StrictHostKeyChecking","no");

        //设置密码
        session.setPassword("your password");
        session.setConfig(config);

        //连接会话
        session.connect();

        log.debug("是否连接:" + session.isConnected());
        log.debug("会话:" + session);

        //断开连接
        session.disconnect();

        log.debug("是否连接:" + session.isConnected());

    }

    /**
     * 使用用户名和私钥连接
     * @throws JSchException
     */
    @Test
    public void test2() throws JSchException {
        //创建一个ssh通讯核心类
        JSch jSch = new JSch();

        //设置私钥路径
        jSch.addIdentity("D:\\hehui\\jsch\\admin_private.ppk");

        //传主机、端口、用户名获得一个会话
        Session session = jSch.getSession("admin", "your host", 22);

        //不进行严格模式检查
        Properties config = new Properties();
        config.put("StrictHostKeyChecking","no");

        session.setConfig(config);

        //连接会话
        session.connect();

        log.debug("是否连接:" + session.isConnected());
        log.debug("会话:" + session);

        //断开连接
        session.disconnect();

        log.debug("是否连接:" + session.isConnected());

    }

    /**
     * 远程执行命令
     * @throws JSchException
     * @throws IOException
     */
    @Test
    public void test3() throws JSchException, IOException {

        log.debug("会话:\r\n" + session);

        ChannelExec channelExec = (ChannelExec)session.openChannel("exec");

        channelExec.setCommand("df -h");
        channelExec.connect();

        InputStream inputStream = channelExec.getInputStream();

        //命令执行结果
        String result = IOUtils.toString(inputStream);

        log.debug("执行结果:\r\n" + result);

    }

    /**
     * 文件上传
     */
    @Test
    public void test4() {
        try {
            //使用ssh会话开启一个sftp文件传输的通道,Channel为抽象类
            Channel channel = session.openChannel("sftp");

            //强转为ChannelSftp
            ChannelSftp channelSftp = (ChannelSftp) channel;

            //连接该通道
            channelSftp.connect();

            String filePath = "D:\\hehui\\jsch\\apache-tomcat-9.0.35.tar.gz";

            String fileName = "apache-tomcat-9.0.35.tar.gz";

            //服务文件夹路径,只支持绝对路径
            String serverDir = "/home/admin/jsch/";

            AtomicReference<String> dir = new AtomicReference<>("/");

            Stream.of(serverDir.split("\\/")).forEach(p -> {
                try {
                    if (StringUtils.isNotEmpty(p)) {
                        String existDir = dir.get();
                        if (StringUtils.equals(existDir,"/")) {
                            dir.set(existDir + p);
                        } else {
                            dir.set(existDir + "/" + p);
                        }
                        channelSftp.cd(dir.get());
                    }

                } catch (SftpException e1) {
                    log.debug("创建目录:" + p);
                    try {
                        channelSftp.mkdir(dir.get());
                        channelSftp.cd(dir.get());
                    } catch (SftpException e2) {
                        log.error("error:",e2);
                        throw new RuntimeException(e2);
                    }
                }
            });

            FileInputStream in = new FileInputStream(filePath);

            //上传
            channelSftp.put(in,fileName);

            //关闭传输通道
            channelSftp.disconnect();

        } catch (JSchException e) {
            log.error("error",e);
        } catch (FileNotFoundException e) {
            log.error("error:",e);
        } catch (SftpException e) {
            log.error("error",e);
        }
    }

    /**
     * 文件下载
     */
    @Test
    public void test5(){
        try {
            //使用ssh会话开启一个sftp文件传输的通道,Channel为抽象类
            Channel channel = session.openChannel("sftp");

            //强转为ChannelSftp
            ChannelSftp channelSftp = (ChannelSftp) channel;

            //连接该通道
            channelSftp.connect();

            String serverDir = "/home/admin/jsch/";
            String serverFile = "apache-tomcat-9.0.35.tar.gz";

            FileOutputStream out = new FileOutputStream("D:\\hehui\\jsch\\apache-tomcat-9.0.35_download.tar.gz");

            channelSftp.cd(serverDir);

            channelSftp.get(serverFile,out);

            //关闭通道
            channelSftp.disconnect();

        } catch (JSchException e) {
            log.error("error:",e);
        } catch (FileNotFoundException e) {
            log.error("error:",e);
        } catch (SftpException e) {
            log.error("error:",e);
        }
    }

}

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现连接远程服务器并执行命令,可以使用Java中的SSH协议。SSH(Secure Shell)是一种加密网络协议,可用于安全地连接远程服务器并执行命令Java中有一些SSH库可以用来实现这个功能,比如JSch和Apache Mina SSHD。下面是一个使用JSch的示例代码: ```java import com.jcraft.jsch.*; public class SSHConnection { public static void main(String[] args) { String host = "remotehost.com"; String user = "username"; String password = "password"; try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec)channel).setCommand("ls -la"); channel.setInputStream(null); ((ChannelExec)channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; System.out.print(new String(tmp, 0, i)); } if (channel.isClosed()) { if (in.available() > 0) continue; System.out.println("exit-status: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception e) {} } channel.disconnect(); session.disconnect(); } catch (JSchException | IOException e) { e.printStackTrace(); } } } ``` 这个代码片段使用JSch创建一个SSH会话,并通过该会话连接远程主机。然后它打开一个执行通道并设置要执行的命令(在这个例子中是“ls -la”)。执行通道连接后,它从通道的输入流中读取输出并将其打印到控制台。最后,通道断开连接,并且会话关闭。 需要注意的是,这个示例代码中的密码是明文存储的,这是不安全的。在实际生产环境中,应该考虑使用密钥进行身份验证,而不是密码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值