From e88584a19baba6ac04210d78d945f6ff3c0c015b Mon Sep 17 00:00:00 2001 From: fanyuhui <852221040@qq.com> Date: Thu, 6 Jun 2024 15:06:08 +0800 Subject: [PATCH] update --- Dockerfile | 2 +- .../common/service/impl/ApiServiceImpl.java | 270 +++++++----------- foreign-server/src/test/java/CommonTest.java | 141 +++++++-- 3 files changed, 210 insertions(+), 203 deletions(-) diff --git a/Dockerfile b/Dockerfile index 2f03aaa..5e89711 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,7 +17,7 @@ FROM openjdk:8-jdk-alpine # 安装依赖包 RUN apk update \ - && apk add bind-tools curl jq \ + && apk add bind-tools \ && ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo Asia/Shanghai > /etc/timezone \ && mkdir -p /app/ && touch /app/scan.db diff --git a/common/src/main/java/com/proxyip/select/common/service/impl/ApiServiceImpl.java b/common/src/main/java/com/proxyip/select/common/service/impl/ApiServiceImpl.java index 51bff7b..8667333 100644 --- a/common/src/main/java/com/proxyip/select/common/service/impl/ApiServiceImpl.java +++ b/common/src/main/java/com/proxyip/select/common/service/impl/ApiServiceImpl.java @@ -2,7 +2,9 @@ import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.FileUtil; +import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.ZipUtil; import cn.hutool.http.HttpRequest; @@ -37,69 +39,33 @@ @Slf4j public class ApiServiceImpl implements IApiService { - private static final String COMMAND_PREFIX = "sh"; - /** - * cf添加dns记录api - */ - private static final String CF_ADD_DNS_RECORDS_API = "curl -X POST \"https://api.cloudflare.com/client/v4/zones/%s/dns_records\"" + - " -H \"Authorization: Bearer %s\" " + - " -H \"Content-Type: application/json\" " + - " --data '{\"type\":\"A\",\"name\":\"%s\",\"content\":\"%s\",\"proxied\":false}'"; - - /** - * cf删除所有dns记录api - */ - private static String CF_REMOVE_DNS_RECORDS_API = "curl -X GET \"https://api.cloudflare.com/client/v4/zones/%s/dns_records?type=A&name=%s\" " + - " -H \"Authorization: Bearer %s\" " + - " -H \"Content-Type: application/json\" | " + - "jq -c '.result[] | .id' | " + - "xargs -n 1 -I {} curl -X DELETE \"https://api.cloudflare.com/client/v4/zones/%s/dns_records/{}\" " + - " -H \"Authorization: Bearer %s\" " + - " -H \"Content-Type: application/json\""; - - /** - * cf删除指定代理域名的某个ip地址的dns记录api - */ - private static String CF_REMOVE_SINGLE_DNS_RECORDS_API = "curl -X GET \"https://api.cloudflare" + - ".com/client/v4/zones/%s/dns_records?type=A&name=%s\" " + - "-H \"Authorization: Bearer %s\" " + - "-H \"Content-Type: application/json\" | jq -c '.result[] | select(.content == \"%s\") | .id' | xargs -n 1 -I {} curl -X DELETE " + - "\"https://api.cloudflare.com/client/v4/zones/%s/dns_records/{}\" " + - "-H \"Authorization: Bearer %s\" " + - "-H \"Content-Type: application/json\""; - /** * 获取ip归属国家api */ - private static String GET_IP_LOCATION_API1 = "curl \"https://api.iplocation.net/?cmd=ip-country&ip=%s\""; - private static String GET_IP_LOCATION_API2 = "curl -H \"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36\" " + - "-H \"Accept: application/json\" \"https://api.ip.sb/geoip/%s\""; - private static String GET_GEO_IP_LOCATION_API = "curl \"https://geolite.info/geoip/v2.1/country/%s\"" + - " -H \"Authorization: Basic %s\""; - - /** - * 个人网盘api - */ - private static String NET_DISC_API = "curl -X POST -F \"image=@%s;type=application/octet-stream\" %s"; + private static final String GET_IP_LOCATION_API1 = "https://api.iplocation.net/?cmd=ip-country&ip=%s"; + private static final String GET_IP_LOCATION_API2 = "https://ipapi.co/%s/json"; + private static final String GET_GEO_IP_LOCATION_API = "https://geolite.info/geoip/v2.1/country/%s"; @Override public void uploadFileToNetDisc(String filePath, String apiAddress) { - String curlCommand = String.format(NET_DISC_API, filePath, apiAddress); - ProcessBuilder processBuilder = new ProcessBuilder(COMMAND_PREFIX, "-c", curlCommand); - try { - Process process = processBuilder.start(); - // Read the output of the command - try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { - String line; - while ((line = reader.readLine()) != null) { - if (line.contains("\"code\":1")) { - log.info("√√√ 文件:{} 已发送至个人网盘 √√√", filePath); - break; - } - } - } - } catch (Exception e) { - e.printStackTrace(); + File file = new File(filePath); + + if (!file.exists()) { + log.error("文件 {} 不存在", filePath); + return; + } + + // 发送POST请求上传文件 + HttpResponse response = HttpRequest.post(apiAddress) + .form("image", file) + .execute(); + + // 读取响应 + String responseBody = response.body(); + if (responseBody.contains("\"code\":1")) { + log.info("√√√ 文件:{} 已发送至个人网盘 √√√", filePath); + } else { + log.error("文件:{} 发送失败,响应信息:{}", filePath, responseBody); } } @@ -110,30 +76,19 @@ public List resolveDomain(List domainList, String dnsServer) { } Set ipAddresses = new HashSet<>(); - domainList.stream().parallel().forEach(domain -> { - ProcessBuilder processBuilder = new ProcessBuilder("nslookup", domain, dnsServer); - + domainList.parallelStream().forEach(domain -> { + String command = String.format("nslookup %s %s", domain, dnsServer); try { - Process process = processBuilder.start(); - // Read the output of the command - try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { - String line; - while ((line = reader.readLine()) != null) { - if (line.startsWith("Address:") && !line.contains("#")) { - String ipAddress = line.substring(line.indexOf(":") + 1).trim(); - ipAddresses.add(ipAddress); - } - } - } + List results = RuntimeUtil.execForLines(command); - // Wait for the process to finish - int exitCode = process.waitFor(); - if (exitCode != 0) { - log.error("Error executing nslookup command"); -// System.exit(1); + for (String line : results) { + if (line.startsWith("Address:") && !line.contains("#")) { + String ipAddress = line.substring(line.indexOf(":") + 1).trim(); + ipAddresses.add(ipAddress); + } } } catch (Exception e) { - e.printStackTrace(); + log.error("Error executing nslookup command", e); } }); @@ -142,85 +97,54 @@ public List resolveDomain(List domainList, String dnsServer) { @Override public String getIpCountry(String ipAddress) { - String curlCommand = String.format(GET_IP_LOCATION_API1, ipAddress); - ProcessBuilder processBuilder = new ProcessBuilder(COMMAND_PREFIX, "-c", curlCommand); - String country = null; - try { - Process process = processBuilder.start(); - // Read the output of the command - try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { - String line; - while ((line = reader.readLine()) != null) { - if (line.contains("country_code2")) { - int index = line.indexOf("country_code2"); - country = line.substring(index + 16, index + 18).trim(); - break; - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - return country; + String url = String.format(GET_IP_LOCATION_API1, ipAddress); + HttpResponse response = HttpRequest.get(url).execute(); + // 将字符串解析为JSONObject + JSONObject jsonObject = JSONUtil.parseObj(response.body()); + // 获取country_code2 + return jsonObject.getStr("country_code2"); } @Override public String getIpCountry(String ipAddress, String geoIpAuth) { - String country = null; - // 不使用GeoIP2 if ("".equals(geoIpAuth)) { return getIpCountry(ipAddress); } - String curlCommand = String.format(GET_GEO_IP_LOCATION_API, ipAddress, geoIpAuth); - ProcessBuilder processBuilder = new ProcessBuilder(COMMAND_PREFIX, "-c", curlCommand); - try { - Process process = processBuilder.start(); - // Read the output of the command - try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { - String line; - while ((line = reader.readLine()) != null) { - if (line.contains("\"iso_code\"")) { - int index = line.indexOf("\"iso_code\""); - country = line.substring(index + 12, index + 14); - break; - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } + String url = String.format(GET_GEO_IP_LOCATION_API, ipAddress); - return country; + HttpResponse response = HttpRequest.get(url) + .header("Authorization", "Basic " + geoIpAuth) + .execute(); + + // 将字符串解析为JSONObject + JSONObject jsonObject = JSONUtil.parseObj(response.body()); + + // 获取country对象中的iso_code + return jsonObject.getByPath("country.iso_code", String.class); } @Override public void addCfDnsRecords(String domainPrefix, String ipAddress, String zoneId, String apiToken) { - String curlCommand = String.format(CF_ADD_DNS_RECORDS_API, zoneId, apiToken, domainPrefix, ipAddress); - ProcessBuilder processBuilder = new ProcessBuilder(COMMAND_PREFIX, "-c", curlCommand); - try { - Process process = processBuilder.start(); - -// try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { -// String line; -// log.info("add ------------------" + domainPrefix + "-------------------"); -// while ((line = reader.readLine()) != null) { -// log.info(line); -// } -// log.info("add ------------------" + domainPrefix + "-------------------"); -// } - - // Wait for the process to finish - int exitCode = process.waitFor(); - if (exitCode != 0) { - log.error("Error executing addCfDnsRecords task"); - } -// log.info("域名:" + domainPrefix + "." + dnsCfg.getRootDomain() + " 的dns记录添加成功!ip地址:" + ipAddress); - } catch (Exception e) { - e.printStackTrace(); - throw new BusinessException(-1, "添加cf记录失败:" + e.getLocalizedMessage()); - } + String url = String.format("https://api.cloudflare.com/client/v4/zones/%s/dns_records", zoneId); + + // 构建请求体 + JSONObject data = new JSONObject(); + data.put("type", "A"); + data.put("name", domainPrefix); + data.put("content", ipAddress); + data.put("proxied", false); + + // 发送POST请求 + HttpResponse response = HttpRequest.post(url) + .header("Authorization", "Bearer " + apiToken) + .header("Content-Type", "application/json") + .body(data.toString()) + .execute(); + + // 返回响应结果 +// log.info(response.body()); } @Override @@ -252,49 +176,47 @@ public void removeCfDnsRecords(List proxyDomainList, String zoneId, Stri @Override public void removeCfSingleDnsRecords(String proxyDomain, String ip, String zoneId, String apiToken) { - String curlCommand = String.format(CF_REMOVE_SINGLE_DNS_RECORDS_API, zoneId, proxyDomain, apiToken, ip, zoneId, apiToken); - ProcessBuilder processBuilder = new ProcessBuilder(COMMAND_PREFIX, "-c", curlCommand); - try { - Process process = processBuilder.start(); - // Wait for the process to finish - int exitCode = process.waitFor(); - if (exitCode != 0) { - log.error("Error executing removeCfSingleDnsRecords task"); + String url = "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/dns_records?type=A&name=" + proxyDomain; + HttpRequest request = HttpRequest.get(url) + .header("Authorization", "Bearer " + apiToken) + .header("Content-Type", "application/json"); + HttpResponse response = request.execute(); + String responseBody = response.body(); + JSONArray recordsArray = JSONUtil.parseArray(JSONUtil.parseObj(responseBody).get("result")); + for (int i = 0; i < recordsArray.size(); i++) { + String address = JSONUtil.parseObj(recordsArray.get(i)).getStr("content"); + if (address.equals(ip)) { + String id = JSONUtil.parseObj(recordsArray.get(i)).getStr("id"); + // 删除 DNS 记录 + String deleteUrl = "https://api.cloudflare.com/client/v4/zones/" + zoneId + "/dns_records/" + id; + HttpRequest deleteRequest = HttpRequest.delete(deleteUrl) + .header("Authorization", "Bearer " + apiToken) + .header("Content-Type", "application/json"); + HttpResponse deleteResponse = deleteRequest.execute(); + // 等待删除命令执行完毕 + if (deleteResponse.getStatus() != 200) { + log.error("Error executing delete command"); + } + break; } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - throw new BusinessException(-1, "清除DNS记录失败:" + e.getLocalizedMessage()); } log.info("√√√ 域名:{} 的A记录ip:{} 的dns记录已清除! √√√", proxyDomain, ip); } @Override public String getIpInfo(String ipAddress, String geoIpAuth) { - StringBuilder sb = new StringBuilder(); - - String curlCommand; // 不使用GeoIP2 if ("".equals(geoIpAuth)) { - curlCommand = String.format(GET_IP_LOCATION_API2, ipAddress); + String url = String.format(GET_IP_LOCATION_API2, ipAddress); + HttpResponse response = HttpRequest.get(url).execute(); + return response.body(); } else { - curlCommand = String.format(GET_GEO_IP_LOCATION_API, ipAddress, geoIpAuth); - } - - ProcessBuilder processBuilder = new ProcessBuilder(COMMAND_PREFIX, "-c", curlCommand); - try { - Process process = processBuilder.start(); - // Read the output of the command - try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { - String line; - while ((line = reader.readLine()) != null) { - sb.append(line); - } - } - } catch (Exception e) { - e.printStackTrace(); + String url = String.format(GET_GEO_IP_LOCATION_API, ipAddress); + HttpResponse response = HttpRequest.get(url) + .header("Authorization", "Basic " + geoIpAuth) + .execute(); + return response.body(); } - - return sb.toString(); } @Override diff --git a/foreign-server/src/test/java/CommonTest.java b/foreign-server/src/test/java/CommonTest.java index 0b1716e..9fce2d9 100644 --- a/foreign-server/src/test/java/CommonTest.java +++ b/foreign-server/src/test/java/CommonTest.java @@ -1,7 +1,12 @@ +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; +import cn.hutool.log.Log; +import cn.hutool.log.LogFactory; import java.io.BufferedReader; +import java.io.File; import java.io.InputStreamReader; /** @@ -12,38 +17,118 @@ * @date: 2024/3/28 20:54 */ public class CommonTest { - public static void main(String[] args) { - String jsonStr = getIpInfo("141.147.101.8", ""); - System.out.println(jsonStr); - JSONObject obj = JSONUtil.parseObj(jsonStr); - System.out.println(obj.get("country_code", String.class) == null ? "kong" : obj.get("country_code", String.class)); + private static final Log log = LogFactory.get(); + + private static final String GET_IP_LOCATION_API1 = "https://api.iplocation.net/?cmd=ip-country&ip=%s"; + private static final String GET_IP_LOCATION_API2 = "https://ipapi.co/%s/json"; + private static final String GET_GEO_IP_LOCATION_API = "https://geolite.info/geoip/v2.1/country/%s"; + + /** + * 获取IP位置(API 1) + * + * @param ip IP地址 + * @return API响应的结果 + */ + public static String getIpLocation1(String ip) { + String url = String.format(GET_IP_LOCATION_API1, ip); + + HttpResponse response = HttpRequest.get(url) + .execute(); - System.out.println(jsonStr.substring(jsonStr.indexOf("country_code") + 15, jsonStr.indexOf("country_code") + 17)); + return response.body(); } - private static String GET_IP_LOCATION_API2 = "curl -H \"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36\" " + - "-H \"Accept: application/json\" \"https://api.ip.sb/geoip/%s\""; - private static String GET_IP_LOCATION_API1 = "curl \"https://api.iplocation.net/?cmd=ip-country&ip=%s\""; - - public static String getIpInfo(String ipAddress, String geoIpAuth) { - StringBuilder sb = new StringBuilder(); - - String curlCommand = String.format(GET_IP_LOCATION_API2, ipAddress); - - ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", curlCommand); - try { - Process process = processBuilder.start(); - // Read the output of the command - try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { - String line; - while ((line = reader.readLine()) != null) { - sb.append(line); - } - } - } catch (Exception e) { - e.printStackTrace(); + /** + * 获取IP位置(API 2) + * + * @param ip IP地址 + * @return API响应的结果 + */ + public static String getIpLocation2(String ip) { + String url = String.format(GET_IP_LOCATION_API2, ip); + + HttpResponse response = HttpRequest.get(url) + .execute(); + + return response.body(); + } + + /** + * 获取GeoIP位置 + * + * @param ip IP地址 + * @param authToken 授权Token + * @return API响应的结果 + */ + public static String getGeoIpLocation(String ip, String authToken) { + String url = String.format(GET_GEO_IP_LOCATION_API, ip); + + HttpResponse response = HttpRequest.get(url) + .header("Authorization", "Basic " + authToken) + .execute(); + + return response.body(); + } + + /** + * 上传文件到网络磁盘 + * + * @param filePath 文件路径 + * @param apiAddress API地址 + */ + public static void uploadFileToNetDisc(String filePath, String apiAddress) { + File file = new File(filePath); + + if (!file.exists()) { + log.error("文件 {} 不存在", filePath); + return; } - return sb.toString(); + // 发送POST请求上传文件 + HttpResponse response = HttpRequest.post(apiAddress) + .form("image", file) + .execute(); + + // 读取响应 + String responseBody = response.body(); + if (responseBody.contains("\"code\":1")) { + log.info("√√√ 文件:{} 已发送至个人网盘 √√√", filePath); + } else { + log.error("文件:{} 发送失败,响应信息:{}", filePath, responseBody); + } + } + + + public static void main(String[] args) { + String ip = "8.8.8.8"; + String authToken = "xxx"; // 需要base64编码后的认证信息 + +// String response1 = getIpLocation1(ip); +// System.out.println("API 1 Response: " + response1); +// // 将字符串解析为JSONObject +// JSONObject jsonObject = JSONUtil.parseObj(response1); +// // 获取country_code2 +// String countryCode2 = jsonObject.getStr("country_code2"); +// // 输出country_code2 +// System.out.println("Country Code2: " + countryCode2); + +// String response2 = getIpLocation2(ip); +// System.out.println("API 2 Response: " + response2); + +// String response3 = getGeoIpLocation(ip, authToken); +// System.out.println("GeoIP API Response: " + response3); +// +// // 将字符串解析为JSONObject +// JSONObject jsonObject = JSONUtil.parseObj(response3); +// +// // 获取country对象中的iso_code +// String isoCode = jsonObject.getByPath("country.iso_code", String.class); +// System.out.println(isoCode); + + + String filePath = "path/file"; + String apiAddress = "https://a.b.c/netdisc/api"; + + uploadFileToNetDisc(filePath, apiAddress); } }