Java实现远程连接服务器并执行命令的方法

一.Apache sshd java实现远程连接服务器并执行命令的方法

先描述一下场景,本人在通信领域工作,暂时负责命令行这一块业务,公司使用apache sshd在Java应用中嵌入sshd服务,实现了通过SecureCRT等工具调用自定义的命令的功能,现想把这一套调用过程移植到web页面,通过接口实现命令的下发,网上查找了大量资料,好多资料年代比较久远,还是花了不少时间,最终实现了该功能。

思路如下:通过两个接口实现该功能,通过startClient启动客户端,实现客户端的连接,并用token作为唯一标识,把输入输出流保存在map中,map里的数据会在客户端断开时清除对应token的数据,客户端启动后,通过sendCommand下发命令,根据token从map中取出对应的流,通过流写入命令下发再从输出流里获取返回的结果,我在代码里写了一段while死循环,是为了保证结果已经完全写入到流里再获取结果,在获取结果前reset保证每次调用获取的都是当前命令下发后返回的结果,如果涉及分布式部署,可以把map中的数据放在redis中。

代码如下:

依赖:

<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-core</artifactId>
    <version>0.8.0</version>
</dependency>

 

package com.datang.demo.controller;

import com.datang.demo.model.ConnectionInfo;
import org.apache.sshd.ClientChannel;
import org.apache.sshd.ClientSession;
import org.apache.sshd.SshClient;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/sshd")
public class SSHController {

    Map<String, PipedOutputStream> inputMap = new HashMap<String, PipedOutputStream>();

    Map<String, ByteArrayOutputStream> outputMap = new HashMap<String, ByteArrayOutputStream>();

    /**
     * 启动客户端
     * @param connectionInfo
     */
    @PostMapping(value = "/startClient")
    public void startClient(@RequestBody ConnectionInfo connectionInfo){
        String host = connectionInfo.getHost();
        int port = connectionInfo.getPost();
        String username = connectionInfo.getUsername();
        String password = connectionInfo.getPassword();
        String token = connectionInfo.getToken();

        SshClient client = SshClient.setUpDefaultClient();
        client.start();
        try {
            ClientSession session = client.connect(host, port).await().getSession();
            if(session.authPassword(username, password).await().isSuccess()){
                ClientChannel channel = session.createShellChannel();
                PipedOutputStream pipedIn = new PipedOutputStream();
                channel.setIn(new PipedInputStream(pipedIn));
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                channel.setOut(out);
                ByteArrayOutputStream err = new ByteArrayOutputStream();
                channel.setErr(err);
                channel.open();
                inputMap.put(token, pipedIn);
                outputMap.put(token, out);
                channel.waitFor(ClientChannel.CLOSED, 0);
                inputMap.remove(token);
                outputMap.remove(token);
                channel.close(false);
                session.close(false);
                client.stop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 找到对应客户端并下发命令
     * @param connectionInfo
     */
    @PostMapping(value = "/sendCommand")
    public String sendCommand(@RequestBody ConnectionInfo connectionInfo)  {
        String command = connectionInfo.getCommand();
        String token = connectionInfo.getToken();
        PipedOutputStream pipedIn = inputMap.get(token);
        ByteArrayOutputStream out = outputMap.get(token);

        if(pipedIn != null && out != null){
            try {
                if(command != null){
                    pipedIn.write(command.getBytes());
                    pipedIn.flush();
                }
                while (true){
                    byte[] a = out.toByteArray();
                    Thread.sleep(500);
                    byte[] b = out.toByteArray();
                    if(b.length == a.length){
                        out.reset();
                        return new String(b, "GBK");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        return "";
    }
}

 

package com.datang.demo.model;

public class ConnectionInfo {

    // 服务端ip
    private String host;

    // 服务端端口
    private int post;

    // 用户名
    private String username;

    // 密码
    private String password;

    // 下发的命令
    private String command;

    // 每个客户端的唯一标识
    private String token;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPost() {
        return post;
    }

    public void setPost(int post) {
        this.post = post;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getCommand() {
        return command;
    }

    public void setCommand(String command) {
        this.command = command;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}

参考:

https://tangmingjie2009.iteye.com/blog/2037048

https://blog.csdn.net/jackie_xiaonan/article/details/8749035

https://blog.csdn.net/jackie_xiaonan/article/details/8907855 

二.Ganymed SSH-2 java实现远程连接服务器并执行命令的方法(Windows和Linux)

依赖: 

<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>262</version>
</dependency>

具体实现参考https://my.oschina.net/liuyuanyuangogo/blog/186159

  • 0
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现连接远程服务器执行命令,可以使用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”)。执行通道连接后,它从通道的输入流中读取输出并将其打印到控制台。最后,通道断开连接,并且会话关闭。 需要注意的是,这个示例代码中的密码是明文存储的,这是不安全的。在实际生产环境中,应该考虑使用密钥进行身份验证,而不是密码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值