如何解决移动网络动态IP无法SSH连接AWS EC2实例的问题?
Got it, let's work through this—dealing with dynamic mobile IPs when trying to SSH into your EC2 instance is a super common headache. Here are a few straightforward ways to grab your current public IP, plus an advanced trick to avoid doing this manually every time:
Whether you're on Linux, macOS, or Windows, these commands spit out your public IP directly with no extra fluff:
- Linux/macOS: Open your terminal and run either
curl ifconfig.meorcurl icanhazip.com—both will return just your IP address. - Windows: Fire up PowerShell and execute
Invoke-RestMethod http://icanhazip.com; same result, clean and quick.
If you're using your phone's mobile data (either directly via Termux or sharing a hotspot):
- Browser method: Open your phone's browser and search for "my public IP"—most search engines will display your IP right at the top of results without needing to click through.
- Termux (Android): If you use the Termux terminal app, run
curl ifconfig.mejust like you would on a desktop—works perfectly.
Manually checking and updating your security group every time your IP changes is tedious. Instead, use a script to automate this:
- First, make sure you have the AWS CLI set up on your device with permissions to modify EC2 security groups.
- Use a script like this to fetch your current IP and update the SSH ingress rule:
# Grab your current public IP (with /32 CIDR notation for single IP) CURRENT_IP=$(curl -s icanhazip.com)/32 # Replace with your security group ID and AWS region SECURITY_GROUP_ID="sg-12345678" AWS_REGION="us-east-1" # Add the new IP to the security group aws ec2 authorize-security-group-ingress --group-id $SECURITY_GROUP_ID --region $AWS_REGION --protocol tcp --port 22 --cidr $CURRENT_IP # Optional: Revoke old IP rules to keep your security group clean # Replace OLD_IP with the previous IP you used, or add logic to list and remove old ones # aws ec2 revoke-security-group-ingress --group-id $SECURITY_GROUP_ID --region $AWS_REGION --protocol tcp --port 22 --cidr OLD_IP/32
You can set this script to run on a schedule (using cron on Linux/macOS or Task Scheduler on Windows) so your security group always has your latest mobile IP.
内容的提问来源于stack exchange,提问作者bhupatbheda

