还不会用Java操作远程服务器?

JSch 是一个纯 Java 实现的 SSH2 客户端库,它允许 Java 应用程序通过 SSH 协议连接到 SSH 服务器,并执行命令、传输文件等。
首页 新闻资讯 行业资讯 还不会用Java操作远程服务器?

java操作服务器

JSch 是一个纯 Java 实现的 SSH2 客户端库,它允许 Java 应用程序通过 SSH 协议连接到 SSH 服务器,并执行命令、传输文件等。JSch 是基于 SSH-2 协议的一个开源项目,广泛用于需要远程执行命令或文件传输的 Java 应用程序中。

主要特点

  • 纯 Java 实现:不依赖于任何本地库或第三方工具,完全用 Java 编写,因此具有很好的跨平台性。

  • SSH2 协议支持:支持 SSH-2 协议,包括密钥认证、密码认证、公钥认证等多种认证方式。

  • 命令执行:允许通过 SSH 连接执行远程命令,并获取命令的输出结果。

  • 文件传输:支持 SFTP(SSH File Transfer Protocol)协议,用于在客户端和服务器之间安全地传输文件。

  • 端口转发:支持本地端口转发和远程端口转发,可以用于创建安全的隧道。

  • 会话管理:提供会话管理功能,包括会话的创建、认证、关闭等。

使用场景

  • 自动化部署:在自动化部署脚本中,使用 JSch 连接到远程服务器,执行部署命令。

  • 远程监控:通过 SSH 连接远程服务器,执行监控命令,并获取监控数据。

  • 文件同步:使用 SFTP 协议安全地同步文件到远程服务器或从远程服务器下载文件。

  • 远程执行脚本:在远程服务器上执行脚本或程序,并获取执行结果。

引入依赖

<dependency><groupId>com.github.mwiede</groupId><artifactId>jsch</artifactId><version>0.2.19</version></dependency>

创建连接

获取会话

publicSessiongetSession(){if(this.session!=null){returnthis.session;}
        try {
            jsch.getSession(property.getUsername(),property.getHost(),property.getPort());session=jsch.getSession(property.getUsername(),property.getHost(),property.getPort());session.setPassword(property.getPassword());session.setConfig("StrictHostKeyChecking","no");// 设置第一次登陆的时候提示session.setConfig("max_input_buffer_size","1024");//Properties sshConfig=new Properties();sshConfig.put("StrictHostKeyChecking","no");session.setConfig(sshConfig);session.connect();returnsession;} catch(JSchException e){
            throw new RuntimeException(e);}
    }

获取Sftp连接

publicstatic ChannelSftp getSftp(Sessionsession){
        try {
            Channel channel=session.openChannel("sftp");channel.connect();ChannelSftp sftp=(ChannelSftp)channel;sftp.setFilenameEncoding("UTF-8");returnsftp;} catch(Exception e){
            throw new RuntimeException(e);}
    }

获取命令执行连接

publicstatic ChannelExec getExec(Sessionsession){
        try {
            Channel channel=session.openChannel("exec");//            channel.connect();ChannelExecexec=(ChannelExec)channel;returnexec;} catch(Exception e){
            throw new RuntimeException(e);}
    }

执行脚本

publicstatic void execCommand(ChannelExecexec,String command){
        try {exec.setCommand(command);InputStreamin=exec.getInputStream();exec.connect();BufferedReader inputReader=new BufferedReader(new InputStreamReader(in,"UTF8"));String inputLine;while((inputLine=inputReader.readLine())!=null){
                System.out.println(inputLine);}
        } catch(Exception e){
            throw new RuntimeException(e);} finally {exec.disconnect();}
    }

执行文件下载

publicstatic void fileDownload(ChannelSftp sftp,String path,String dist){
        try {
            InputStreamis=sftp.get(path);FileUtils.copyInputStreamToFile(is,FileUtils.getFile(dist,FilenameUtils.getName(path)));is.close();} catch(SftpException e){
            e.printStackTrace();} catch(IOException e){
            e.printStackTrace();}
    }

测试

获取会话

publicstaticSessiongetSession(){
    ConnectProperty property=new ConnectProperty();property.setHost("...");property.setPort(22);property.setUsername("...");property.setPassword("...");ConnectHelper helper=new ConnectHelper(property);returnhelper.getSession();}

下载文件

publicstatic void download(Sessionsession){
    ChannelSftp sftp=ConnectHelper.getSftp(session);ConnectHelper.fileDownload(sftp,"/home/test/1.txt","E:\\home\\tmp");}

执行命令

public static void execCommand(Session session){
    ChannelExec exec = ConnectHelper.getExec(session);
    ConnectHelper.execCommand(exec, "pwd");