不建议使用,需要知道服务器密码才能使用,但是生产环境的服务器密码一般不对开发者开放。
SCPClient 的get方法从服务器下载中文名称的文件时也存在问题。
/**
* 创建SSH连接
* @param hostName
* @param username
* @param password
* @param port
* @return
*/
public static Connection getConnect(String hostName, String username, String password, int port) {
Connection conn = new Connection(hostName, port);
try {
// 连接到主机
conn.connect();
// 使用用户名和密码校验
boolean isconn = conn.authenticateWithPassword(username, password);
if (!isconn) {
System.out.println("用户名称或者是密码不正确");
} else {
System.out.println("服务器连接成功.");
return conn;
}
} catch (Exception e) {
logger.error("远程服务器连接异常:", e);
}
return null;
}
/**
* 实现下载服务器上的文件到本地指定目录
* @param conn SSH连接信息
* @param basePath 服务器上的文件地址/home/Fileimg/myqxin.jpg
* @param localPath 本地路径:D:/
* @throws IOException
*/
public static void getFile(Connection conn, String basePath,String localPath) throws IOException {
SCPClient scpClient=conn.createSCPClient();
try {
scpClient.get(basePath,localPath);
} catch (IOException e) {
logger.error("服务器文件保存本地异常:", e);
} finally {
System.out.println("服务关闭");
conn.close();
}
}