广告:
信号屏蔽器:守护你的数字生活,为你带来宁静与专注
还在为复杂的防火墙运维烦恼吗,接下来带大家写一个动态获取本地ip生成脚本
1.导入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 请检查是否有更新的版本 -->
</dependency>
2.我的对应的是云服务器的数据库,在云服务面板防火墙设有数据库3306端口,mysql用户登陆权限设置有ip限制。直接上代码
package com.sstx.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* @author Mr.Zhang
* @version 11
* @since jdk version1.8
*/
public class CreatShellCommand {
private static String lastIp = "116.30.241.71";
private static String newIp = "";
public static void main(String[] args) {
createMysqlAuth();
}
public static void createMysqlAuth(){
newIp = getPublicIP();
String deleteSql = " DROP USER 'root'@'"+lastIp+"';\n";
String createSql = " CREATE USER 'root'@'"+newIp+"' IDENTIFIED BY 'zp730990..';\n";
String grantSql = " GRANT ALL PRIVILEGES ON *.* TO 'root'@'"+newIp+"' WITH GRANT OPTION;\n";
String refreshSql = " FLUSH PRIVILEGES;\n";
System.out.println("请按照以下操作执行!");
System.out.println(" 1. 修改腾讯云3306允许ip为"+newIp);
System.out.println(" 2. 进入腾讯云服务器的mysql的docker容器,进入mysql服务器,输入以下命令:\n"+deleteSql+createSql+grantSql+refreshSql);
}
/**
* 动态获取公网ip
* @return 公网ip
*/
public static String getPublicIP() {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://ifconfig.me"); // 这是一个提供公网IP信息的服务
HttpResponse response = null;
try {
response = client.execute(request);
} catch (IOException e) {
throw new RuntimeException(e);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
// 返回的内容就是公网IP地址
try {
return EntityUtils.toString(entity);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return null;
}
}
3.效果展示
按照所示步骤直接粘贴使用即可
更多信息请咨询 sz-sstx.com