接口调用,输出结果为Json格式(ConvertTo-Json),提交参数给URL(WebRequest),ConvertFrom-Json
1.直接输出为json格式:
Get-Process -Id $pid | ConvertTo-Json | clip.exe
2.自定义结果为json格式:
$serverinfoj = @" { "Status": "Success", "Infors": { "ServerName": "$env:ComputerName", "IP": "$Server", "OSVersion": "$osversion", "MemorySize": "$memorysize_sum", "CPU": "$cpunamecore", "DomainName": "$domainname", "DISK": "$disklist", "SN": "$sn", "Xinghao":"$xinghao" } } "@ #格式必须要这样,顶格写,开头和结尾的@不能与大括号写到一行 #其中的变量内容也必须要引起来 $serverinfo = ConvertFrom-Json -InputObject $serverinfoj #转换为json格式 $serverinfo.Status $serverinfo.Infors $serverinfo.Infors.OSVersion
#输出结果: ServerName : PC-L IP : 10.16.30.51 OSVersion : Microsoft Windows Server 2012 R2 Datacenter 64bit MemorySize : 4GB CPU : Intel(R) Xeon(R) CPU E5-2620 v3 @ 2.40GHz 2*1C DomainName : uxin.youxinpai.com DISK : Disk0:300GB SN : Hyper-V Xinghao : Microsoft Virtual Machine Microsoft Windows Server 2012 R2 Datacenter 64bit
还可以对$serverinfo内容进行修改,如:
$serverinfo.Status = "test"
value也可以直接通过命令获得,使用$符号
$json = @" { "ServerName": "$env:ComputerName", "BIOS": { "sn" : "$((Get-WmiObject -Class Win32_BIOS).sn)", "Version" : "$((Get-WmiObject -Class Win32_BIOS).Version)" }, "OS" : "$([Environment]::OSVersion.VersionString)" } "@
$data = (New-Object PSObject | Add-Member -PassThru NoteProperty ServerName "nnn" | Add-Member -PassThru NoteProperty Infors "192.168.1.1" ) | ConvertTo-JSON #返回是json字符串,等同于@""@方法
后端API,通过GET方法接收URL参数:
def srvinfors_api(request): #Client access this api to write server infors. if request.method == 'GET': Infors=request.GET['Infors'] cj = json.loads(Infors,strict=False,encoding='utf-8') #将参数转换为dict cjres = json.dumps(cj,ensure_ascii=False) #返回时使用json字符串 print cj['ServerName'] #serverinfors.objects.update_or_create(IP=cj['IP'],defaults=cj) return HttpResponse(cjres)
提交参数:http://10.160.25.48/sinfors/srvinfors_api/?a=2&b=3&c=22
在PowerShell3.0中使用invoke-restmethod提交参数,(invoke-webrequest返回格式是对象,invoke-restmethod返回格式是字符串)
$a='adf' $h=@{a=$a; b=222; c="" } $url = "http://10.160.25.48/sinfors/srvinfors_api" invoke-restmethod -Uri $url -body $h
参数中还可以包含json格式数据:
$a='adf' $data=@{a=$a; b=222; c=@" {"ServerName": "$env:ComputerName","IP": "$Server"} "@ } $url = "http://10.160.25.48/sinfors/srvinfors_api" invoke-restmethod -Uri $url -body $data
Python API中取参数c的字段值:
json.loads(c)['ServerName']
示例:将计算机硬件信息提交到API,该API可以将数据写入到数据库中(PS3.0):
$system = Get-WmiObject -Class Win32_ComputerSystem #获取计算机域名、型号 $domainname = $system.Domain $model = $system.Model #获取计算机IP地址,取IP和gw不为空的网卡IP地址 $Server = (gwmi Win32_NetworkAdapterConfiguration |?{ $_.DefaultIPGateway -ne $null}).IPAddress[0] #获取操作系统版本 $os = Get-WmiObject -Class Win32_OperatingSystem #获取操作系统版本 $os_caption = $os.Caption If ($os_caption.Contains("Server 2008 R2 Enterprise")) {$os_caption_s = "Win2008"} ElseIf ($os_caption.Contains("Server 2003 Enterprise")) {$os_caption_s = "Win2003"} Else {$os_caption_s = $os.Caption} $osversion = $os_caption_s + " " + $os.OSArchitecture.Substring(0,2) + "bit" #获取CPU名称、单颗CPU核心数量*CPU个数 $cpus = Get-WmiObject -Class win32_processor $cpucount = 0 Foreach ($cpu in $cpus) { If ($cpu.DeviceID -ne $null) {$cpucount += 1} } $cpunamecore = $cpu.name+""+[string]$cpu.NumberOfLogicalProcessors + '*' + [string]$cpucount + "C" #获取内存大小 $memorys = Get-WmiObject -Class Win32_PhysicalMemory #$memorylist = $null $memorysize_sum = $null Foreach ($memory in $memorys) { #$memorylist += ($memory.capacity/1024/1024/1024).tostring("F1")+"GB + " [int]$memorysize_sum_n += $memory.capacity/1024/1024/1024 } $memorysize_sum = [string]$memorysize_sum_n + "GB" #获取磁盘信息 $disks = Get-WmiObject -Class Win32_Diskdrive $disklist = $null #$disksize_sum = $null Foreach ($disk in $disks) { $disklist += ($disk.deviceid.replace("\\.\PHYSICALDRIVE","Disk") +":" + [int]($disk.size/1024/1024/1024)+"GB ") #$disksize_sum+=$disk.size } #获取计算机序列号、制造商 $bios = Get-WmiObject -Class Win32_BIOS $sn = $bios.SerialNumber If ($sn.Substring(0,6) -eq "VMware") {$sn = "VMware"} If ($bios.Manufacturer.contains("Dell")) {$manufacturer = "Dell"} Elseif ($bios.Manufacturer.contains("HP")) {$manufacturer = "HP"} Elseif ($bios.Manufacturer.contains("Microsoft")) { $manufacturer = "Microsoft" $sn = "" } Else {$manufacturer = $bios.Manufacturer} $type = $manufacturer + " " + $model if ($type.contains("Microsoft Virtual Machine")) {$type = "Hyper-V"} $serverinfoj = @{ Status="Success"; Infors= @" {"ServerName": "$env:ComputerName","IP": "$Server","OSVersion": "$osversion","MemorySize": "$memorysize_sum", "CPU": "$cpunamecore","DomainName": "$domainname","DISK": "$disklist","SN": "$sn","Type":"$type"} "@ } $url = "http://10.160.25.48/sinfors/srvinfors_api" invoke-restmethod -Uri $url -body $serverinfoj
返回值:
ServerName : PC-L
IP : 192.168.50.74
OSVersion : Microsoft Windows 10 企业版 64bit
MemorySize : 64GB
CPU : Intel(R) Core(TM) i7-5500U CPU @ 2.40GHz4*1C
DomainName : WORKGROUP
DISK : Disk0:932GB
SN : FY5DZ32
Type : Dell Inspiron 5448
示例:将计算机硬件信息提交到API,该API可以将数据写入到数据库中(PS2.0):
#客户端运行该脚本,将信息写入到数据库中,适用于PS2.0及其以上 $system = Get-WmiObject -Class Win32_ComputerSystem #获取计算机域名、型号 $domainname = $system.Domain $model = $system.Model #获取计算机IP地址,取IP和gw不为空的网卡IP地址 $Server = (gwmi Win32_NetworkAdapterConfiguration |?{ $_.DefaultIPGateway -ne $null}).IPAddress[0] #获取操作系统版本 $os = Get-WmiObject -Class Win32_OperatingSystem #获取操作系统版本 $os_caption = $os.Caption If ($os_caption.Contains("Server 2008 R2 Enterprise")) {$os_caption_s = "Win2008"} ElseIf ($os_caption.Contains("Server 2003 Enterprise")) {$os_caption_s = "Win2003"} Else {$os_caption_s = $os.Caption} $osversion = $os_caption_s + " " + $os.OSArchitecture.Substring(0,2) + "bit" #获取CPU名称、单颗CPU核心数量*CPU个数 $cpus = Get-WmiObject -Class win32_processor $cpucount = 0 Foreach ($cpu in $cpus) { If ($cpu.DeviceID -ne $null) {$cpucount += 1} } $cpunamecore = $cpu.name+""+[string]$cpu.NumberOfLogicalProcessors + '*' + [string]$cpucount + "C" #获取内存大小 $memorys = Get-WmiObject -Class Win32_PhysicalMemory #$memorylist = $null $memorysize_sum = $null Foreach ($memory in $memorys) { #$memorylist += ($memory.capacity/1024/1024/1024).tostring("F1")+"GB + " [int]$memorysize_sum_n += $memory.capacity/1024/1024/1024 } $memorysize_sum = [string]$memorysize_sum_n + "GB" #获取磁盘信息 $disks = Get-WmiObject -Class Win32_Diskdrive $disklist = $null #$disksize_sum = $null Foreach ($disk in $disks) { $disklist += ($disk.deviceid.replace("\\.\PHYSICALDRIVE","Disk") +":" + [int]($disk.size/1024/1024/1024)+"GB ") #$disksize_sum+=$disk.size } #获取计算机序列号、制造商 $bios = Get-WmiObject -Class Win32_BIOS $sn = $bios.SerialNumber If ($sn.Substring(0,6) -eq "VMware") {$sn = "VMware"} If ($bios.Manufacturer.contains("Dell")) {$manufacturer = "Dell"} Elseif ($bios.Manufacturer.contains("HP")) {$manufacturer = "HP"} Elseif ($bios.Manufacturer.contains("Microsoft")) { $manufacturer = "Microsoft" $sn = "" } Else {$manufacturer = $bios.Manufacturer} $type = $manufacturer + " " + $model if ($type.contains("Microsoft Virtual Machine")) {$type = "Hyper-V"} $Status = @" {Status:"Success"} "@ $Infors= @" {"ServerName": "$env:ComputerName","IP": "$Server","OSVersion": "$osversion","MemorySize": "$memorysize_sum", "CPU": "$cpunamecore","DomainName": "$domainname","DISK": "$disklist","SN": "$sn","Type":"$type","OS_mark":"wa"} "@ $postdata = "/?Status=" + $Status + "&Infors=" + $Infors $url = "http://10.160.25.48/sinfors/srvinfors_api" $uri = $url + $postdata #调用WebRequest方法访问接口 $request = [System.Net.WebRequest]::Create($uri) $request.KeepAlive = $false $request.AllowAutoRedirect=$false $request.Method="GET" #输出接口返回结果 $response = $request.GetResponse() $stream = $response.GetResponseStream() $reader = New-Object IO.StreamReader($stream) $html = $reader.ReadToEnd() Write-Host $html #clean up resources $reader.Close() $stream.Close() $response.Close()
#返回值:
{"DISK": "Disk0:200GB ", "DomainName": "u.com", "IP": "10.16.2.4", "ServerName": "MGMT", "MemorySize": "12GB", "SN": "", "OS_mark": "wa", "OSVersion": "Microsoft Windows Server 2012 R2 Datacenter 64bit", "Ty
pe": "Hyper-V", "CPU": "Intel(R) Xeon(R) CPU E5-2620 v3 @ 2.40GHz4*1C"}
###############################
在PowerShell2.0下没有invoke-restmethod命令可用,可以调用相应的静态类实现,通过拼接字符串方式提交参数:
1.调用System.Net.WebRequest类:
$Status = @" {Status:"Success"} "@ $Infors= @" {"ServerName": "ComputerName","IP": "192.168.1.1"} "@ $postdata = "/?Status=" + $Status + "&Infors=" + $Infors $url = "http://10.160.25.48/sinfors/srvinfors_api" $uri = $url + $postdata #调用WebRequest方法访问接口 $request = [System.Net.WebRequest]::Create($uri) $request.KeepAlive = $false $request.AllowAutoRedirect=$false $request.Method="GET" #输出接口返回结果 $response = $request.GetResponse() $stream = $response.GetResponseStream() $reader = New-Object IO.StreamReader($stream) $html = $reader.ReadToEnd() Write-Host $html #clean up resources $reader.Close() $stream.Close() $response.Close() #必须要close,否则response资源不释放,调用多次后后会出现超时。http://www.ravichaganti.com/blog/handling-system-net-webrequest-getresponse-timeout-in-powershell/
2.调用System.Net.WebClient类:
$data=@" {"ServerName":"nnn","Infors":"192.168.1.1"} "@ $url = "http://10.160.25.48/sinfors/srvinfors_api/?Infors="+$data $webclient = New-Object System.Net.WebClient $webClient.DownloadString($url) #| ConvertFrom-Json
webrequest后端接收不到数据,还有问题。。。。:
$url = "http://10.160.25.48/sinfors/srvinfors_api" $request = [Net.WebRequest]::Create($url) $request.ServicePoint.Expect100Continue = $false $request.ContentType = "application/json" $request.Method = "POST" $data = (New-Object PSObject | Add-Member -PassThru NoteProperty ServerName "nnn" | Add-Member -PassThru NoteProperty Infors "192.168.1.1" ) | ConvertTo-JSON $bytes = [System.Text.Encoding]::UTF8.GetBytes($data) $request.ContentLength = $bytes.Length $requestStream = [System.IO.Stream]$request.GetRequestStream() $requestStream.write($bytes, 0, $bytes.Length) $requestStream.Close() $response = $request.GetResponse()
查询IP所在地:
$ip="61.135.169.121" $ipSvc= 'http://ip.taobao.com/service/getIpInfo.php?ip='+ $ip # 向IP地址服务发送Rest请求 $r = Invoke-RestMethod $ipSvc $r.data |Select country,region,city,isp
通过ConvertFrom-Json读取python导出的json文件
$jsonFile = gci "d:\Temp\emps.json" $json = [System.IO.File]::ReadAllText($jsonFile.FullName) | ConvertFrom-Json foreach ($user in $json.ziduan02) { $user }