首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Invoke-RestMethod PowerShell Google DDNS

Invoke-RestMethod PowerShell Google DDNS
EN

Stack Overflow用户
提问于 2020-04-13 22:20:13
回答 1查看 374关注 0票数 1

我似乎在使用Google的DDNS服务更新我的IP这个看似基本的脚本上遇到了很多问题。

代码语言:javascript
复制
#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放在上面,它不会产生输出,但没有它就可以正常工作(我需要它作为一个变量,因为我以后会用到它)。

第二个问题是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)运行它,它也无法发送任何东西。

附注:在我的实际代码中,我替换了正确的用户名和密码(由谷歌提供)和正确的子域,域,顶级域,因为它适用于我。

对此有什么想法吗?

编辑:更新(和工作)的代码如下所示:

代码语言:javascript
复制
#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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-13 22:54:15

首先,这是一个很好的服务,api.ipify.org,我将来会用到它的。

其次,我认为这里唯一的问题是您对$url的定义。

如果你试图自己运行这行代码,你之前使用的语法实际上会抛出一个错误,错误显示在这里。

代码语言:javascript
复制
"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中,您应该像这样使用字符串扩展语法,而不是嵌套引号。

代码语言:javascript
复制
$uri = "https://username:password.google.com/nic/update?hostname=home.domain.com&myip=$($ip)"

更新

在这里找到https://support.google.com/domains/answer/6147083?hl=en接口文档。他们说使用Basic Auth提供你的用户名和密码,这会使你的凭证成为一个base64编码的字符串。我们可以在PowerShell中很容易地做到这一点!

您可以使用Get-Credential cmdlet保存凭据,然后将它们传递给Invoke-RestMethod并添加-Credential-Authentication作为参数。下面是一个完整的解决方案应该是什么样子。

代码语言:javascript
复制
$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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61189871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档