首先需要ganymed的jar包,pom依赖为
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
以下为代码展示
//连接主机
Connection conn = new Connection(hostName);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(userName, password);
//判断连接是否成功
if (isAuthenticated == false)
throw new IOException("通过ssh登录失败");
//创建一个copy文件客户端
SCPClient scpClient = conn.createSCPClient();
scpClient.put(path+tarName, "~/");//从本地复制文件到远程目录
// scpClient.get(path,path);//从远程获取文件放到本地
//复制压缩包并解压,删除agent.properties
Session sess = conn.openSession();
sess.execCommand("cd ~/;tar -zxvf agent.tar.gz;");//执行命令,只能类似一条一条执行
sess.close();
sess.waitForCondition(ChannelCondition.EXIT_STATUS, 1000*5*60);//同步等待
if(sess3.getExitStatus()==0){
System.out.println("执行成功");
}else{
System.out.println("执行 失败");
}
/*//接收目标服务器上的控制台返回结果,输出结果。
InputStream stdout = new StreamGobbler(sess3.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
} */
sess3.close();//关闭连接
conn.close();//关闭连接