首先引入需要的jar包
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
引入完后创建连接 ip什么的都是随便写的,根据自己情况去写
Connection conn=new Connection("192.168.0.123",22) //远程连接的ip 和端口
conn.connect(); //进行连接
//isAuthenticated 返回的是true,验证成功就可以开始进行一些操作了
boolean isAuthenticated = conn.authenticateWithPassword("root","root"); //账号,密码
接下来进行文件上传 下载
SCPClient client = new SCPClient(conn);
//上传文件
client.put(file.getBytes(),"agent.jar","/root/agent"); //传入的是文件byte字节,agent,jar是linux上文件名,/root/agent是上传路径
//还有一种上传方式
client.put("E:\agent.jar","/root/agent.agent.jar"); //本地文件路径,服务器文件路径
//下载文件
client.get("/root/agent.agent.jar","E:\agent.jar"); //服务器文件路径,本地文件路径
连接服务器最重要的当然还是执行命令
下面的是我的工具类里的一些方法
public static String DEFAULTCHART="UTF-8";
/**
*
* @param cmd
*
* @return 执行命令 返回结果
*/
public static String execute(Connection conn, String cmd){
String result="";
Session session=null;
try {
if(conn !=null){
session= conn.openSession();//打开一个会话
session.execCommand(cmd);//执行命令
result=processStdout(session.getStdout(),DEFAULTCHART);
log.info("执行的命令:"+cmd);
}
return result;
} catch (IOException e) {
log.info("执行命令失败,链接conn:"+conn+",执行的命令:"+cmd+" "+e.getMessage());
e.printStackTrace();
return "执行失败";
}finally {
if(session!=null){
session.close();
}
}
}
/**
* 执行命令返回的结果(返回结果需要等待所有结果返回完毕才返回)
* @param in
* @param charset 编码格式
* @return
*/
private static String processStdout(InputStream in, String charset) {
InputStream stdout = new StreamGobbler(in);
StringBuffer buffer = new StringBuffer();
BufferedReader br=null;
try {
br = new BufferedReader(new InputStreamReader(stdout, charset));
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line + "\n");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(stdout!=null){
stdout.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(br!=null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return buffer.toString();
}
可以尝试 execute(conn,"ls") 看一下