通过java接口实现远程控制服务器

11 篇文章 0 订阅
10 篇文章 0 订阅

通过java接口实现远程控制服务器

这里是在一个springboot项目中实现的
maven配置中增加几个引用

<dependency>
	<groupId>ch.ethz.ganymed</groupId>
	<artifactId>ganymed-ssh2</artifactId>
	<version>262</version>
</dependency>
<dependency>
	<groupId>commons-io</groupId>  
	<artifactId>commons-io</artifactId>  
	<version>2.7</version>  
	<type>jar</type>  
	<scope>compile</scope>  
</dependency>  
<dependency>  
	<groupId>commons-lang</groupId>  
	<artifactId>commons-lang</artifactId>  
	<version>2.6</version>  
	<type>jar</type>  
	<scope>compile</scope>  
</dependency>

创建一个controller类


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

@RestController
@RequestMapping("/system")
public class PoweroffController {

    private static final Logger log = LoggerFactory.getLogger(PoweroffController.class);
    private static String DEFAULTCHART = "UTF-8";

    @RequestMapping("/poweroff")
    public String poweroff(String ip, String userName, String userPwd, String cmd) {
    	// 连接主机
        Connection conn = this.login(ip, userName, userPwd);
        String result = this.execute(conn, cmd);
        return result;
    }

    /**
     * 登录主机
     * 
     * @return 登录成功返回true,否则返回false
     */
    public Connection login(String ip, String userName, String userPwd) {
        boolean flg = false;
        Connection conn = null;
        try {
            conn = new Connection(ip);
            conn.connect();// 连接
            flg = conn.authenticateWithPassword(userName, userPwd);// 认证
            if (flg) {
                log.info("=========登录成功=========" + conn);
                return conn;
            }
        } catch (IOException e) {
            log.error("=========登录失败=========" + e.getMessage());
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 远程执行shll脚本或者命令
     * 
     * @param cmd 即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    public String execute(Connection conn, String cmd) {
        String result = "";
        try {
            if (conn != null) {
                Session session = conn.openSession();// 打开一个会话
                session.execCommand(cmd);// 执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                // 如果为得到标准输出为空,说明脚本执行出错了
                if (StringUtils.isBlank(result)) {
                    log.info("得到标准输出为空,链接conn:" + conn + ",执行的命令:" + cmd);
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                } else {
                    log.info("执行命令成功,链接conn:" + conn + ",执行的命令:" + cmd);
                }
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            log.info("执行命令失败,链接conn:" + conn + ",执行的命令:" + cmd + "  " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     * 
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     */
    private String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
        } catch (UnsupportedEncodingException e) {
            log.error("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }
}

这就可以了, 足够了
之所以需要配置ip,username,userpwd这几个字段, 主要是为了灵活, 如果在代码中固定设置了ip, 那么只能操作一个服务器, 这样动态的ip地址, 让用户可以尽可能多的操作服务器

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以用于实现远程控制,具体实现方式可以采用Socket编程或者RMI(远程方法调用)技术。以下是一些简单的示例代码: 使用Socket编程实现远程控制: ```java // 服务端代码 import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("等待客户端连接..."); Socket socket = serverSocket.accept(); System.out.println("客户端已连接:" + socket.getInetAddress()); ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); while (true) { String message = (String) in.readObject(); if ("exit".equalsIgnoreCase(message)) { break; } System.out.println("收到客户端消息:" + message); out.writeObject("服务端已收到消息:" + message); } in.close(); out.close(); socket.close(); serverSocket.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } // 客户端代码 import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.Scanner; public class Client { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 8888); System.out.println("已连接到服务器:" + socket.getInetAddress()); ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); Scanner scanner = new Scanner(System.in); while (true) { System.out.print("请输入消息:"); String message = scanner.nextLine(); out.writeObject(message); String response = (String) in.readObject(); System.out.println("收到服务端回复:" + response); if ("exit".equalsIgnoreCase(message)) { break; } } in.close(); out.close(); socket.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } ``` 使用RMI实现远程控制: ```java // 定义远程接口 import java.rmi.Remote; import java.rmi.RemoteException; public interface RemoteService extends Remote { String sayHello(String name) throws RemoteException; } // 实现远程接口 import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class RemoteServiceImpl extends UnicastRemoteObject implements RemoteService { protected RemoteServiceImpl() throws RemoteException { super(); } @Override public String sayHello(String name) throws RemoteException { return "Hello, " + name + "!"; } } // 服务端代码 import java.rmi.Naming; import java.rmi.registry.LocateRegistry; public class Server { public static void main(String[] args) { try { LocateRegistry.createRegistry(1099); RemoteServiceImpl service = new RemoteServiceImpl(); Naming.rebind("RemoteService", service); System.out.println("服务已启动"); } catch (Exception e) { e.printStackTrace(); } } } // 客户端代码 import java.rmi.Naming; public class Client { public static void main(String[] args) { try { RemoteService service = (RemoteService) Naming.lookup("rmi://localhost/RemoteService"); String response = service.sayHello("World"); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码仅作为示例,实际应用需要根据具体需求进行修改和完善。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值