Java代码
package springboot.demo;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
/**
* java远程虚拟机命令控制
* 2019-12-03
*/
public class RemoteShellTool {
private Connection conn;
private String ipAddr;
private String charset = Charset.defaultCharset().toString();
private String userName;
private String password;
//构造方法
public RemoteShellTool(String ipAddr, String userName, String password,
String charset) {
this.ipAddr = ipAddr;
this.userName = userName;
this.password = password;
if (charset != null) {
this.charset = charset;
}
}
//连接
public boolean login() throws IOException {
conn = new Connection(ipAddr);
conn.connect(); // 连接
return conn.authenticateWithPassword(userName, password); // 认证
}
//创建一个exec的命令通道
public String exec(String cmds) {
InputStream in = null;
String result = "";
try {
if (this.login()) {
Session session = conn.openSession(); // 打开一个会话
session.execCommand(cmds);
in = session.getStdout();
result = this.processStdout(in, this.charset);
session.close();
conn.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return result;
}
//过程输出
public String processStdout(InputStream in, String charset) {
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
try {
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* @param args
* Main命令测试
*/
public static void main(String[] args) {
//输入我们要操作的虚拟机信息(IP、用户名、密码)
RemoteShellTool tool = new RemoteShellTool("192.168.0.179", "user",
"userpwd", "utf-8");
//打开虚拟机,这里的win7是我们虚拟机的名称
//String result = tool.exec("vboxmanage startvm win7 vrdp");
//关闭虚拟机,这里的win7是我们虚拟机的名称
String result = tool.exec("VBoxManage controlvm win7 poweroff");
System.out.print(result);
}
}
添加SSH依赖
<dependency>
<groupId>org.jvnet.hudson</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210-hudson-1</version>
</dependency>
开机
关机