Debian Java遠程控制的實現方法
JSch是純Java實現的SSH2客戶端庫,支持通過SSH協議遠程執行命令、傳輸文件,適合需要Java原生集成的場景。
<dependency>
<groupId>com.github.mwiede</groupId>
<artifactId>jsch</artifactId>
<version>0.2.19</version>
</dependency>
JSch
類建立會話,打開exec
通道執行遠程命令,處理輸入流獲取結果。示例代碼:import com.jcraft.jsch.*;
public class RemoteControl {
public static void main(String[] args) {
String username = "your_username";
String host = "remote_host";
int port = 22;
String password = "your_password";
String command = "ls -l"; // 遠程執行的命令
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no"); // 跳過主機密鑰檢查(生產環境建議開啟)
session.connect();
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
channel.connect();
// 讀取命令輸出
InputStream in = channel.getInputStream();
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1) {
System.out.print(new String(buffer));
}
channel.disconnect();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
sudo apt install openssh-server && sudo systemctl start ssh
),確保防火墻開放22端口。RMI(遠程方法調用)是Java標準特性,允許不同JVM間的對象通信,適合Java環境內的緊密集成。
java.rmi.Remote
,聲明遠程方法并拋出RemoteException
);UnicastRemoteObject
,實現接口方法);LocateRegistry.createRegistry(1099)
),綁定遠程對象;public interface HelloService extends Remote { String sayHello() throws RemoteException; }
public class HelloServiceImpl extends UnicastRemoteObject implements HelloService { public HelloServiceImpl() throws RemoteException {} @Override public String sayHello() { return "Hello from Debian Server"; } }
HelloService service = new HelloServiceImpl(); Registry registry = LocateRegistry.createRegistry(1099); registry.bind("HelloService", service);
Registry registry = LocateRegistry.getRegistry("remote_host"); HelloService service = (HelloService) registry.lookup("HelloService"); System.out.println(service.sayHello());
RESTful基于HTTP協議,適合不同語言、平臺的遠程交互,常用Spring Boot框架快速實現。
spring-boot-starter-web
依賴);@RestController
和@GetMapping
/@PostMapping
注解定義接口);curl
、Postman或瀏覽器訪問)。@RestController public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello from Debian Server"; } }
./mvnw spring-boot:run
(默認監聽8080端口)curl http://remote_host:8080/hello
若通過VNC、RDP等非加密協議遠程控制,可通過SSH隧道加密流量,防止數據泄露。
ssh -L 5901:localhost:5901 username@remote_host -N
(-N
表示不執行遠程命令,僅建立隧道);vncserver :1
,對應端口5901);localhost:5901
,流量將通過SSH隧道加密傳輸。若需圖形界面操作,可使用以下工具:
sudo apt update && sudo apt install xrdp
;sudo systemctl enable xrdp && sudo systemctl start xrdp
;sudo ufw allow 3389
;sudo apt install xfce4
;vncserver -depth 24 -geometry 1024x768 :1
,設置密碼;remote_host:5901
(:1
對應5901端口)。