powershell
47 TopicsPowerShell 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.519KViews2likes150CommentsGet associated pool name from VIP IP using F5-LTM
I am trying to get the pool name from the VIP IP which I am getting from a input file, but I am unable to get any cmdlet related to that ``` $secpasswd = ConvertTo-SecureString "" -AsPlainText -Force $MyLTM_IP = "12.16.16.8" $mycreds = New-Object System.Management.Automation.PSCredential "rk", $secpasswd $session = $null #Create an F5 session $session = New-F5Session -LTMName $MyLTM_IP -LTMCredentials $mycreds -PassThru $get_data = Import-Csv -Path "D:\f5\IP_Addition_Input.csv" $VIP_IP = $get_data.VIPIP ``` Please let me know how can I get the pool name. going forward I have a add nodes to that pool. I am using `F5-LTM` module ``` # Download latest version $webclient = New-Object System.Net.WebClient $url = "https://github.com/joel74/POSH-LTM-Rest/archive/master.zip" Write-Host "Downloading latest version of F5-LTM from $url" -ForegroundColor Cyan $file = "$($env:TEMP)\F5-LTM.zip" $webclient.DownloadFile($url,$file) Write-Host "File saved to $file" -ForegroundColor Green # Unblock and decompress Unblock-File -Path $file $targetondisk = "$($env:USERPROFILE)\Documents\WindowsPowerShell\Modules" # no need to handle, this folder should just exist New-Item -ItemType Directory -Force -Path $targetondisk -ErrorAction SilentlyContinue | out-null # Unzip Write-Host "Uncompressing the Zip file to $($targetondisk)" -ForegroundColor Cyan $shell_app=new-object -com shell.application $zip_file = $shell_app.namespace($file) $destination = $shell_app.namespace($targetondisk) $destination.Copyhere($zip_file.items(), 0x10) # Rename and import Write-Host "Renaming folder" -ForegroundColor Cyan if (Test-Path ($targetondisk+"\F5-LTM")) { Write-Host "Removing prior $($targetondisk+"\F5-LTM") folder" -ForegroundColor Yellow Remove-Item -Recurse -Force -Path ($targetondisk+"\F5-LTM") | out-null } Move-Item -Path ($targetondisk+"\POSH-LTM-Rest-master") -Destination "$($targetondisk+"\F5-LTM")" -Force | out-null Write-Host "Module has been installed" -ForegroundColor Green Import-Module -Name "$($targetondisk+"\F5-LTM\F5-LTM")" # Zip file has a sub F5-LTM folder with the module Get-Command -Module F5-LTM <#!-------------------#> ```30Views0likes0Commentsplink command in powershell | problem with imish
Hi I'm trying to send "imish" command via powershell to f5 and it is not working I tried: imish run /util imish -r 0 both ways did not work I also tried to send the command in the same line like this: plink admin@192.168.1.1 -pw 12345 imish and via external file like this: plink admin@192.168.1.1 -pw 12345 -m E:\myfolder\imishcommand.txt Any other command like "show" or "list" is working fine If I do it gradually, step by step, first by passing the credentials and then when I'm in I write the "imish" command, it is working fine The user I'm using has the administrator level. I also tried with the local "admin" user and the "root" user. Why I'm not able to send the imish command along with the plink command Alternatively, if there is a way to check "show ip ospf neighbor" without entering the "imish"1.1KViews0likes1CommentPowerShell - Get a list of VIPs and SSL profiles (client and server)
Problem this snippet solves: Having had numerous occasions where I needed to figure out where a particular SSL profile was assigned and seeing a few similar questions here on DC, I decided to make use of PowerShell and iControlRest to get that data for me. This script allows you to grab all the VIPs on the box and list the SSL profiles (both client and server) associated with them. How to use this snippet: Prerequisites: You will need to be on BIG-IP v11.4 or newer, as that's when iControlRest was introduced. You will also need a Windows machine and PowerShell v3 or newer (v4 or v5). Paste this code into your PowerShell console and then run it with at least the hostname (or IP) of your BIG-IP, and it will prompt you for credentials and return the list of VIPs and SSL profiles. Note: If you use an IP address, you should really include the -IgnoreCertErrors flag as well, since it won't work by default without a valid cert Examples: Get-F5VipsAndSslProfiles mybigip.example.com; Get-F5VipsAndSslProfiles 10.10.10.10 -IgnoreCertErrors; Get-F5VipsAndSslProfiles -f5HostIp mybigip.example.com; Get-F5VipsAndSslProfiles -f5HostIp 10.10.10.10 -IgnoreCertErrors; $cred = (Get-Credentials); Get-F5VipsAndSslProfiles -f5HostIp 10.10.10.10 -f5Cred $cred -IgnoreCertErrors; Code : function Get-F5VipsAndSslProfiles($f5HostIp, $f5Cred, [switch]$IgnoreCertErrors = $false) { $f5Host = "https://$f5HostIp/mgmt/tm"; if ($IgnoreCertErrors) { Add-Type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@; [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy; } $sslProfilesClient = $(Invoke-RESTMethod -Method GET -Uri "$($f5Host)/ltm/profile/client-ssl?`$select=name,partition,fullPath" -Credential $f5Cred).items | Select-Object -ExpandProperty FullPath; $sslProfilesServer = $(Invoke-RESTMethod -Method GET -Uri "$($f5Host)/ltm/profile/server-ssl?`$select=name,partition,fullPath" -Credential $f5Cred).items | Select-Object -ExpandProperty FullPath; $virtualServers = $(Invoke-RESTMethod -Method GET -Uri "$($f5Host)/ltm/virtual?expandSubcollections=true&`$select=name,partitioclsn,fullPath,profilesReference" -Credential $f5Cred); $virtualServers.items | Select-Object Name, FullPath, ` @{Name="ClientSslProfiles"; Expression={($_.profilesReference.items | ?{ $sslProfilesClient -contains $_.fullPath -and $_.context -eq "clientside" }) | Select -ExpandProperty fullPath }}, ` @{Name="ServerSslProfiles"; Expression={($_.profilesReference.items | ?{ $sslProfilesServer -contains $_.fullPath -and $_.context -eq "serverside" }) | Select -ExpandProperty fullPath }}; } Tested this on version: 11.51.9KViews0likes2CommentsiControl soap
Hi! Trying to import a key/certificate with the iControl SOAP powershell snapin, but I get these errors: Exception calling "key_import_from_pem_v2" with "6" argument(s): "Exception caught in Management::urn:iControl:Management/KeyCertificate::key_import_from_pem_v2() Exception: Common::OperationFailed primary_error_code : -14 (0xFFFFFFF2) secondary_error_code : 0 error_string : Keys do not match" At C:\Scripts\LetsencryptQA\letsencrypt1.1.ps1:418 char:90 + ... rt_from_pem_v2($ManagementModetype, @($KeyName), @($StringPem), $Secu ... + ~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SoapHeaderException And for the certificate Exception calling "certificate_import_from_pem" with "4" argument(s): "Exception caught in Management::urn:iControl:Management/KeyCertificate::certificate_import_from_pem() Exception: Common::OperationFailed primary_error_code : -14 (0xFFFFFFF2) secondary_error_code : 0 error_string : Keys do not match" At C:\Scripts\LetsencryptQA\letsencrypt1.1.ps1:441 char:103 + ... om_pem($ManagementModetype, @($CertificateName), @($StringPem), $true ... + ~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SoapHeaderException ` **Importing the key with another name works though**, which would indicate that the key exists somewhere. However: `list sys file ssl-key | grep name Nothing list sys file ssl-cert | grep name Nothing ls -alR | grep name Nothing And nothing in the GUI certificate list under any partition. I have also: Done a mcpd reload and restarted the device. Manually imported the certificate and key in the Web UI (works, but then I can t reproduce the error) Any clever ideas? /Patrik325Views0likes3CommentsPowerShell to iRule AES-CBC conversation using random IV values
Problem this snippet solves: Hi Folks, I saw recently on the DevCentral boards that people are struggeling to securely exchange AES encrypted information between a Windows System and LTM. Although some DevCentral members already managed it by using static IV (Initialization Vectors) on both sites, this approach should be considered as a very bad practise, since it allows an adversary to pulloff certain crypto analyses/attacks which could already lead to a security breach. The snippets below will outline how to implement AES-CBC decryption/encryption with dynamic IV values on Windows using PowerShell and on LTM using iRules. The outlined snippets are alligned to each other by using the same AES crypto settings (Key-Size, Block-Size, CBC-Mode and Padding-Mode) and IV exchange techniques to become interoperable. The implemented IV exchange technique will generate a fresh and random IV on each single encryption and simply prepended the AES-IV to the AES-Ciphertext before passing it to the receiver. The receiver then splits the received AES-Cipherstring into the contained AES-IV and AES-Ciphertext values and finally decrypt the AES-Ciphertext by using the shared AES-Key. From Windows to LTM 1. Import the follwing PS functions on the Windows side function Create-AesKey($KeySize) { $AesManaged = New-Object "System.Security.Cryptography.AesManaged" $AesManaged.KeySize = $KeySize $AesManaged.GenerateKey() [System.Convert]::ToBase64String($AesManaged.Key) } function Encrypt-Data($AesKey, $Data) { $Data = [System.Text.Encoding]::UTF8.GetBytes($Data) $AesManaged = New-Object "System.Security.Cryptography.AesManaged" $AesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC $AesManaged.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7 $AesManaged.BlockSize = 128 $AesManaged.KeySize = 256 $AesManaged.Key = [System.Convert]::FromBase64String($AesKey) $Encryptor = $AesManaged.CreateEncryptor() $EncryptedData = $Encryptor.TransformFinalBlock($Data, 0, $Data.Length); [byte[]] $EncryptedData = $AesManaged.IV + $EncryptedData $AesManaged.Dispose() [System.Convert]::ToBase64String($EncryptedData) } function Decrypt-Data($AesKey, $Data) { $Data = [System.Convert]::FromBase64String($Data) $AesManaged = New-Object "System.Security.Cryptography.AesManaged" $AesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC $AesManaged.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7 $AesManaged.BlockSize = 128 $AesManaged.KeySize = 256 $AesManaged.IV = $Data[0..15] $AesManaged.Key = [System.Convert]::FromBase64String($AesKey) $Decryptor = $AesManaged.CreateDecryptor(); $DecryptedData = $Decryptor.TransformFinalBlock($Data, 16, $Data.Length - 16); $aesManaged.Dispose() [System.Text.Encoding]::UTF8.GetString($DecryptedData) } 2. Generate a fresh 256bit AESKey on your Windows System and store it locally as well as on your F5. Create-AesKey 256 iTEEieok7//RyzrPe5mWwz1yroPPsm4e5cqghdEHIlU= 3. Encrypt some data using the AES-Shared-Key $encrypted = Encrypt-Data " iTEEieok7//RyzrPe5mWwz1yroPPsm4e5cqghdEHIlU=" "Hello World!" $encrypted W5xFrWz72U/vt95HG6fHWIuDDHpuhj2HB42E4SIrNwo= Note: Every single encryption should have a different outcome. Thanks to the random IV! 4. Pass the AES-Cipherstring to your LTM and decrypt it using the snippet below set aes_key [b64decode "iTEEieok7//RyzrPe5mWwz1yroPPsm4e5cqghdEHIlU="] set aes_cipherstring [b64decode "W5xFrWz72U/vt95HG6fHWIuDDHpuhj2HB42E4SIrNwo="] binary scan $aes_cipherstring a16a* aes_iv aes_ciphertext set aes_plaintext [CRYPTO::decrypt -alg aes-256-cbc -key $aes_key -iv $aes_iv $aes_ciphertext] log local0.debug "Plaintext = $aes_plaintext" Log Output : Plaintext = Hello World! From LTM to Windows 1. AES encrypt some data on your LTM using the snippet below set aes_key [b64decode "iTEEieok7//RyzrPe5mWwz1yroPPsm4e5cqghdEHIlU="] set aes_plaintext "Hello World!!" set aes_iv [CRYPTO::keygen -alg random -passphrase "MyIVSeed" -len 128] set aes_ciphertext [CRYPTO::encrypt -alg aes-256-cbc -key $aes_key -iv $aes_iv $aes_plaintext] set aes_cipherstring [b64encode [binary format a*a* $aes_iv $aes_ciphertext]] log local0.debug "Cipherstring = $aes_cipherstring" Log Output : Cipherstring = vCIizWalo4KWO+3bLuTUp5iD0J3kArrcZS1fKDue89M= Note: Every single encryption should also have a different outcome. Thanks to the random IV! 2. Pass the AES-Cipherstring to your Windows system and decrypt it using the snippet below $decrypted = Decrypt-Data "iTEEieok7//RyzrPe5mWwz1yroPPsm4e5cqghdEHIlU=" "vCIizWalo4KWO+3bLuTUp5iD0J3kArrcZS1fKDue89M=" $decrypted Hello World!! Cheers, Kai How to use this snippet: See above... Code : See above...1.5KViews0likes0CommentsPowershell iControl Snapin - DISconnecting from one LTM, connecting to another - same script
We have a need to populate an address datagroup from an external database. I currently have a working proof of concept in powershell using the F5 supplied iControl snapin. Works great. However, we have a pair of LTM4000's - running active/standby. I want to cover the case where a standby swap has happened and the active is now standby. I have noticed that when I connect to the LTM using Initialize-F5.iControl that I cannot "disconnect", and that if I try to connec to to the second LTM using a second statement (with a different hostname), that all subsequent commands pull information from the FIRST connected LTM. For example, (Get-F5.iControl).ManagementDBVariable.query("hostname") will show the hostname of the first one I initialize no matter what. I'm new to powershell, and I must be missing something here. If anyone can lend a hand - the problem I'm trying to solve is: Connect to both LTM's, and determine which is active Connect to only that LTM and perform our manipulation of the address data group. Each loop through I would check and connect to only the active. Probably would also be nice to check the sync state, just in case it winds up in an inconsistent state I can abort/error. I suspect that perhaps I need to set a hostname value for each icontrol command to tell it where to go? Thanks in advance257Views0likes1CommentUsing Powershell to create an iApp Service
HI All, Long time user first time poster 🙂 I am currently tryinbg to use the REST API to automate the creatation of iApps for a project we are working on. We are trying to create a basic vServer with one pool on port 80 with no profiles, and creating this under an Application Service. using the predefied iApp http template. I am trying to use Powershell to do this, and using the PS Module that is up on GitHub (https://github.com/joel74/POSH-LTM-Rest) as the basis for my script. I have been able to run a GET and get the JSON of an existing Application Service, and changing the parameters and doing a POST it is failing with the below error Invoke-RestMethodOverride : "400 Bad Request: "name" unexpected argument At line:1 char:7 + Invoke-RestMethodOverride -Method POST -Uri "$URI" ` + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-RestMethodOverride Has been driving me crazy, any recommendations? Devcentral is not letting me upload the JSON Body cause it is too long, but below is a link to download my script, it is a txt file. https://goo.gl/4Cc3z2 Thanks407Views0likes2CommentsPowerShell - How to modify system iFile?
I use PowerShell to upload a text file containing a number of parameters that I want to use in an existing iRule. Through the web-gui I have already created an iFile named 'iFileApiKeys'. In PowerShell I use this procedure to upload the text file: $length = "0-" + ($fileContent.Length - 1) + "/" + $fileContent.Length $headers = @{ "Content-Range" = $length} $uploadResult = Invoke-WebRequest $URL -Method POST -Headers $headers -InFile $filePathPlusTextfile - ContentType "multipart/form-data" -TimeoutSec 20 -Credential $mycreds | ConvertFrom-Json Write-Host "Upload Result:" Write-Host $uploadResult According to the 'uploadResult' the file ends up in the folder:'var/config/rest/downloads/iFileApiKeys.txt' on my F5 LTM Using 'SuperPutty' I can via tmos (tmsh) modify the existing system iFile by executing: `tmos> modify /sys file ifile iFileApiKeys source-path file:///var/config/rest/downloads/iFileApiKeys.txt My problem is that I can't seem to find the correct PowerShell command to achieve the same result as the tmos (tmsh) command does. I want to use and actually think I should use: `Invoke-Webrequest -Method Put` I've been trying to emulate an example taken from a Jason Rahm post on this site: https://devcentral.f5.com/articles/getting-started-with-icontrol-working-with-the-system-20592 Like this: $sysIfilePath = "/mgmt/tm/sys/file/ifile/iFileApiKeys" `$sysPath = "https://" + $host_address + $sysIfilePath $updateresult = Invoke-WebRequest -Method Put -Uri $sysPath -Headers $headers -Credential $mycreds -Body $body But this command fails unfortunately, My assumption is that I don't fill $headers and/or $body with the correct values. When executing a GET for my sys iFile object the result is: ``{"kind":"tm:sys:file:ifile:ifilestate","name":"iFileApiKeys","fullPath":"iFileApiKeys","generation":10970077,"selfLink":"https://localhost/mgmt/tm/sys/file/ifile/iFileApiKeys?ver=13.1.0.2","chec ksum":"SHA1:878:52a261b5a113db5c9421a54e1e8b5685e7da7a4d","createTime":"2018-11-26T22:52:08Z","createdBy":"per.eriksson","lastUpdateTime":"2018-12-08T19:49:15Z","mode":33188,"revision":24,"size" :878,"sourcePath":"file:///var/config/rest/downloads/iFileApiKeys.txt","updatedBy":"per.eriksson"} Anyone out there that can point me in the right direction on how to update my sys iFile using PowerShell? Thank you! /Per766Views0likes2CommentsBackup F5 BigIP using RestAPI and PowerShell (again?)
Hello! I went through the Forum and I saw a lot of related messages but none of them actually answered my question. The documentation [I found] leaves to be desired and I hope that the community is able to help me. I am looking for a simple "backup everything and store as a file" solution and it looks like it is much more than just 2-3 RestAPI calls. So, I am able to connect and get a token. Now, I am googling the "Create Backup" command and nothing works. Could you please point me to the exact link that will create a new backup? I also think that it could be a "story" to download the backup, so I will be happy to get any advice on that also. Thanks.Solved1.9KViews0likes6Comments