使用apache sshd框架,作为ssh客户端,连接到linux机器,执行命令。
1. pom.xml中添加如下依赖。
<dependency> <groupId>org.apache.sshd</groupId> <artifactId>sshd-core</artifactId> <version>2.2.0</version> </dependency>
2. 执行命令的代码如下。
package com.baicells.SpringbootHelloworld.sshd; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.apache.sshd.client.SshClient; import org.apache.sshd.client.channel.ClientChannel; import org.apache.sshd.client.channel.ClientChannelEvent; import org.apache.sshd.client.session.ClientSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class SSHClientTest { private Logger logger = LoggerFactory.getLogger(getClass()); @PostConstruct private void init() { SshClient client = null; ClientSession session = null; String result = null; String error = null; try { client = SshClient.setUpDefaultClient(); client.start(); session = client.connect("root", "192.168.101.35", 22).verify(10 * 1000).getSession(); session.addPasswordIdentity("omcomc"); if (!session.auth().verify(10 * 1000).isSuccess()) { throw new Exception("auth faild"); } ClientChannel channel = session.createExecChannel("ls -l"); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); channel.setOut(out); channel.setErr(err); if (!channel.open().verify(10 * 1000).isOpened()) { throw new Exception("open faild"); } List<ClientChannelEvent> list = new ArrayList<ClientChannelEvent>(); list.add(ClientChannelEvent.CLOSED); channel.waitFor(list, 10 * 1000); channel.close(); result = out.toString(); error = err.toString(); } catch (Exception e) { logger.error("", e); } finally { if (client != null) { try { client.stop(); client.close(); } catch (IOException e) { logger.error("", e); } } } System.out.println("--------------------result--------------------"); System.out.println(result); System.out.println("--------------------error--------------------"); System.out.println(error); } }