要实现
连接 远程 服务器并
执行命令,可以
使用 Java中的
SSH协议。
SSH(Secure Shell)是一种加密网络协议,可用于安全地
连接到
远程 服务器并
执行命令。
Java中有一些
SSH库可以用来实现这个功能,比如
JSch和Apache Mina
SSHD。下面是一个
使用 JSch的示例代码:
javaimport com.jcraft.jsch.*;public classSSHConnection {public static void main(String[] args) {String host= "remotehost.com";Stringuser = "username";Stringpassword = "password";try {JSch jsch= newJSch();Session session =jsch.getSession(user,host, 22);session.setPassword(password);session.setConfig("Strict Host Key Check ing", "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”)。执行通道
连接后,它从通道的输入流中读取输出并将其打印到控制台。最后,通道断开
连接,并且会话关闭。
需要注意的是,这个示例代码中的密码是明文存储的,这是不安全的。在实际生产环境中,应该考虑
使用密钥进行身份验证,而不是密码。
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.mushiming.com/mjsbk/8896.html