microsoft powershell with icontrol
44 TopicsBigIP Report Old
Problem this snippet solves: This codeshare has been deprecated due to a hosting platform corruption. I have movedcode and conversation to a new record (on the same original URL) https://devcentral.f5.com/s/articles/bigip-report can be Overview This is a script which will generate a report of the BigIP LTM configuration on all your load balancers making it easy to find information and get a comprehensive overview of virtual servers and pools connected to them. This information is used to relay information to our NOC and developers to give them insight in where things are located and to be able to plan patching and deploys. I also use it myself as a quick way get information or gather data used as a foundation for RFC's, ie get a list of all external virtual servers without compression profiles. The script has been running on 13 pairs of load balancers, indexing over 1200 virtual servers for several years now and the report is widely used across the company and by many companies and governments across the world. It's easy to setup and use and only requires guest permissions on your devices. Demo/Preview Please note that it takes time to make these so sometimes they're a bit outdated and they only cover one HA pair. However, they still serve the purpose of showing what you can expect from the report. Interactive demo http://loadbalancing.se/bigipreportdemo/ Screen shots The main report: The device overview: Certificate details: How to use this snippet: This codeshare has been deprecated due to a hosting platform corruption. I have movedcode and conversation to a new record (on the same original URL) https://devcentral.f5.com/s/articles/bigip-report Installation instructions BigipReport REST This is the only branch we're updating since middle of 2020 and it supports 12.x and upwards (maybe even 11.6). Download:https://loadbalancing.se/downloads/bigipreport-v5.5.4.zip Documentation, installation instructions and troubleshooting:https://loadbalancing.se/bigipreport-rest/ Docker support This will be the recommended way of running bigipreport in the near future. It's still undergoing testing but it's looking really good so far. https://loadbalancing.se/2021/01/05/running-bigipreport-on-docker/ BigipReport (Legacy) Older version of the report that only runs on Windows and is depending on a Powershell plugin originally written by Joe Pruitt (F5). BigipReport (Stable): https://loadbalancing.se/downloads/bigipreport-5.3.1.zip BigipReport (BETA): https://loadbalancing.se/downloads/bigipreport-5.4.0-beta.zip iControl Snapin: https://loadbalancing.se/downloads/f5-icontrol.zip Documentation and installation instructions: https://loadbalancing.se/bigip-report/ Upgrade instructions Protect the report using APM and active directory Written by DevCentral member Shann_P: https://loadbalancing.se/2018/04/08/protecting-bigip-report-behind-an-apm-by-shannon-poole/ Got issues/problems/feedback? Still have issues? Drop a comment below. We usually reply quite fast. Any bugs found, issues detected or ideas contributed makes the report better for everyone, so it's always appreciated. --- Also trying out a Discord channel now. You're welcome to hang out with us there: https://discord.gg/7JJvPMYahA Code : 85931,86647,90730 Tested this on version: 13.026KViews16likes974CommentsPowerShell module for the F5 LTM REST API
Problem this snippet solves: To report an issue with the F5-LTM or F5-BIGIP modules, please use the Issues sections of the GitHub repos (here and here) instead of commenting here. Thanks! This PowerShell module uses the iControlREST API to manipulate and query pools, pool members, virtual servers, and iRules. It aims to support version 11.5.1 and higher, and to conform to the schedule for technical support of versions, though this may eventually prove to become difficult. The module currently includes some functionality that, strictly speaking, is outside the scope of the LTM module. Hence, there is an active effort to wrap this LTM module into a larger BIG-IP module, and relocate that functionality elsewhere within that parent module, as well as expand the scope of functionality to include BIG-IP DNS (formerly GTM) and possibly other areas. Both the LTM module and the parent BIG-IP module are projects on github. Please use these projects to report any issues you discover. Thanks! The module contains the following functions. Add-iRuleToVirtualServer Add-iRuleToVirtualServer Add-PoolMember Add-PoolMonitor Disable-PoolMember Disable-VirtualServer Enable-PoolMember Enable-VirtualServer Get-CurrentConnectionCount (deprecated; use Get-PoolMemberStats | Select-Object -ExpandProperty 'serverside.curConns') Get-F5Session (will be deprecated in future versions. use New-F5Session) Get-F5Status Get-HealthMonitor Get-HealthMonitorType Get-iRule Get-iRuleCollection (deprecated; use Get-iRule) Get-Node Get-BIGIPPartition Get-Pool Get-PoolList (deprecated; use Get-Pool) Get-PoolMember Get-PoolMemberCollection (deprecated; use Get-PoolMember) Get-PoolMemberCollectionStatus Get-PoolMemberDescription (deprecated; use Get-PoolMember) Get-PoolMemberIP (deprecated; use Get-PoolMember) Get-PoolMembers (deprecated; use Get-PoolMember) Get-PoolMemberStats Get-PoolMemberStatus (deprecated; use Get-PoolMember) Get-PoolMonitor Get-PoolsForMember Get-StatusShape Get-VirtualServer Get-VirtualServeriRuleCollection (deprecated; use Get-VirtualServer | Where rules | Select -ExpandProperty rules) Get-VirtualServerList (deprecated; use Get-VirtualServer) Invoke-RestMethodOverride New-F5Session New-HealthMonitor New-Node New-Pool New-VirtualServer Remove-HealthMonitor Remove-iRule Remove-iRuleFromVirtualServer Remove-Pool Remove-PoolMember Remove-PoolMonitor Remove-ProfileRamCache Remove-Node Remove-VirtualServer Set-iRule Set-PoolLoadBalancingMode (deprecated; use Set-Pool) Set-PoolMemberDescription Set-Pool Set-VirtualServer Sync-DeviceToGroup Test-F5Session Test-Functionality Test-HealthMonitor Test-Node Test-Pool Test-VirtualServer How to use this snippet: To use the module, click 'Download Zip', extract the files, and place them in a folder named F5-LTM beneath your PowerShell modules folder. By default, this is %USERPROFILE%\Documents\WindowsPowerShell\Modules. The WindowsPowerShell and Modules folders may need to be created. You will most likely need to unblock the files after extracting them. Use the Unblock-File PS cmdlet to accomplish this. The Validation.cs class file (based on code posted by Brian Scholer) allows for using the REST API with LTM devices with self-signed SSL certificates. Nearly all of the functions require an F5 session object as a parameter, which contains the base URL for the F5 LTM and a credential object for a user with privileges to manipulate the F5 LTM via the REST API. Use the New-F5session function to create this object. This function expects the following parameters: The name or IP address of the F5 LTM device A credential object for a user with rights to use the REST API An optional TokenLifespan value for extending the life of the authentication token past the default 20 minutes You can create a credential object using Get-Credential and entering the username and password at the prompts, or programmatically like this: $secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force $mycreds = New-Object System.Management.Automation.PSCredential "username", $secpasswd Thanks to Kotesh Bandhamravuri and his blog entry for this snippet. There is a function called Test-Functionality that takes an F5Session object, a new pool name, a new virtual server, an IP address for the virtual server, and a computer name as a pool member, and validates nearly all the functions in the module. I've also contributed this code sample for how to gather some basic info about your LTM with this PS module. The module has been tested on: 11.5.1 Build 8.0.175 Hotfix 8 and later 11.6.0 Build 5.0.429 Hotfix 4 and later 12.0 / 12.1 13.0 Code : https://github.com/joel74/POSH-LTM-Rest Tested this on version: 11.519KViews2likes150CommentsBIG-IP Report
Problem this snippet solves: Overview This is a script which will generate a report of the BIG-IP LTM configuration on all your load balancers making it easy to find information and get a comprehensive overview of virtual servers and pools connected to them. This information is used to relay information to NOC and developers to give them insight in where things are located and to be able to plan patching and deploys. I also use it myself as a quick way get information or gather data used as a foundation for RFC's, ie get a list of all external virtual servers without compression profiles. The script has been running on 13 pairs of load balancers, indexing over 1200 virtual servers for several years now and the report is widely used across the company and by many companies and governments across the world. It's easy to setup and use and only requires auditor (read-only) permissions on your devices. Demo/Preview Interactive demo http://loadbalancing.se/bigipreportdemo/ Screen shots The main report: The device overview: Certificate details: How to use this snippet: Installation instructions BigipReport REST This is the only branch we're updating since middle of 2020 and it supports 12.x and upwards (maybe even 11.6). Downloads: https://loadbalancing.se/downloads/bigipreport-v5.7.13.zip Documentation, installation instructions and troubleshooting:https://loadbalancing.se/bigipreport-rest/ Docker support https://loadbalancing.se/2021/01/05/running-bigipreport-on-docker/ Kubernetes support https://loadbalancing.se/2021/04/16/bigipreport-on-kubernetes/ BIG-IP Report (Legacy) Older version of the report that only runs on Windows and is depending on a Powershell plugin originally written by Joe Pruitt (F5) BIG-IP Report (only download this if you have v10 devices): https://loadbalancing.se/downloads/bigipreport-5.4.0-beta.zip iControl Snapin https://loadbalancing.se/downloads/f5-icontrol.zip Documentation and Installation Instructions https://loadbalancing.se/bigip-report/ Upgrade instructions Protect the report using APM and active directory Written by DevCentral member Shann_P: https://loadbalancing.se/2018/04/08/protecting-bigip-report-behind-an-apm-by-shannon-poole/ Got issues/problems/feedback? Still have issues? Drop a comment below. We usually reply quite fast. Any bugs found, issues detected or ideas contributed makes the report better for everyone, so it's always appreciated. --- Join us on Discord: https://discord.gg/7JJvPMYahA Code : BigIP Report Tested this on version: 12, 13, 14, 15, 1613KViews20likes96CommentsPowerShell Setup Snapin
Problem this snippet solves: This PowerShell script will register the iControl Snapin on 32 and 64 bit platforms. Code : param([switch]$force) function Is-SnapinRegistered() { $registered = $false; if ( $null -ne (Get-PSSnapIn -Registered | where { $_.Name -eq "iControlSnapIn" } ) ) { $registered = $true; } $registered; } function Install-Snapin() { param( [string]$assembly = $null ); foreach ($platform in ("", "64") ) { Write-Host "Registering $assembly on platform '$platform'"; $installUtil = "$env:windir\Microsoft.Net\Framework${platform}\v2.0.50727\installUtil.exe"; if ( [System.IO.File]::Exists($installUtil) ) { Set-Alias installUtil $installUtil; installUtil $assembly /LogToConsole=false /LogFile=; } } } function Remove-Snapin() { param( [string]$assembly = $null ); foreach ($platform in ("", "64") ) { Write-Host "Unregistering $assembly on platform '$platform'"; $installUtil = "$env:windir\Microsoft.Net\Framework${platform}\v2.0.50727\installUtil.exe"; if ( [System.IO.File]::Exists($installUtil) ) { Set-Alias installUtil $installUtil; installUtil /u $assembly /LogToConsole=false /LogFile=; } } } if ( ($force) -or !(Is-SnapinRegistered) ) { Install-Snapin -assembly iControlSnapin.dll; } else { Write-Host "iControlSnapIn already registered..." }1.2KViews0likes1CommentPowerShell Pool Member Availability
Problem this snippet solves: This PowerShell script will query the status of the pool members for a specified poolname. How to use this snippet: PowerShellPoolMemberAvailability.ps1 -BIGIP < bigip> -User < user> -Pass < pass> [-Pool < poolname> [-List]] Code : #---------------------------------------------------------------------------- # The contents of this file are subject to the "END USER LICENSE AGREEMENT # FOR F5 Software Development Kit for iControl"; you may not use this file # except in compliance with the License. The License is included in the # iControl Software Development Kit. # # Software distributed under the License is distributed on an "AS IS" # basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See # the License for the specific language governing rights and limitations # under the License. # # The Original Code is iControl Code and related documentation # distributed by F5. # # The Initial Developer of the Original Code is F5 Networks, # Inc. Seattle, WA, USA. Portions created by F5 are Copyright (C) 1996-2010 # F5 Networks, Inc. All Rights Reserved. iControl (TM) is a registered # trademark of F5 Networks, Inc. # # Alternatively, the contents of this file may be used under the terms # of the GNU General Public License (the "GPL"), in which case the # provisions of GPL are applicable instead of those above. If you wish # to allow use of your version of this file only under the terms of the # GPL and not to allow others to use your version of this file under the # License, indicate your decision by deleting the provisions above and # replace them with the notice and other provisions required by the GPL. # If you do not delete the provisions above, a recipient may use your # version of this file under either the License or the GPL. #---------------------------------------------------------------------------- param( [string]$BIGIP = $null, [string]$User = $null, [string]$Pass = $null, [string]$Pool = $null, [switch]$List = $false ); Set-PSDebug -strict; #------------------------------------------------------------------------- function Write-Usage() # # Print Usage information for this script #------------------------------------------------------------------------- { Write-Host "Usage: $(Split-Path -Path $MyInvocation.ScriptName -Leaf) -BIGIP -User -Pass [-Pool [-List]]"; exit; } #------------------------------------------------------------------------- function Get-PoolList() #------------------------------------------------------------------------- { $pool_list = (Get-F5.iControl).LocalLBPool.get_list(); Write-Host "Available Pools:"; foreach ($pool in $pool_list) { Write-Host " $pool"; } } #------------------------------------------------------------------------- function Get-PoolMemberAvailability() #------------------------------------------------------------------------- { param([string]$Pool); $avail_count = 0; $total_count = 0; if ( $Pool.Length -ne 0 ) { $MemberObjectStatusAofA = (Get-F5.iControl).LocalLBPoolMember.get_object_status((, $Pool)); # Only one pool, so let's access the members for first entry of returned array. $MemberObjectStatusA = $MemberObjectStatusAofA[0]; foreach ($MemberObjectStatus in $MemberObjectStatusA) { $member = $MemberObjectStatus.member; $addr = $member.address; $port = $member.port; $Availability = $MemberObjectStatus.object_status.availability_status; $Enabled = $MemberObjectStatus.object_status.enabled_status; $Description = $MemberObjectStatus.object_status.status_description; $total_count++; if ( $Availability -eq "AVAILABILITY_STATUS_GREEN" ) { $avail_count++; } if ($List) { Write-Host "$Pool,${addr}:${port},$Availability,$Enabled,$Description"; } } if (!$List) { Write-Host "$avail_count/$total_count" } } } #------------------------------------------------------------------------- function Do-Initialize() #------------------------------------------------------------------------- { if ( (Get-PSSnapin | Where-Object { $_.Name -eq "iControlSnapIn"}) -eq $null ) { Add-PSSnapIn iControlSnapIn } $success = Initialize-F5.iControl -HostName $BIGIP -Username $User -Password $Pass; return $success; } #------------------------------------------------------------------------- # Main Application Logic #------------------------------------------------------------------------- if ( ($BIGIP.Length -eq 0) -or ($User.Length -eq 0) -or ($Pass.Length -eq 0) ) { Write-Usage; } if ( Do-Initialize ) { if ( $Pool.Length -eq 0 ) { Get-PoolList; } else { Get-PoolMemberAvailability -Pool $Pool; } }599Views0likes3CommentsASM Policy Report
Problem this snippet solves: PowerShell script using F5 iControls that produces an email report of all ASM policies and what websites they protect. If a policy is enabled at the HTTP Class, it will be presented via a green table. Disabled policies will be presented via a red table. Code : # ============================================================================================== # # COMMENT: used on our 1600 running v11 to email out a weekly report of websites protected by the ASM # # Created from Ps Config Archiving @https://devcentral.f5.com/s/wiki/iControl.PsConfigArchiving.ashx # # ============================================================================================== # Customize the following six variables $g_file = "C:\Folder\File.txt" # ref: http://technet.microsoft.com/en-us/magazine/ff714574.aspx $g_uid = "F5User" $g_bigip = "F5.domain.com" $g_email_to = "recipient@domain.com" $g_email_from = "ASM Policy Report " $g_email_smtp = "smtp.domain.com" Set-PSDebug -strict; Function Get-ASMPolicyList(){ $ASMPolicyList = (Get-F5.iControl).ASMWebApplication.get_list() | Select-String "/Common/*" | %{$_.line.substring(8)} | Sort-Object Return $ASMPolicyList } # End Get-ASMPolicyList Function Function Get-LogonPwd(){ $a1 = Get-Content -Path $g_file | ConvertTo-SecureString $b1 = New-Object system.management.automation.pscredential($g_uid,$a1) $ReturnValue = $b1.GetNetworkCredential().password Return $ReturnValue } # End Get-Logon Function function Get-PolicyState($PolicyName){ $FullPolicyName = "/Common/$PolicyName" $PolicyState = ((Get-F5.iControl).ASMWebApplication).get_enabled_state($FullPolicyName) Return $PolicyState } # End Get-PolicyState Function Function Do-Initialize($pwd){ if ( (Get-PSSnapin | Where-Object { $_.Name -eq "iControlSnapIn"}) -eq $null ){ Add-PSSnapIn iControlSnapIn } $success = Initialize-F5.iControl -HostName $g_bigip -Username $g_uid -Password $PWD; return $success; } # End Do-Initialize Function Function Get-PolicyPatterns($PolicyName){ $PolicyPatterns = (Get-F5.iControl).LocalLBProfileHttpClass.get_host_match_pattern($PolicyName) | %{$_.values} | Format-Table Pattern -HideTableHeaders | Out-String Return $PolicyPatterns.trim() } # End Get-PolicyPatterns Function Function Get-EmailSendFunc($SUBJECT,$BODY){ Send-MailMessage -SmtpServer $g_email_smtp -To $g_email_to -From $g_email_from -Subject $SUBJECT -Body $BODY -BodyAsHtml } # End Get-EmailFunc Function Function Get-TableFormat($heading,$contents,$state){ $contentsHTML = "" if($contents.length -gt 1){ $contents = $contents.split(" ") | Where-Object {$_ -ne ""} | %{$_.trim()} foreach($item in $contents){ $contentsHTML += "$item" } } if($state -eq $true){ [string]$TableFormatReturn = " $heading $contentsHTML " } else { [string]$TableFormatReturn = " $heading $contentsHTML " } Return $TableFormatReturn } # End Get-TableFormat Function #------------------------------------------------------------------------- # Main Application Logic #------------------------------------------------------------------------- $g_pwd = Get-LogonPwd if(Do-Initialize -pwd $g_pwd){ [string]$MainBody = "" $MainBody = " " $MainBody += ".table1{border-width: 2px;border-style: solid;border-color: black;border-collapse: collapse;}" $MainBody += ".table1 TH{border-width:2px;padding:4px;border-style:solid;border-color:black;background-color:green;text-align:left;font-size:14px;color:white}" $MainBody += ".table1 TD{border-width:2px;border-style:solid;border-color:black;font-size:10px}" $MainBody += ".table2{border-width: 2px;border-style: solid;border-color: black;border-collapse: collapse;}" $MainBody += ".table2 TH{border-width:2px;padding:4px;border-style:solid;border-color:black;background-color:red;text-align:left;font-size:14px;color:white}" $MainBody += ".table2 TD{border-width:2px;border-style:solid;border-color:black;font-size:10px}" $MainBody += " " $MainBodyFooter = " Red indicates disabled policies while green indicates enabled policies. " $MainASMPolicyList = Get-ASMPolicyList foreach($MainASMPolicy in $MainASMPolicyList){ $MainPolicyState = Get-PolicyState -PolicyName $MainASMPolicy $MainPolicyPattern = Get-PolicyPatterns -PolicyName $MainASMPolicy $MainPolicyPatternHTML = Get-TableFormat -heading $MainASMPolicy -contents $MainPolicyPattern -state $MainPolicyState $MainBody = $MainBody + $MainPolicyPatternHTML } $MainBody += $MainBodyFooter $emailDate = (get-date).tostring("MMMM dd") Get-EmailSendFunc -SUBJECT "ASM Policy Report - $emailDate" -BODY $MainBody } else { Get-EmailFunc -SUBJECT "FAILED: Do-Initialize" -BODY "ASM Policy Report" } Exit Exit505Views0likes1CommentPs Self Ip Port Lockdown
Problem this snippet solves: A Self IP address is an IP address that you associate with a VLAN, to access hosts in that VLAN. By virtue of its netmask, a self IP address represents an address space, that is, a range of IP addresses spanning the hosts in the VLAN, rather than a single host address. You can associate self IP addresses not only with VLANs, but also with VLAN group. Self IP addresses serve two purposes. First, when sending a message to a destination server, the BIG-IP system uses the self IP addresses of its VLANs to determine the specific VLAN in which a destination server resides. Second, a self IP address serves as the default route for each destination server in the corresponding VLAN. In this case, the self IP address of a VLAN appears as the destination IP address in the packet header when the server sends a response to the BIG-IP system. Each self IP address has a feature known as port lockdown. Port lockdown is a security feature that allows you to specify particular UDP and TCP protocols and services from which the self IP address can accept traffic. This application illustrates how how to use the iControl API to manage Port Lockdown Access Lists. Code : #---------------------------------------------------------------------------- # The contents of this file are subject to the "END USER LICENSE AGREEMENT FOR F5 # Software Development Kit for iControl"; you may not use this file except in # compliance with the License. The License is included in the iControl # Software Development Kit. # # Software distributed under the License is distributed on an "AS IS" # basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See # the License for the specific language governing rights and limitations # under the License. # # The Original Code is iControl Code and related documentation # distributed by F5. # # The Initial Developer of the Original Code is F5 Networks, # Inc. Seattle, WA, USA. Portions created by F5 are Copyright (C) 1996-2009 F5 Networks, # Inc. All Rights Reserved. iControl (TM) is a registered trademark of F5 Networks, Inc. # # Alternatively, the contents of this file may be used under the terms # of the GNU General Public License (the "GPL"), in which case the # provisions of GPL are applicable instead of those above. If you wish # to allow use of your version of this file only under the terms of the # GPL and not to allow others to use your version of this file under the # License, indicate your decision by deleting the provisions above and # replace them with the notice and other provisions required by the GPL. # If you do not delete the provisions above, a recipient may use your # version of this file under either the License or the GPL. #---------------------------------------------------------------------------- param ( $g_bigip = $null, $g_uid = $null, $g_pwd = $null, $g_cmd = $null, $g_selfip = $null, $g_arg1 = $null, $g_arg2 = $null, $g_arg3 = $null, $g_arg4 = $null ); Set-PSDebug -strict; #------------------------------------------------------------------------- # function Write-Usage #------------------------------------------------------------------------- function Write-Usage() { Write-Host @" Usage: SelfIPPortLockdown.ps1 host uid pwd [options] options ------- list - Get a list of Self IPs getaccesslist - Gets the access lists for the specified self IP. addaccesslist - Adds the list of access methods, with optional protocols/ports, for the specified self IP. deleteaccesslist - Deletes protocols and ports from the allow access list for the specified self IP. getdefaccesslist - Gets the default protocol/port access list on which access is allowed. adddefaccesslist - Adds to the default list of protocols/ports on which access is allowed. removedefaccesslist - Remove protocols and ports from the default list of protocols/ports on which access is allowed. "@; exit; } #------------------------------------------------------------------------- # Get-SelfIPList #------------------------------------------------------------------------- function Get-SelfIPList() { $ip_list = (Get-F5.iControl).NetworkingSelfIP.get_list(); Write-Host "Available SelfIPs:"; foreach ($ip in $ip_list) { Write-Host " $ip"; } } #------------------------------------------------------------------------- # function Get-AccessList #------------------------------------------------------------------------- function Get-AccessList() { param([string]$selfip = $null); $pld = (Get-F5.iControl).NetworkingSelfIPPortLockdown; $SelfIPAccessA = $pld.get_allow_access_list( (,$selfip) ); foreach ($SelfIPAccess in $SelfIPAccessA) { Write-Host "--------------------------------"; Write-Host "Self IP : " $SelfIPAccess.self_ip; Write-Host "Mode : " $SelfIPAccess.mode; Write-Host "Protocol Ports : "; $pA = $SelfIPAccess.protocol_ports; foreach ($ProtocolPort in $pA) { Write-Host " Protocol : " $ProtocolPort.protocol; Write-Host " Port : " $ProtocolPort.port; } } } #------------------------------------------------------------------------- # function Add-AccessList #------------------------------------------------------------------------- function Add-AccessList() { param( [string]$selfip = $null, [string]$mode = "ALLOW_MODE_NONE", [string]$protocol = "PROTOCOL_ANY", [int]$port = 0); $pld = (Get-F5.iControl).NetworkingSelfIPPortLockdown; $SelfIPAccess = New-Object -TypeName iControl.NetworkingSelfIPPortLockdownSelfIPAccess; $SelfIPAccess.self_ip = $selfip; $SelfIPAccess.mode = $mode; $SelfIPAccess.protocol_ports = New-Object -TypeName iControl.NetworkingSelfIPPortLockdownProtocolPort; $(${SelfIPAccess}.protocol_ports).protocol = $protocol; $(${SelfIPAccess}.protocol_ports).port = $port; $pld.add_allow_access_list( (,$SelfIPAccess) ); Get-AccessList $selfip; } #------------------------------------------------------------------------- # function Delete-AccessList #------------------------------------------------------------------------- function Delete-AccessList() { param( [string]$selfip = $null, [string]$mode = "ALLOW_MODE_NONE", [string]$protocol = "PROTOCOL_ANY", [int]$port = 0); $pld = (Get-F5.iControl).NetworkingSelfIPPortLockdown; $SelfIPAccess = New-Object -TypeName iControl.NetworkingSelfIPPortLockdownSelfIPAccess; $SelfIPAccess.self_ip = $selfip; $SelfIPAccess.mode = $mode; $SelfIPAccess.protocol_ports = New-Object -TypeName iControl.NetworkingSelfIPPortLockdownProtocolPort; $(${SelfIPAccess}.protocol_ports).protocol = $protocol; $(${SelfIPAccess}.protocol_ports).port = $port; $pld.delete_allow_access_list( (,$SelfIPAccess) ); Get-AccessList $selfip; } #------------------------------------------------------------------------- # function Get-DefaultAccessList #------------------------------------------------------------------------- function Get-DefaultAccessList() { $pld = (Get-F5.iControl).NetworkingSelfIPPortLockdown; $ProtocolPortA = $pld.get_default_protocol_port_access_list(); if ( $ProtocolPortA.Length ) { foreach ($ProtocolPort in $ProtocolPortA) { Write-Host "--------------------------------"; Write-Host "Protocol : " $ProtocolPort.protocol; Write-Host " Port : " $ProtocolPort.port; } } else { Write-Host "No default Protocol Port Access Lists defined"; } } #------------------------------------------------------------------------- # function Add-DefaultAccessList #------------------------------------------------------------------------- function Add-DefaultAccessList() { param([string]$protocol = "PROTOCOL_ANY", [int]$port = 0); $pld = (Get-F5.iControl).NetworkingSelfIPPortLockdown; $protocol_port = New-Object -TypeName iControl.NetworkingSelfIPPortLockdownProtocolPort; $protocol_port.protocol = $protocol; $protocol_port.port = $port; $pld.add_default_protocol_port_access_list( (,$protocol_port) ); Get-DefaultAccessList; } #------------------------------------------------------------------------- # function Remove-DefaultAccessList #------------------------------------------------------------------------- function Remove-DefaultAccessList() { param([string]$protocol = "PROTOCOL_ANY", [int]$port = 0); $pld = (Get-F5.iControl).NetworkingSelfIPPortLockdown; $protocol_port = New-Object -TypeName iControl.NetworkingSelfIPPortLockdownProtocolPort; $protocol_port.protocol = $protocol; $protocol_port.port = $port; $pld.remove_default_protocol_port_access_list( (,$protocol_port) ); Get-DefaultAccessList; } #------------------------------------------------------------------------- # Do-Initialize #------------------------------------------------------------------------- function Do-Initialize() { if ( (Get-PSSnapin | Where-Object { $_.Name -eq "iControlSnapIn"}) -eq $null ) { Add-PSSnapIn iControlSnapIn } $success = Initialize-F5.iControl -HostName $g_bigip -Username $g_uid -Password $g_pwd; return $success; } #------------------------------------------------------------------------- # Main Application Logic #------------------------------------------------------------------------- if ( ($g_bigip -eq $null) -or ($g_uid -eq $null) -or ($g_pwd -eq $null) ) { Write-Usage; } if ( Do-Initialize ) { switch ($g_cmd) { "" { Get-SelfIPList; } "getaccesslist" { Get-AccessList $g_selfip; } "addaccesslist" { Add-AccessList $g_selfip $g_arg1 $g_arg2 $g_arg3 $g_arg4; } "deleteaccesslist" { Delete-AccessList $g_selfip; } "getdefaccesslist" { Get-DefaultAccessList $g_selfip; } "adddefaccesslist" { Add-DefaultAccessList $g_selfip $g_arg1 $g_arg2; } "removedefaccesslist" { Remove-DefaultAccessList $g_selfip $g_arg1 $g_arg2; } default { Write-Usage; } } } else { Write-Error "ERROR: iControl subsystem not initialized" }434Views0likes0CommentsPs Twitter Api
Problem this snippet solves: Here is a set of PowerShell functions that give access to the Twitter web based APIs allowing you to interact with the Twitter service from within Windows PowerShell. How to use this snippet: Twitter Functions Internal Helpers function Shrink-Url() function Shrink-Links() function Set-TwitterCredentials() function Get-TwitterCredentials() function Execute-HTTPGetCommand() function Execute-HTTPPostCommand() function Process-TwitterStatus() Status function Get-TwitterPublicTimeline() function Get-TwitterFriendsTimeline() function Get-TwitterUserTimeline() function Get-TwitterStatus() function Set-TwitterStatus() function Get-TwitterReplies() function Destroy-TwitterStatus() User function Process-TwitterUsers() function Get-TwitterFriends() function Get-TwitterFollowers() function Get-TwitterUser() Direct Messages function Process-TwitterDirectMessages() function Get-TwitterDirectMessages() function Get-TwitterSentDirectMessages() function New-TwitterDirectMessage() function Destroy-TwitterDirectMessage() Friendship function Get-TwitterFriendshipExists function Process-Ids() function Get-TwitterSocialGraphFriendIds() function Get-TwitterSocialGraphFollowerIds() Account function Is-ValidHexColor() function Verify-TwitterCredentials() function End-TwitterSession() function Set-TwitterDeliveryDevice() function Set-TwitterProfileColors() function Set-TwitterProfileImage() function Set-TwitterProfileBackgroundImage() function Get-TwitterRateLimitStatus() function Set-TwitterProfile() Favorites function Get-TwitterFavorites() function Create-TwitterFavorite() function Destroy-TwitterFavorite() Notification function Follow-TwitterUser() function Leave-TwitterUser() Block function Create-TwitterBlock() function Destroy-TwitterBlock() Help function Get-TwitterHelpTest() function Get-TwitterDowntimeSchedule() 3rd Party Services function Get-TwitterCounterStats() function Get-GroupMemberList() Code : #---------------------------------------------------------------------------- # The contents of this file are subject to the "END USER LICENSE AGREEMENT # FOR F5 Software Development Kit for iControl"; you may not use this file # except in compliance with the License. The License is included in the # iControl Software Development Kit. # # Software distributed under the License is distributed on an "AS IS" # basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See # the License for the specific language governing rights and limitations # under the License. # # The Original Code is iControl Code and related documentation # distributed by F5. # # The Initial Developer of the Original Code is F5 Networks, # Inc. Seattle, WA, USA. Portions created by F5 are Copyright (C) 1996-2008 # F5 Networks, Inc. All Rights Reserved. iControl (TM) is a registered # trademark of F5 Networks, Inc. # # Alternatively, the contents of this file may be used under the terms # of the GNU General Public License (the "GPL"), in which case the # provisions of GPL are applicable instead of those above. If you wish # to allow use of your version of this file only under the terms of the # GPL and not to allow others to use your version of this file under the # License, indicate your decision by deleting the provisions above and # replace them with the notice and other provisions required by the GPL. # If you do not delete the provisions above, a recipient may use your # version of this file under either the License or the GPL. #---------------------------------------------------------------------------- [void] [Reflection.Assembly]::LoadWithPartialName("System.Web") [void] [Reflection.Assembly]::LoadWithPartialName("System.Text") [System.Net.ServicePointManager]::Expect100Continue = $false; $script:g_creds = $null; #============================================================================ # Shared Functions #============================================================================ #---------------------------------------------------------------------------- # function Shrink-Url #---------------------------------------------------------------------------- function Shrink-Url() { param([string]$longurl = $null, [string]$provider = "tinyurl"); $shorturl = $null; if ( $longurl ) { switch ($provider.ToLower()) { "is.gd" { $shorturl = Execute-HTTPGetCommand "http://is.gd/api.php?longurl=$longurl"; } "tinyurl" { $shorturl = Execute-HTTPGetCommand "http://tinyurl.com/api-create.php?url=$longurl"; } "snipurl" { $shorturl = Execute-HTTPGetCommand "http://snipurl.com/site/snip?r=simple&link=$longurl"; } default { $shorturl = Execute-HTTPGetCommand "http://tinyurl.com/api-create.php?url=$longurl"; } } } $shorturl; } #---------------------------------------------------------------------------- # function Shrink-Links #---------------------------------------------------------------------------- function Shrink-Links() { param([string]$text = $null, [string]$provider = "tinyurl"); [regex]$regex="(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?" if ($text -match $regex) { $link = $matches[0] } #if an embedded url was found, convert it to a shortened link if ($link) { $shrunklink = Shrink-Url $link $text = $text.Replace($link, $shrunklink) } $text; } #---------------------------------------------------------------------------- # function Set-TwitterCredentials #---------------------------------------------------------------------------- function Set-TwitterCredentials() { param([string]$user = $null, [string]$pass = $null); if ( $user -and $pass ) { $script:g_creds = New-Object System.Net.NetworkCredential -argumentList ($user, $pass); } else { $creds = Get-TwitterCredentials; } } #---------------------------------------------------------------------------- # function Get-TwitterCredentials #---------------------------------------------------------------------------- function Get-TwitterCredentials() { if ( $null -eq $g_creds ) { trap { Write-Error "ERROR: You must enter your Twitter credentials for PoshTweet to work!"; continue; } $c = Get-Credential if ( $c ) { $user = $c.GetNetworkCredential().Username; $pass = $c.GetNetworkCredential().Password; $script:g_creds = New-Object System.Net.NetworkCredential -argumentList ($user, $pass); } } $script:g_creds; } #---------------------------------------------------------------------------- # function Execute-HTTPGetCommand #---------------------------------------------------------------------------- function Execute-HTTPGetCommand() { param([string] $url = $null); if ( $url ) { [System.Net.WebClient]$webClient = New-Object System.Net.WebClient if ( $url.ToLower().Contains("twitter.com") ) { $webClient.Credentials = Get-TwitterCredentials } [System.IO.Stream]$stream = $webClient.OpenRead($url); [System.IO.StreamReader]$sr = New-Object System.IO.StreamReader -argumentList $stream; [string]$results = $sr.ReadToEnd(); $results; } } #---------------------------------------------------------------------------- # function Execute-HTTPPostCommand #---------------------------------------------------------------------------- function Execute-HTTPPostCommand() { param([string] $url = $null, [string] $data = $null); if ( $url -and $data ) { [System.Net.WebRequest]$webRequest = [System.Net.WebRequest]::Create($url); $webRequest.ServicePoint.Expect100Continue = $false; if ( $url.ToLower().Contains("twitter.com") ) { $webRequest.Credentials = Get-TwitterCredentials $webRequest.PreAuthenticate = $true; } $webRequest.ContentType = "application/x-www-form-urlencoded"; $webRequest.Method = "POST"; $webRequest.Headers.Add("X-Twitter-Client", "PoshTweet"); $webRequest.Headers.Add("X-Twitter-Version", "1.0"); $webRequest.Headers.Add("X-Twitter-URL", "http://devcentral.f5.com/s/poshtweet"); [byte[]]$bytes = [System.Text.Encoding]::UTF8.GetBytes($data); $webRequest.ContentLength = $bytes.Length; [System.IO.Stream]$reqStream = $webRequest.GetRequestStream(); $reqStream.Write($bytes, 0, $bytes.Length); $reqStream.Flush(); [System.Net.WebResponse]$resp = $webRequest.GetResponse(); $rs = $resp.GetResponseStream(); [System.IO.StreamReader]$sr = New-Object System.IO.StreamReader -argumentList $rs; [string]$results = $sr.ReadToEnd(); $results; } } #============================================================================ # Status Functions #============================================================================ #---------------------------------------------------------------------------- # Helper functions #---------------------------------------------------------------------------- function Process-TwitterStatus() { param([string]$sxml = $null, [bool]$raw = $false); if ( $sxml ) { if ( $raw ) { $sxml; } else { [xml]$xml = $sxml; if ( $xml.statuses.status ) { $stats = $xml.statuses.status; } elseif ($xml.status ) { $stats = $xml.status; } $stats | Foreach-Object -process { $info = "by " + $_.user.screen_name + ", " + $_.created_at; if ( $_.source ) { $info = $info + " via " + $_.source; } if ( $_.in_reply_to_screen_name ) { $info = $info + " in reply to " + $_.in_reply_to_screen_name; } "-------------------------"; $_.text; $info; }; "-------------------------"; } } } #---------------------------------------------------------------------------- # public_timeline #---------------------------------------------------------------------------- function Get-TwitterPublicTimeline() { param([bool]$raw = $false); $results = Execute-HTTPGetCommand "http://twitter.com/statuses/public_timeline.xml"; Process-TwitterStatus $results $raw; } #---------------------------------------------------------------------------- # friends_timeline #---------------------------------------------------------------------------- function Get-TwitterFriendsTimeline() { param ( [string]$since = $null, [int]$since_id = $null, [int]$count = $null, [int]$page = $null, [bool]$raw = $false ); if ( $since ) { $args = "?since=$since"; } if ( $since_id ) { if ( $args ) { $args = "${args}&" } else { $args = "?" } $args = "${args}since_id=$since_id"; } if ( $count ) { if ( $args ) { $args = "${args}&" } else { $args = "?" } $args = "${args}count=$count"; } if ( $page ) { if ( $args ) { $args = "${args}&" } else { $args = "?" } $args = "${args}page=$page"; } Write-Host "Requesting URI: http://twitter.com/statuses/friends_timeline.xml${args}"; $results = Execute-HTTPGetCommand "http://twitter.com/statuses/friends_timeline.xml${args}"; Process-TwitterStatus $results $raw } #---------------------------------------------------------------------------- #user_timeline #---------------------------------------------------------------------------- function Get-TwitterUserTimeline() { param([string]$username = $null, [bool]$raw = $false); if ( $username ) { $username = "/$username"; } $results = Execute-HTTPGetCommand "http://twitter.com/statuses/user_timeline$username.xml"; Process-TwitterStatus $results $raw } #---------------------------------------------------------------------------- # show #---------------------------------------------------------------------------- function Get-TwitterStatus() { param([string]$id, [bool]$raw = $false); if ( $id ) { $results = Execute-HTTPGetCommand "http://twitter.com/statuses/show/" + $id + ".xml"; Process-TwitterStatus $results $raw; } } #---------------------------------------------------------------------------- # update #---------------------------------------------------------------------------- function Set-TwitterStatus() { param([string]$status, [int]$in_reply_to_status_id = $null, [bool]$raw = $false); $encstatus = [System.Web.HttpUtility]::UrlEncode("$status"); $args = "status=$encstatus"; if ( $in_reply_to_status_id ) { $args += "&in_reply_to_status_id=${in_reply_to_status_id}"; } $results = Execute-HTTPPostCommand "http://twitter.com/statuses/update.xml" $args; Process-TwitterStatus $results $raw; } #---------------------------------------------------------------------------- # replies #---------------------------------------------------------------------------- function Get-TwitterReplies() { param([bool]$raw = $false); $results = Execute-HTTPGetCommand "http://twitter.com/statuses/replies.xml"; Process-TwitterStatus $results $raw; } #---------------------------------------------------------------------------- # destroy #---------------------------------------------------------------------------- function Destroy-TwitterStatus() { param([string]$id = $null); if ( $id ) { Execute-HTTPPostCommand "http://twitter.com/statuses/destroy/$id.xml", "id=$id"; } } #============================================================================ # User Functions #============================================================================ #---------------------------------------------------------------------------- # Helper functions #---------------------------------------------------------------------------- function Process-TwitterUsers() { param([string]$sxml = $null, [bool]$raw = $false); if ( $sxml ) { if ( $raw ) { $sxml; } else { [xml]$xml = $sxml; if ( $xml.users.user ) { $user = $xml.users.user; } elseif ($xml.user ) { $user = $xml.user; } $user | Foreach-Object -process { $id = $_.id; $screen_name = $_.screen_name; $name = $_.name; $desc = $_.description; $url = $_.url; $followers_count = $_.followers_count; $last_status = $_.status.text; "-------------------------"; "$screen_name / $name (# $id , $followers_count followers) / $url"; "Bio: $desc"; "Tweet: $last_status"; }; "-------------------------"; } } } #---------------------------------------------------------------------------- # friends #---------------------------------------------------------------------------- function Get-TwitterFriends() { param([string]$id_or_screenname, [string]$page = $null, [bool]$raw = $false); if ( $id_or_screenname ) { $id_or_screenname = "/$id_or_screenname"; } if ( $page ) { $page = "?page=$page"; } Write-Host "Requesting: http://twitter.com/statuses/friends$id_or_screenname.xml$page"; $results = Execute-HTTPGetCommand "http://twitter.com/statuses/friends$id_or_screenname.xml$page"; Process-TwitterUsers $results $raw; } #---------------------------------------------------------------------------- # followers #---------------------------------------------------------------------------- function Get-TwitterFollowers() { param([string]$id_or_screenname, [string]$page = $null, [bool]$raw = $false); if ( $id_or_screenname ) { $id_or_screenname = "/$id_or_screenname"; } if ( $page ) { $page = "?page=$page"; } Write-Host "Requesting: http://twitter.com/statuses/followers$id_or_screenname.xml$page"; $results = Execute-HTTPGetCommand "http://twitter.com/statuses/followers$id_or_screenname.xml$page"; Process-TwitterUsers $results $raw; } #---------------------------------------------------------------------------- # show #---------------------------------------------------------------------------- function Get-TwitterUser() { param([string]$id = $null, [string]$email = $null, [bool]$raw = $false); $url = $null; if ( $id ) { $url = "http://twitter.com/users/show/$id.xml"; } elseif ( $email ) { $url = "http://twitter.com/users/show.xml?email=$email"; } if ( $url ) { $results = Execute-HTTPGetCommand $url; PRocess-TwitterUsers $results $raw; } } #============================================================================ # Direct Message Functions #============================================================================ #---------------------------------------------------------------------------- # Helper functions #---------------------------------------------------------------------------- function Process-TwitterDirectMessages() { param([string]$sxml = $null, [bool]$raw = $false); if ( $sxml ) { if ( $raw ) { $sxml; } else { [xml]$xml = $sxml; if ( $xml.{direct-messages}.direct_message ) { $dm = $xml.{direct-messages}.direct_message; } elseif ($xml.direct_message ) { $dm = $xml.direct_message; } $dm | Foreach-Object -process { $id = $_.id; $text = $_.text; $sender_screen_name = $_.sender_screen_name; $name = $_.sender.name; $created_at = $_.created_at; "-------------------------"; "(DM #$id) $text"; "by $sender_screen_name / $name on $created_at"; }; "-------------------------"; } } } #---------------------------------------------------------------------------- # direct_messages #---------------------------------------------------------------------------- function Get-TwitterDirectMessages() { param([string]$since = $null, [string]$since_id = $null, [string]$page = $null, [bool]$raw = $false); $args = $null; if ( $since ) { $args = "?since=$since"; } elseif ( $since_id ) { $args = "?since_id=$since_id"; } elseif ( $page ) { $args = "?page=$page"; } $results = Execute-HTTPGetCommand "http://twitter.com/direct_messages.xml$args"; Process-TwitterDirectMessages $results $raw; } #---------------------------------------------------------------------------- # sent #---------------------------------------------------------------------------- function Get-TwitterSentDirectMessages() { param([string]$since = $null, [string]$since_id = $null, [string]$page = $null, [bool]$raw = $false); $args = $null; if ( $since ) { $args = "?since=$since"; } elseif ( $since_id ) { $args = "?since_id=$since_id"; } elseif ( $page ) { $args = "?page=$page"; } $results = Execute-HTTPGetCommand "http://twitter.com/direct_messages/sent.xml$args"; Process-TwitterDirectMessages $results $raw; } #---------------------------------------------------------------------------- # new #---------------------------------------------------------------------------- function New-TwitterDirectMessage() { param([string]$user = $null, [string]$text = $null, [bool]$raw = $false); if ( $user -and $text ) { $enctext = [System.Web.HttpUtility]::UrlEncode("$text"); $results = Execute-HTTPPostCommand "http://twitter.com/direct_messages/new.xml" "user=$user&text=$enctext" Process-TwitterDirectMessages $results $raw; } } #---------------------------------------------------------------------------- # destroy #---------------------------------------------------------------------------- function Destroy-TwitterDirectMessage() { param([string]$id = $null); if ( $id ) { $results = Execute-HTTPPostCommand "http://twitter.com/direct_messages/destroy/$id.xml" "id=$id"; } } #============================================================================ # Friendship Functions #============================================================================ #---------------------------------------------------------------------------- # create #---------------------------------------------------------------------------- function Create-TwitterFriendship() { param([string]$id = $null, [bool]$follow = $true, [bool]$raw = $false); if ( $id ) { $follow = $follow.ToString().ToLower(); $results = Execute-HTTPPostCommand "http://twitter.com/friendsips/create/${id}.xml" "id=${id}&follow=${follow}" Process-TwitterUsers $results $raw; } } #---------------------------------------------------------------------------- # destroy #---------------------------------------------------------------------------- function Destroy-TwitterFriendship() { param([string]$id = $null, [bool]$raw = $false); if ( $id ) { $results = Execute-HTTPPostCommand "http://twitter.com/friendships/destroy/${id}.xml" "id=${id}" $results; Process-TwitterUsers $results $raw; } } #---------------------------------------------------------------------------- # exists #---------------------------------------------------------------------------- function Get-TwitterFriendshipExists { param([string]$user_a = $null, [string]$user_b = $null); if ( $user_a -and $user_b ) { $results = Execute-HTTPGetCommand "http://twitter.com/friendships/exists.xml?user_a=${user_a}&user_b=${user_b}"; $results; } } #============================================================================ # Social Graph Functions #============================================================================ #---------------------------------------------------------------------------- # Helper Functions #---------------------------------------------------------------------------- function Process-Ids() { param([string]$sxml = $null, [bool]$raw = $false); if ( $sxml ) { if ( $raw ) { $sxml; } else { [xml]$x = $sxml; $i = 1; $x.ids.id | ForEach-Object -Process { $info = "[$i] : " + $_; $info; $i++; } } } } #---------------------------------------------------------------------------- # ids (friends) #---------------------------------------------------------------------------- function Get-TwitterSocialGraphFriendIds() { param([string]$id = $null, [bool]$raw = $false); $args = ""; if ( $id ) { $args = "?id=${id}"; } $results = Execute-HTTPGetCommand "http://twitter.com/friends/ids.xml$args"; Process-Ids $results $raw; } #---------------------------------------------------------------------------- # ids (followers) #---------------------------------------------------------------------------- function Get-TwitterSocialGraphFollowerIds() { param([string]$id = $null, [bool]$raw = $false); $args = ""; if ( $id ) { $args = "?id=${id}"; } $results = Execute-HTTPGetCommand "http://twitter.com/followers/ids.xml$args"; Process-Ids $results $raw; } #============================================================================ # Account Functions #============================================================================ #---------------------------------------------------------------------------- # helper functions #---------------------------------------------------------------------------- function Is-ValidHexColor() { param([string]$color_in_hex = $null) [bool]$valid = $false; if ( $color_in_hex ) { [regex]$regex3 = "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"; [regex]$regex6 = "[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]"; if ( ($color_in_hex.Length -eq 3) -and ($color_in_hex -match $regex3) ) { $valid = $true; } elseif ( ($color_in_hex.Length -eq 6) -and ($color_in_hex -match $regex6) ) { $valid = $true; } } $valid; } #---------------------------------------------------------------------------- # verify_credentials #---------------------------------------------------------------------------- function Verify-TwitterCredentials() { $results = Execute-HTTPGetCommand "http://twitter.com/account/verify_credentials.xml"; $results; } #---------------------------------------------------------------------------- # end_session #---------------------------------------------------------------------------- function End-TwitterSession() { $results = Execute-HTTPPostCommand "http://twitter.com/account/end_session.xml" ""; $results; } #---------------------------------------------------------------------------- # update_delivery_device #---------------------------------------------------------------------------- function Set-TwitterDeliveryDevice() { param([string]$device = $null); if ( $device ) { if ( $device.Equals("sms") -or $device.Equals("im") -or $device.Equals("none") ) { $results = Execute-HTTPPostCommand "http://twitter.com/account/update_delivery_device.xml?device=$device" "device=$device"; $results; } else { Write-Error "device must be either sms, im, or none!" } } } #---------------------------------------------------------------------------- # update_profile_colors #---------------------------------------------------------------------------- function Set-TwitterProfileColors() { param( [string]$background_color = $null, [string]$text_color = $null, [string]$link_color = $null, [string]$sidebar_fill_color = $null, [string]$sidebar_border_color = $null); $args = $null; if ( $background_color ) { if ( Is-ValidHexColor $background_color ) { if ( $args ) { $args = "$args&"; } $args = "${args}profile_background_color=$background_color"; } else { Write-Error "background_color '$background_color' must be a 3 or 6 valid hexadecimal value!"; } } if ( $text_color ) { if ( Is-ValidHexColor $text_color ) { if ( $args ) { $args = "$args&"; } $args = "${args}profile_text_color=$text_color"; } else { Write-Error "text_color '$text_color' must be a 3 or 6 valid hexadecimal value!"; } } if ( $link_color ) { if ( Is-ValidHexColor $link_color ) { if ( $args ) { $args = "$args&"; } $args = "${args}profile_link_color=$link_color"; } else { Write-Error "link_color '$link_color' must be a 3 or 6 valid hexadecimal value!"; } } if ( $sidebar_fill_color ) { if ( Is-ValidHexColor $sidebar_fill_color ) { if ( $args ) { $args = "$args&"; } $args = "${args}profile_sidebar_fill_color=$sidebar_fill_color"; } else { Write-Error "sidebar_fill_color '$sidebar_fill_color' must be a 3 or 6 valid hexadecimal value!"; } } if ( $sidebar_border_color ) { if ( Is-ValidHexColor $sidebar_border_color ) { if ( $args ) { $args = "$args&"; } $args = "${args}profile_sidebar_border_color=$sidebar_border_color"; } else { Write-Error "sidebar_border_color '$sidebar_border_color' must be a 3 or 6 valid hexadecimal value!"; } } if ( $args ) { Write-Host "http://twitter.com/account/update_profile_colors.xml - $args"; $results = Execute-HTTPPostCommand "http://twitter.com/account/update_profile_colors.xml" $args; $results; } } #---------------------------------------------------------------------------- # update_profile_image #---------------------------------------------------------------------------- function Set-TwitterProfileImage() { param([string]$image = $null); if ( $image ) { $results = Execute-HTTPPostCommand "http://twitter.com/account/update_profile_image.xml" "image=$image"; $results; } } #---------------------------------------------------------------------------- # update_profile_background_image #---------------------------------------------------------------------------- function Set-TwitterProfileBackgroundImage() { param([string]$image = $null); if ( $image ) { $results = Execute-HTTPPostCommand "http://twitter.com/account/update_profile_background_image.xml" "image=$image"; $results; } } #---------------------------------------------------------------------------- # rate_limit_status #---------------------------------------------------------------------------- function Get-TwitterRateLimitStatus() { param([bool]$raw = $false); $sXml = Execute-HTTPGetCommand "http://twitter.com/account/rate_limit_status.xml"; if ( $sXml ) { if ( $raw ) { $sXml; } else { [xml]$results = $sXml; $remaining_hits = $results.hash.{remaining-hits}.get_InnerText(); $hourly_limit = $results.hash.{hourly-limit}.get_InnerText(); $reset_time_in_seconds = $results.hash.{reset-time-in-seconds}.get_InnerText(); $reset_time = $results.hash.{reset-time}.get_InnerText(); "Remaining Hits: $remaining_hits"; "Hourly Limit : $hourly_limit"; "Reset Time (s): $reset_time_in_seconds s."; "Reset Time : $reset_time"; } } } #---------------------------------------------------------------------------- # update_profile #---------------------------------------------------------------------------- function Set-TwitterProfile() { param( [string]$name = $null, [string]$email = $null, [string]$url = $null, [string]$location = $null, [string]$description = $null); $args = $null; if ( $name ) { if ( $args ) { $args = "$args&"; } $args = "${args}name=$name"; } if ( $email ) { if ( $args ) { $args = "$args&"; } $args = "${args}email=$email"; } if ( $url ) { if ( $args ) { $args = "$args&"; } $args = "${args}url=$url"; } if ( $location ) { if ( $args ) { $args = "$args&"; } $args = "${args}location=$location"; } if ( $description ) { if ( $args ) { $args = "$args&"; } $args = "${args}description=$description"; } if ( $args ) { $results = Execute-HTTPPostCommand "http://twitter.com/account/update_profile.xml" $args; $results; } } #============================================================================ # Favorite Functions #============================================================================ #---------------------------------------------------------------------------- # favorites #---------------------------------------------------------------------------- function Get-TwitterFavorites() { param([string]$id, [string]$page = $null, [bool]$raw = $false); if ( $id ) { $id = "/$id"; } if ( $page ) { $page = "?page=$page"; } $results = Execute-HTTPGetCommand "http://twitter.com/favorites${id}.xml${page}"; Process-TwitterStatus $results $raw; } #---------------------------------------------------------------------------- # create #---------------------------------------------------------------------------- function Create-TwitterFavorite() { param([string]$id, [bool]$raw = $false); if ( $id ) { $id = "/$id"; } $results = Execute-HTTPPostCommand "http://twitter.com/favorites/create${id}.xml" "id=${id}"; Process-TwitterStatus $results $raw; } #---------------------------------------------------------------------------- # destroy #---------------------------------------------------------------------------- function Destroy-TwitterFavorite() { param([string]$id, [bool]$raw = $false); if ( $id ) { $id = "/$id"; } $results = Execute-HTTPPostCommand "http://twitter.com/favorites/destroy${id}.xml" "id=${id}"; Process-TwitterStatus $results $raw; } #============================================================================ # Notification Functions #============================================================================ #---------------------------------------------------------------------------- # follow #---------------------------------------------------------------------------- function Follow-TwitterUser() { param([string]$id, [bool]$raw = $false); if ( $id ) { $results = Execute-HTTPPostCommand "http://twitter.com/notifications/follow/${id}.xml" "id=${id}"; Process-TwitterUsers $results $raw; } } #---------------------------------------------------------------------------- # leave #---------------------------------------------------------------------------- function Leave-TwitterUser() { param([string]$id, [bool]$raw = $false); if ( $id ) { $results = Execute-HTTPPostCommand "http://twitter.com/notifications/leave/${id}.xml" "id=${id}"; Process-TwitterUsers $results $raw; } } #============================================================================ # Block Functions #============================================================================ #---------------------------------------------------------------------------- # create #---------------------------------------------------------------------------- function Create-TwitterBlock() { param([string]$id, [bool]$raw = $false); if ( $id ) { $results = Execute-HTTPPostCommand "http://twitter.com/blocks/create/${id}.xml" "id=${id}"; Process-TwitterUsers $results $raw; } } #---------------------------------------------------------------------------- # destroy #---------------------------------------------------------------------------- function Destroy-TwitterBlock() { param([string]$id, [bool]$raw = $false); if ( $id ) { $results = Execute-HTTPPostCommand "http://twitter.com/blocks/destroy/${id}.xml" "id=${id}"; Process-TwitterUsers $results $raw; } } #============================================================================ # Help Functions #============================================================================ #---------------------------------------------------------------------------- # test #---------------------------------------------------------------------------- function Get-TwitterHelpTest() { $results = Execute-HTTPGetCommand "http://twitter.com/help/test.xml"; $results; } #---------------------------------------------------------------------------- # downtime_schedule #---------------------------------------------------------------------------- function Get-TwitterDowntimeSchedule() { $results = Execute-HTTPGetCommand "http://twitter.com/help/downtime_schedule.xml"; $results; } #============================================================================ # TwitterCounter #============================================================================ #---------------------------------------------------------------------------- # Get-TwitterCounterStats #---------------------------------------------------------------------------- function Get-TwitterCounterStats() { param([string]$username = $null, [int]$results = 14, [bool]$raw = $false); $output = "xml"; $stats = $null; if ( $username ) { $stats = Execute-HTTPGetCommand "http://twittercounter.com/api/?username=$username&output=$output&results=$results" } if ( !$raw ) { $stats = [xml]$stats; $stats.twittercounter } else { $stats; } } #============================================================================ # Utilities #============================================================================ function Get-GroupMemberList() { param([string]$url = $null, [string]$tagstart = $null); if ( $tagstart -eq $null ) { $tagstart = "entrybody"; } # Posh Twitter Users "http://www.mindofroot.com/powershell-twitterers/"; if ( $url ) { $site = Execute-HTTPGetRequest $url; $previous = @() $start = $site.IndexOf(' ') $site = $site.substring($start) $start = $site.IndexOf(' ') $site = $site.substring($start) $end = $site.IndexOf(' ') + 5 [xml]$doc = $site.substring(0,$end) $results = $doc.ul.li | select @{name='Name';Expression={$_.a.'#text'}}, @{name='TwitterURL';Expression={$_.a.href}}, @{name='UserName';Expression={$_.a.href -replace 'http://twitter.com/'}} $results = $results[1..($results.count-1)] return $results } }394Views0likes0CommentsPs Pool Member Control
Problem this snippet solves: This question comes up quite often here on DevCentral: "How can I gracefully shut down my servers for maintenance without disrupting current user sessions?". In fact, I answered this question just the other day again in the iControl forum and figured I'd throw out an application that accomplished this. So I went about writing this application to allow for the graceful shutdown of a given pool member. Of course, the application wouldn't be complete without listing the pools and members for a specified pool as well as allowing for enabling and disabling of the server so I went ahead and included those pieces as a bonus. Code : #---------------------------------------------------------------------------- # The contents of this file are subject to the "END USER LICENSE AGREEMENT FOR F5 # Software Development Kit for iControl"; you may not use this file except in # compliance with the License. The License is included in the iControl # Software Development Kit. # # Software distributed under the License is distributed on an "AS IS" # basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See # the License for the specific language governing rights and limitations # under the License. # # The Original Code is iControl Code and related documentation # distributed by F5. # # The Initial Developer of the Original Code is F5 Networks, # Inc. Seattle, WA, USA. Portions created by F5 are Copyright (C) 1996-2007 F5 Networks, # Inc. All Rights Reserved. iControl (TM) is a registered trademark of F5 Networks, Inc. # # Alternatively, the contents of this file may be used under the terms # of the GNU General Public License (the "GPL"), in which case the # provisions of GPL are applicable instead of those above. If you wish # to allow use of your version of this file only under the terms of the # GPL and not to allow others to use your version of this file under the # License, indicate your decision by deleting the provisions above and # replace them with the notice and other provisions required by the GPL. # If you do not delete the provisions above, a recipient may use your # version of this file under either the License or the GPL #---------------------------------------------------------------------------- param ( $g_bigip = $null, $g_uid = $null, $g_pwd = $null, $g_pool = $null, $g_member = $null, $g_mode = $null ); Set-PSDebug -strict; #------------------------------------------------------------------------- # function Write-Usage #------------------------------------------------------------------------- function Write-Usage() { Write-Host "Usage: PoolMemberControl.ps1 host uid pwd [pool [member:ip [mode = "enable"|"disable"]]]"; exit; } #------------------------------------------------------------------------- # Get-Pools #------------------------------------------------------------------------- function Get-Pools() { $pool_list = (Get-F5.iControl).LocalLBPool.get_list(); Write-Host "Available Pools:"; foreach ($pool in $pool_list) { Write-Host " $pool"; } } #------------------------------------------------------------------------- # Get-PoolMembers #------------------------------------------------------------------------- Function Get-PoolMembers() { param($pool_name); $member_lists = (Get-F5.iControl).LocalLBPool.get_member((, $pool_name)); Write-Host "Members for Pool ${pool_name}:" foreach($member in $member_lists[0]) { $addr = $member.address; $port = $member.port; Write-Host " ${addr}:${port}" } } #------------------------------------------------------------------------- # Get-PoolMemberStatus #------------------------------------------------------------------------- Function Get-PoolMemberStatus() { param($pool_name, $member); $vals = $member.Split( (, ':')); $member_addr = $vals[0]; $member_port = $vals[1]; $bFound = 0; $MemberObjectStatusAofA = (Get-F5.iControl).LocalLBPoolMember.get_object_status((, $pool_name)); foreach($MemberObjectStatus in $MemberObjectStatusAofA[0]) { $a2 = $MemberObjectStatus.member.address; $p2 = $MemberObjectStatus.member.port; if ( "${member_addr}:${member_port}" -eq "${a2}:${p2}" ) { $Availability = $MemberObjectStatus.object_status.availability_status; $Enabled = $MemberObjectStatus.object_status.enabled_status; $Description = $MemberObjectStatus.object_status.status_description; Write-Host "Pool $pool_name, Member ${member_addr}:${member_port} status:" Write-Host " Availability : $Availability" Write-Host " Enabled : $Enabled" Write-Host " Description : $Description" $bFound = 1; } } if ( $bFound -eq 0 ) { Write-Host "Member ${member_addr}:${member_port} could not be found in pool $pool_name!" } } #------------------------------------------------------------------------- # Enable-Member #------------------------------------------------------------------------- function Enable-Member() { param($pool_name, $member); $vals = $member.Split( (, ':')); $member_addr = $vals[0]; $member_port = $vals[1]; $MemberMonitorState = New-Object -TypeName iControl.LocalLBPoolMemberMemberMonitorState; $MemberMonitorState.member = New-Object -TypeName iControl.CommonIPPortDefinition; $MemberMonitorState.member.address = $member_addr; $MemberMonitorState.member.port = $member_port; $MemberMonitorState.monitor_state = "STATE_ENABLED"; $MemberMonitorStateAofA = New-Object -TypeName "iControl.LocalLBPoolMemberMemberMonitorState[][]" 1,1 $MemberMonitorStateAofA[0][0] = $MemberMonitorState; Write-Host "Setting Montior State to Enabled"; (Get-F5.iControl).LocalLBPoolMember.set_monitor_state( (, $pool_name), $MemberMonitorStateAofA); $MemberSessionState = New-Object -TypeName iControl.LocalLBPoolMemberMemberSessionState; $MemberSessionState.member = New-Object -TypeName iControl.CommonIPPortDefinition; $MemberSessionState.member.address = $member_addr; $MemberSessionState.member.port = $member_port; $MemberSessionState.session_state = "STATE_ENABLED"; $MemberSessionStateAofA = New-Object -TypeName "iControl.LocalLBPoolMemberMemberSessionState[][]" 1,1 $MemberSessionStateAofA[0][0] = $MemberSessionState; Write-Host "Setting Session Enabled State to Enabled"; (Get-F5.iControl).LocalLBPoolMember.set_session_enabled_state( (, $pool_name), $MemberSessionStateAofA); Get-PoolMemberStatus $pool_name $member } #------------------------------------------------------------------------- # Disable-Member #------------------------------------------------------------------------- function Disable-Member() { param($pool_name, $member); $vals = $member.Split( (, ':')); $member_addr = $vals[0]; $member_port = $vals[1]; Write-Host "Disabling Session Enabled State..."; $MemberSessionState = New-Object -TypeName iControl.LocalLBPoolMemberMemberSessionState; $MemberSessionState.member = New-Object -TypeName iControl.CommonIPPortDefinition; $MemberSessionState.member.address = $member_addr; $MemberSessionState.member.port = $member_port; $MemberSessionState.session_state = "STATE_DISABLED"; $MemberSessionStateAofA = New-Object -TypeName "iControl.LocalLBPoolMemberMemberSessionState[][]" 1,1 $MemberSessionStateAofA[0][0] = $MemberSessionState; (Get-F5.iControl).LocalLBPoolMember.set_session_enabled_state( (, $pool_name), $MemberSessionStateAofA); Write-Host "Waiting for current connections to drop to zero..." $MemberDef = New-Object -TypeName iControl.CommonIPPortDefinition; $MemberDef.address = $member_addr; $MemberDef.port = $member_port; $MemberDefAofA = New-Object -TypeName "iControl.CommonIPPortDefinition[][]" 1,1 $MemberDefAofA[0][0] = $MemberDef; $cur_connections = 1; while ( $cur_connections -gt 0 ) { $MemberStatisticsA = (Get-F5.iControl).LocalLBPoolMember.get_statistics( (, $pool_name), $MemberDefAofA); $MemberStatisticEntry = $MemberStatisticsA[0].statistics[0]; $Statistics = $MemberStatisticEntry.statistics; foreach ($Statistic in $Statistics) { $type = $Statistic.type; $value = $Statistic.value; if ( $type -eq "STATISTIC_SERVER_SIDE_CURRENT_CONNECTIONS" ) { # just use the low value. Odds are there aren't over 2^32 current connections. # If your site is this big, you'll have to convert this to a 64 bit number. $cur_connections = $value.low; Write-Host "Current Connections: $cur_connections" } } Start-Sleep -s 1 } Write-Host "Disabling Monitor State..."; $MemberMonitorState = New-Object -TypeName iControl.LocalLBPoolMemberMemberMonitorState; $MemberMonitorState.member = New-Object -TypeName iControl.CommonIPPortDefinition; $MemberMonitorState.member.address = $member_addr; $MemberMonitorState.member.port = $member_port; $MemberMonitorState.monitor_state = "STATE_DISABLED"; $MemberMonitorStateAofA = New-Object -TypeName "iControl.LocalLBPoolMemberMemberMonitorState[][]" 1,1 $MemberMonitorStateAofA[0][0] = $MemberMonitorState; (Get-F5.iControl).LocalLBPoolMember.set_monitor_state( (, $pool_name), $MemberMonitorStateAofA); Get-PoolMemberStatus $pool_name $member } #------------------------------------------------------------------------- # Do-Initialize #------------------------------------------------------------------------- function Do-Initialize() { if ( (Get-PSSnapin | Where-Object { $_.Name -eq "iControlSnapIn"}) -eq $null ) { Add-PSSnapIn iControlSnapIn } $success = Initialize-F5.iControl -HostName $g_bigip -Username $g_uid -Password $g_pwd; return $success; } #------------------------------------------------------------------------- # Main Application Logic #------------------------------------------------------------------------- if ( ($g_bigip -eq $null) -or ($g_uid -eq $null) -or ($g_pwd -eq $null) ) { Write-Usage; } if ( Do-Initialize ) { if ( $g_pool -eq $null ) { Get-Pools; } elseif ( $g_member -eq $null ) { Get-PoolMembers $g_pool; } elseif ( $g_mode -eq $null ) { Get-PoolMemberStatus $g_pool $g_member; } else { switch ($g_mode.ToLower()) { "enable" { Enable-Member $g_pool $g_member; } "disable" { Disable-Member $g_pool $g_member; } default { Write-Usage; } } } } else { Write-Error "ERROR: iControl subsystem not initialized" }306Views0likes0Comments