我似乎在使用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放在上面,它不会产生输出,但没有它就可以正常工作(我需要它作为一个变量,因为我以后会用到它)。
第二个问题是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)运行它,它也无法发送任何东西。
附注:在我的实际代码中,我替换了正确的用户名和密码(由谷歌提供)和正确的子域,域,顶级域,因为它适用于我。
对此有什么想法吗?
编辑:更新(和工作)的代码如下所示:
#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发布于 2020-04-13 22:54:15
首先,这是一个很好的服务,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接口文档。他们说使用Basic Auth提供你的用户名和密码,这会使你的凭证成为一个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 Basichttps://stackoverflow.com/questions/61189871
复制相似问题