最近遇到一个场景,需要利用web前端以图形化界面的方式修改远程服务器的一些配置文件,我的思路是这样的,首先从远程服务器上把文件拷贝下来,然后在本地修改完成之后再上传到服务器的原路径,下面直接上代码:
从服务器到本地:
public static boolean getConfFile(String userName, String password, String ipAddr, String clusterPath, String localPath) {
boolean isAuthed = false;
boolean status = false;
try {
status = InetAddress.getByName(ipAddr).isReachable(1500);
System.out.println(status);
if (status) {
Connection conn = new Connection(ipAddr);
conn.connect();
isAuthed = conn.authenticateWithPassword(userName, password);
System.out.println(isAuthed);
if (isAuthed) {
Session session = conn.openSession();
SCPClient scpClient = conn.createSCPClient();
scpClient.get(clusterPath, localPath);
session.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return isAuthed;
}
从本地上传到服务器:
public static boolean putBackConfFile(String userName, String password, String ipAddr, String loadFilePath, String clusterPath) {
boolean isAuthed = false;
try {
if (InetAddress.getByName(ipAddr).isReachable(1500)) {
Connection conn = new Connection(ipAddr);
conn.connect();
isAuthed = conn.authenticateWithPassword(userName, password);
if (isAuthed) {
SCPClient scpClient = conn.createSCPClient();
scpClient.put(loadFilePath, clusterPath);
conn.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return isAuthed;
}
所用到的一些依赖:
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-scp</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>