使用Google DDNS服务更新我的IP的看似基本的脚本似乎有很多问题。
#Fetch current IP address
$ipuri = "https://api.ipify.org"
$ip = Invoke-RestMethod -Uri $ipuri
#Send fetched IP address to Google Domains through their API
$uri = "https://username:password.google.com/nic/update?hostname=home.domain.com&myip="$ip""
Invoke-RestMethod -Method 'Get' -Uri $uri
第一个问题是$ ip变量。如果我保留$ ip,它不会产生任何输出,但是如果没有$ ip,它就可以正常工作(我以后需要使用它作为变量)。
第二个问题是https://username:password@domains.google.com/nic/update?hostname=home.domain.com&myip=“ $ ip”。
如果我将确切的字符串转储到邮递员中(用实际的IP地址代替$ ip,则可以正常工作) 但是即使我使用在PowerShell中手动插入的IP(例如https://username:password@domains.google.com/nic/update?hostname=home.domain.com&myip=1.2.3.4)运行它,也无法发送任何内容。
P.S。在我的实际代码中,我用正确的用户名和密码(由Google提供)代替,并替换适用于我的正确的子域,域和顶级域。
对此有何想法?
编辑: 更新的(并且可以正常工作的)代码如下所示:
#Fetches current IPv4 address
$ipuri = "https://api.ipify.org"
$ip = Invoke-RestMethod -Uri $ipuri
#Stores Google-provided username and password
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$credential = New-Object Management.Automation.PSCredential ('username', $password)
#Send fetched IP address to Google Domains through their API
$uri = "https://domains.google.com/nic/update?hostname=home.domain.com&myip=$($ip)"
Invoke-RestMethod -Method 'POST' -Uri $uri -Credential $credential
答案 0 :(得分:0)
首先,这是一个整洁的服务api.ipify.org,以后我将不得不使用它。
第二,我认为这里唯一的问题是您对$url
的定义。
如果您尝试自行运行该行,则以前使用的语法实际上会引发错误,此处显示错误。
"https://username:password.google.com/nic/update?hostname=home.domain.com&myip="$ip""
At line:1 char:81
+ ... e:password.google.com/nic/update?hostname=home.domain.com&myip="$ip""
+ ~~~~~
Unexpected token '$ip""' in expression or statement.
在PowerShell中,您应该使用这样的字符串扩展语法,而不是嵌套引号。
$uri = "https://username:password.google.com/nic/update?hostname=home.domain.com&myip=$($ip)"
在https://support.google.com/domains/answer/6147083?hl=en处找到了API文档。他们说要使用基本身份验证提供您的用户名和密码,这将使您的凭据成为base64编码的字符串。我们可以在PowerShell中轻松做到这一点!
您可以使用Get-Credential
cmdlet提供凭据以保存它们,然后将其传递到Invoke-RestMethod
中,并添加-Credential
和-Authentication
作为参数。这是完整的解决方案。
$ipuri = "https://api.ipify.org"
$ip = Invoke-RestMethod -Uri $ipuri
#Send fetched IP address to Google Domains through their API
$myCredential = Get-Credential #you'll be prompted to provide your google username and pwd.
$uri = "https://domains.google.com/nic/update?hostname=home.domain.com&myip=$($ip)"
Invoke-RestMethod -Method 'POST' -Uri $uri -Credential $myCredential -Authentication Basic