你可以使用Java中的SSH库来连接远程服务器并执行shell命令。下面是一个简单的示例代码:
import com.jcraft.jsch.*;public class SSHExample {public static void main(String[] args) {String host = "your_host";String username = "your_username";String password = "your_password";int port = 22;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("your_shell_command");channel.connect();InputStream in = channel.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in));String line;while ((line = reader.readLine()) != null) {System.out.println(line);}channel.disconnect();session.disconnect();} catch (JSchException | IOException e) {e.printStackTrace();}}
}
请注意替换your_host
,your_username
,your_password
和your_shell_command
为实际的远程服务器信息和要执行的shell命令。该示例代码使用JSch库来建立SSH连接并执行命令。