获取公网IP脚本

写了一个获取公网IP脚本

SCHTASKS /CREATE /SC MINUTE /MO 10 /TN "GetPublicIP" /TR "powershell -ExecutionPolicy Bypass -File E:\bat\getip.ps1" /F

 

# FTP 配置
$ftpServer = "ftp://xxx"
$ftpUser = "xxx"
$ftpPass = "xxx"
$ipFile = "ip.txt"
$localDir = "E:/bat/txt/"
$localFile = "$localDir$ipFile"

# 日志目录 & 日志文件名(每天生成一个新日志)
$logDir = "E:/bat/logs/"
$logFile = "$logDir$(Get-Date -Format "yyyy-MM-dd").log"

# 确保日志目录和文本目录存在
if (!(Test-Path $localDir)) { New-Item -ItemType Directory -Path $localDir -Force }
if (!(Test-Path $logDir)) { New-Item -ItemType Directory -Path $logDir -Force }

# 记录日志函数
function Write-Log {
    param (
        [string]$message
    )
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "$timestamp - $message" | Out-File -Append -Encoding utf8 $logFile
}

# 获取公网 IP
function Get-PublicIP {
    try {
        return (Invoke-WebRequest -Uri "https://api64.ipify.org" -UseBasicParsing).Content
    } catch {
        Write-Log "获取公网 IP 失败: $_"
        return $null
    }
}

# 读取上次保存的 IP
$lastIp = if (Test-Path $localFile) { Get-Content $localFile } else { "" }

# 获取当前公网 IP 和获取时间
$currentIp = Get-PublicIP
$currentTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

if ($currentIp -eq $null) {
    Write-Log "无法获取公网 IP,脚本终止。"
    exit
}

# 组合 IP + 获取时间
$currentIpInfo = "$currentIp  ($currentTime)"

# 如果 IP 发生变化
if ($currentIp -ne $lastIp) {
    Write-Log "新的公网 IP: $currentIpInfo"
    $currentIpInfo | Out-File -Encoding utf8 $localFile

    # 上传到 FTP
    try {
        $ftpUri = "$ftpServer/$ipFile"
        $webClient = New-Object System.Net.WebClient
        $webClient.Credentials = New-Object System.Net.NetworkCredential($ftpUser, $ftpPass)
        $webClient.UploadFile($ftpUri, $localFile)

        Write-Log "公网 IP 已更新,并上传到 FTP:$ftpUri"
    } catch {
        Write-Log "FTP 上传失败: $_"
    }
} else {
    Write-Log "公网 IP 未变更: $currentIpInfo"
}

  

posted @ 2025-03-11 22:29  ucdos2023  阅读(39)  评论(0)    收藏  举报