c
15 Topicsdelete_devices
Problem this snippet solves: Introduced: EM_v3.0 Use the delete_devices API to remove devices currently being managed by an Enterprise Manager. How to use this snippet: Prototype Python ic.Management.EM.deletedevices(deviceaddresses) C#, Java, and Perl ic.getManagementEM().delete_devices(deviceAddresses); Inputs Name Type Description IP addresses String Sequence This parameter specifies the IP addresses or hostnames of the F5 device(s) that you want to delete from the list of managed devices. Return values There is no explicit return when this API executes successfully. Exceptions The table lists error categories that Enterprise Manager can raise if the API call fails. Exception Name This exception is raised when... AccessDenied The credentials supplied by the client do not satisfy the F5 device's validation requirements. OperationFailed The API call causes an operation error. InvalidArgument The API call contains an invalid argument. Code : To view a code sample, click the relevant code type. C# (.net) Java Perl Python289Views0likes0Commentsget_task_status
Problem this snippet solves: Introduced : EM_v3.0 Use the get_task_status API to determine the current status of a device discovery task. How to use this snippet: Python ic.Management.EM.get_task_status(ids = task_ids) C#, Java, and Perl ic.Management.EM.get_task_status(ids = task_ids); Inputs Name Type Description tasks String Sequence This parameter specifies the task IDs of the tasks for which you want to know the status. Return Values Name Type Description task TaskStatus Sequence The ID of the new discovery task. This ID can return the following values: TASK_STATUS_UNKNOWN TASK_STATUS_PENDING TASK_STATUS_STARTED TASK_STATUS_FAILED TASK_STATUS_COMPLETE TASK_STATUS_RUNNING TASK_STATUS_CANCELING TASK_STATUS_CANCELED TASK_STATUS_ABANDONED TASK_STATUS_TERMINATED TASK_STATUS_TIMED_OUT TASK_STATUS_RESCHEDULED Exceptions Exception Name This exception is raised when... AccessDenied The credentials supplied by the client do not satisfy the F5 device's validation requirements. OperationFailed The API call causes an operation error. InvalidArgument The API call contains an invalid argument. Code : To view a code sample, click the relevant code type. C# (.net) Java Perl Python269Views0likes0CommentsGet all certificates and their virtual servers and SSL profiles via API calls
Problem this snippet solves: Summary F5 will give you a decent report of all your certificates and their expiration dates. However I have not found a way to pull what Virtual Server or SSL Profile the certificates are applied to (or if they are used at all). What this code does is grabs all the virtual servers, all SSL profiles, and all certificates. Then it loops through them to find where a certificate is applied. Then it returns the certificate and virtual server info. I wrote this in C# but the logic can be used anywhere as the API calls are independent of language. How to use this snippet: You will need some way to compile C#. Easiest way is to use Visual Studio. Simply add your API credentials and IP addresses and run the code through a C# compiler. Code : https://github.com/matthewwedlow/F5_Scripts/blob/master/GetCerts.cs2.4KViews1like3CommentsC# Making Async Calls using the iControlAssembly
Problem this snippet solves: This C# example application shows three different ways to make iControl calls Asynchronously using the An iControlAssembly library. Each way serves a slightly different purpose depending on the needs of the application. Code : using System; using System.Collections.Generic; using System.Text; using iControl; using System.Diagnostics; using System.Threading; namespace iControlAssemblyAsyncExample { class AsyncExample { private static Thread mainThread; static void Main(string[] args) { Stopwatch sw = null; Interfaces m_Interfaces = null; IAsyncResult ar = null; string[] poolList = null; //////////////////////////////////////////////////////////////////////////////// // Synchronously connect to the BigIP Appliance Console.WriteLine("Establishing connection to Appliance."); sw = Stopwatch.StartNew(); m_Interfaces = new Interfaces("hostname", "username", "password"); Console.WriteLine("Connection completed in {0} ms\n", sw.ElapsedMilliseconds); //////////////////////////////////////////////////////////////////////////////// // Synchronously Retrieve the Pool List Console.WriteLine("Beginning syncronous Pool list retrieval."); sw = Stopwatch.StartNew(); poolList = m_Interfaces.LocalLBPool.get_list(); Console.WriteLine("Syncronous retrieval completed in {0} ms\n", sw.ElapsedMilliseconds); //////////////////////////////////////////////////////////////////////////////// // Asynchronously retrieve the Pool List, do something and then wait // for the Async call to complete. Console.WriteLine("Beginning async retrieval with wait."); sw = Stopwatch.StartNew(); ar = m_Interfaces.LocalLBPool.Beginget_list(null, null); // Do some work, which may or may not take longer than // the Async call to execute. Console.WriteLine("Done some work after {0} ms. Now waiting.",sw.ElapsedMilliseconds); ar.AsyncWaitHandle.WaitOne(); // Wait indefinitely for the Async Call to complete ar.AsyncWaitHandle.Close(); poolList = m_Interfaces.LocalLBPool.Endget_list(ar); Console.WriteLine("Asyncronous retrieval completed in {0} ms\n", sw.ElapsedMilliseconds); //////////////////////////////////////////////////////////////////////////////// // Asynchronously Retrieve the Pool List while doing something indefinitely. Console.Write("Beginning inline async retrieval"); sw = Stopwatch.StartNew(); ar = m_Interfaces.LocalLBPool.Beginget_list(null, null); while (ar.IsCompleted == false) { Console.Write("."); // Continually to something until the Async Thread.Sleep(15); // call has completed. } poolList = m_Interfaces.LocalLBPool.Endget_list(ar); Console.WriteLine("\nAsyncronous retrieval completed in {0} ms\n", sw.ElapsedMilliseconds); //////////////////////////////////////////////////////////////////////////////// // Asynchronously Retrieve the Pool List with a Callback AsyncCallback myCallBackRoutine = new AsyncCallback(MyAsyncCallback); mainThread = Thread.CurrentThread; Console.WriteLine("Beginning Callback Async retrieval"); sw = Stopwatch.StartNew(); ar = m_Interfaces.LocalLBPool.Beginget_list(myCallBackRoutine, m_Interfaces); try { while (true) { Console.Write("."); // Do something useful while we Thread.Sleep(15); // wait for the Callback to complete. } } catch (ThreadInterruptedException) { Console.WriteLine("\nAsyncronous Callback retrieval completed in {0} ms\n", sw.ElapsedMilliseconds); } Console.WriteLine("Press ANY key to exit."); Console.ReadKey(); } private static void MyAsyncCallback(IAsyncResult ar) { Interfaces m_Interfaces = (Interfaces)ar.AsyncState; string[] poolList = m_Interfaces.LocalLBPool.Endget_list(ar); int c = 0; while (c < 7) { Console.Write("X"); // Do something useful while the main Thread.Sleep(15); // thread is doing what it needs to c++; } mainThread.Interrupt(); } } }490Views0likes1CommentUp/Down Nodes: Visual C#
Problem this snippet solves: This app enables and disables nodes. It installs and runs as a stand alone windows application. It connects to an LTM, collects the pools, collects pool members, and allows the user to toggle the enabled/disabled state of nodes. This is my first iControl App. It is also my first run at C# and Visual Studio. It is pretty basic and a little rough around the edges. I am posting it because I did not find many examples of C# using Visual Studio. I plagiarized from other code examples found on DevCentral so you may see some similarities if you look around. The entire project is attached as a .zip. Code : using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public class poolmember { public string poolname { get; set; } public string address { get; set; } public Int64 port { get; set; } public iControl.LocalLBSessionStatus status { get; set; } public iControl.CommonAddressPort addressport { get; set; } } List _poolmember = new List (); //iControl.CommonAddressPort my_addressport() = ""; iControl.Interfaces interfaces = new iControl.Interfaces(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void label6_Click(object sender, EventArgs e) { } private void label7_Click(object sender, EventArgs e) { } private void label5_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { lblVersion.Text = "Connecting ..."; lblFailover.Text = ""; lblHostname.Text = ""; if (interfaces.initialize(txtIPAddr.Text, txtAccount.Text, txtPasswd.Text)) { lblVersion.Text = interfaces.SystemSystemInfo.get_version(); lblFailover.Text = Convert.ToString(interfaces.SystemFailover.get_failover_state()); lblHostname.Text = Convert.ToString(interfaces.ManagementDevice.get_local_device()); string[] pools = interfaces.LocalLBPool.get_list(); foreach (string pool in pools) { lstBxPools.Items.Add(pool); } } else { lblVersion.Text = "Connection Failure"; } } private void lstBxPools_SelectedIndexChanged(object sender, EventArgs e) { if (lstBxPools.SelectedIndex >= 0) { btnGetMembers.Enabled = true; } else { btnGetMembers.Enabled = false; } } private void button1_Click_1(object sender, EventArgs e) { lstbxMembers.Items.Clear(); // List > members = new List >(); string[] pool = new string[1] { lstBxPools.Text }; // lstbxMemUp.Items.Add(lstBxPools.Text); iControl.CommonAddressPort[][] memberlist = interfaces.LocalLBPool.get_member_v2(pool); foreach (iControl.CommonAddressPort member in memberlist[0]) { poolmember node = new poolmember { poolname = lstBxPools.Text, address = member.address, port = member.port, addressport = member, }; _poolmember.Add(node); } foreach (poolmember member in _poolmember) { //Method requires a multi-dimensional array for input. Add CommonAddressPort to new List List convertedserverlist = new List { member.addressport }; //Convert List to Array for input into the next method iControl.CommonAddressPort[] targetarry = convertedserverlist.ToArray(); //Call the BIG-IP - Inputs are an array of Pool Names and a multi-dimensional array of CommonAddressPorts iControl.LocalLBSessionStatus[][] targetstatus = interfaces.LocalLBPool.get_member_session_status(new[] { member.poolname }, new[] { targetarry }); //Only requested a single pool, so specify the first dimension and collect data for output. foreach (iControl.LocalLBSessionStatus status in targetstatus[0]) { lstbxMembers.Items.Add(member.address + ":" + member.port + " " + status); member.status = status; } } _poolmember.Clear(); } private void btnDown_Click(object sender, EventArgs e) { if (lstbxMembers.Text.Contains("SESSION_STATUS_ENABLED")) { label7.Text = "saw Session Status ENABLED"; // string[] poolname = { lstBxPools.Text }; // interfaces.LocalLBPool.set_member_session_enabled_state(poolname[0], my_addressport[1][1], iControl.CommonEnabledState.STATE_DISABLED); string node = lstbxMembers.Text.Split(':')[0]; label7.Text = node; string[] node_a = {node}; iControl.CommonEnabledState[] states = new iControl.CommonEnabledState[] { iControl.CommonEnabledState.STATE_DISABLED }; interfaces.LocalLBNodeAddressV2.set_session_enabled_state(node_a, states); } else if (lstbxMembers.Text.Contains("SESSION_STATUS_ADDRESS_DISABLED")) { string node = lstbxMembers.Text.Split(':')[0]; string[] node_a = { node }; iControl.CommonEnabledState[] states = new iControl.CommonEnabledState[] { iControl.CommonEnabledState.STATE_ENABLED }; interfaces.LocalLBNodeAddressV2.set_session_enabled_state(node_a, states); } else { } lstbxMembers.Items.Clear(); // List > members = new List >(); string[] pool = new string[1] { lstBxPools.Text }; // lstbxMemUp.Items.Add(lstBxPools.Text); iControl.CommonAddressPort[][] memberlist = interfaces.LocalLBPool.get_member_v2(pool); foreach (iControl.CommonAddressPort member in memberlist[0]) { poolmember node = new poolmember { poolname = lstBxPools.Text, address = member.address, port = member.port, addressport = member, }; _poolmember.Add(node); } foreach (poolmember member in _poolmember) { //Method requires a multi-dimensional array for input. Add CommonAddressPort to new List List convertedserverlist = new List { member.addressport }; //Convert List to Array for input into the next method iControl.CommonAddressPort[] targetarry = convertedserverlist.ToArray(); //Call the BIG-IP - Inputs are an array of Pool Names and a multi-dimensional array of CommonAddressPorts iControl.LocalLBSessionStatus[][] targetstatus = interfaces.LocalLBPool.get_member_session_status(new[] { member.poolname }, new[] { targetarry }); //Only requested a single pool, so specify the first dimension and collect data for output. foreach (iControl.LocalLBSessionStatus status in targetstatus[0]) { lstbxMembers.Items.Add(member.address + ":" + member.port + " " + status); member.status = status; } } _poolmember.Clear(); } } }406Views0likes1CommentC# Polling Default Pool Connections
Problem this snippet solves: This C# application will display the current connections for all of the default pools. There was found to be too much overhead when sending in the list of all pools, some of which were empty so this app strips out the virtual servers with non-defined default pools and batches up requests for statistics. Code : using System; using System.Collections.Generic; using System.Text; using iControl; using System.Diagnostics; namespace PRVD.iControl.GetAllPoolCurrentConnections { class Program { static void Main(string[] args) { if (args.Length < 3 || string.IsNullOrEmpty(args[0]) || string.IsNullOrEmpty(args[1]) || string.IsNullOrEmpty(args[2])) { Console.WriteLine( "Usage: f5GetAllPoolCurrentConnections [username] [password] [hostname or ip address] optional [partition]"); return; } string user = args[0]; string pass = args[1]; string ipAddress = args[2]; string partition = ""; if (args.Length > 3 && !string.IsNullOrEmpty(args[3])) partition = args[3]; Interfaces m_interfaces = new Interfaces(); m_interfaces.initialize(ipAddress, user, pass); //Check if inialized if (!m_interfaces.initialized) Environment.Exit(Environment.ExitCode); //Get the partition list to drop into PROD bool partitionFound = false; ManagementPartitionAuthZPartition[] partitionList = m_interfaces.ManagementPartition.get_partition_list(); for (int i = 0; i < partitionList.Length; i++) { Console.WriteLine("Partition found: {0}", partitionList[ i ].partition_name); if (partitionList[ i ].partition_name == partition) { m_interfaces.ManagementPartition.set_active_partition(partitionList[ i ].partition_name); partitionFound = true; } } if (!partitionFound) { Console.WriteLine("The partition '{0}' specified was not found.", partition); return; } //Get all virtual servers string[] localVirtualServers = m_interfaces.LocalLBVirtualServer.get_list(); //PrintInfo(localVirtualServers); //Get all the active default pools string[] localDefaultPools = m_interfaces.LocalLBVirtualServer.get_default_pool_name(localVirtualServers); //PrintInfo(localDefaultPools); //Get the pool stats LocalLBPoolPoolStatistics poolStats = new LocalLBPoolPoolStatistics(); //Get the pool stat entries LocalLBPoolPoolStatisticEntry[] poolStatEntries; //Load the localDefaultPools into a List object to prune and perform batch get_statistics with List localDefaultPoolsList = RemoveNoNamePools(localDefaultPools); string[] poolBatch; int batchCount = 1; Stopwatch timer = new Stopwatch(); timer.Start(); //Break the statistics rquests into batchs of XX while(localDefaultPoolsList.Count > 0) { if(localDefaultPoolsList.Count >= 10) { poolBatch = localDefaultPoolsList.GetRange(localDefaultPoolsList.Count - 10, 10).ToArray(); localDefaultPoolsList.RemoveRange(localDefaultPoolsList.Count - 10, 10); poolStats = m_interfaces.LocalLBPool.get_statistics(poolBatch); poolStatEntries = poolStats.statistics; PrintStatistics(poolStatEntries); } else { poolBatch = localDefaultPoolsList.ToArray(); localDefaultPoolsList.Clear(); poolStats = m_interfaces.LocalLBPool.get_statistics(poolBatch); poolStatEntries = poolStats.statistics; PrintStatistics(poolStatEntries); } //Console.WriteLine("Batch {0} time elapsed: {1}", batchCount.ToString(), timer.Elapsed.ToString()); batchCount++; } Console.WriteLine("Total time elapsed: {1}", batchCount.ToString(), timer.Elapsed.ToString()); timer.Stop(); } private static List RemoveNoNamePools(string[] localDefaultPools) { List localDefaultPoolsList = new List (); foreach (string poolName in localDefaultPools) { if (poolName != "") localDefaultPoolsList.Add(poolName); } return localDefaultPoolsList; } public static void PrintInfo(string[] info) { for (int i = 0; i > info.Length; i++) { Console.WriteLine(info[ i ].ToString()); } } public static void PrintStatistics(LocalLBPoolPoolStatisticEntry[] poolStatEntries) { //Loop through each pool and print out the server side current connection stats for (int i = 0; i < poolStatEntries.Length; i++) { CommonStatistic[] commonStats = poolStatEntries[ i ].statistics; for (int x = 0; x < commonStats.Length; x++) { if (commonStats[x].type == CommonStatisticType.STATISTIC_SERVER_SIDE_CURRENT_CONNECTIONS && poolStatEntries[ i ].pool_name != "") { Console.WriteLine("Pool name: {0} Current connections: {1}", poolStatEntries[ i ].pool_name, commonStats[x].value.low.ToString()); } } } } } }487Views0likes1CommentGet Task Status (C# code sample)
Problem this snippet solves: This C# client code sample uses Enterprise Manager's device inventory to get the status for a specific task executed by the referenced Enterprise Manager. Code : using System; using iControl; /** * A class for testing the Management::EM::get_task_status iControl interface. */ class ManagementEMGetTaskStatus { private static int MIN_ARGS = 3; private static string USAGE = "ManagementEMGetTaskStatus " + "[ ]"; private static int EM_PORT = 443; /** * The main method. * * @param args command line arguments */ static void Main(string[] args) { if (args.Length < MIN_ARGS) { Console.WriteLine("Usage: " + USAGE); Environment.Exit(1); } string emAddress = args[0]; string emUsername = args[1]; string emPassword = args[2]; String[] taskIds = new String[args.Length - MIN_ARGS]; for (int i = 0; i < taskIds.Length; i++) { taskIds[i] = args[i + MIN_ARGS]; } iControl.ManagementEMTaskStatus[] statuses = null; try { Interfaces ic = new Interfaces(); ic.initialize(emAddress, EM_PORT, emUsername, emPassword); statuses = ic.ManagementEM.get_task_status(taskIds); if (statuses.Length != taskIds.Length) { throw new Exception("wrong number of status values returned"); } } catch (Exception e) { Console.WriteLine("Failed to get task status: " + e.Message); Environment.Exit(1); } for (int i = 0; i < taskIds.Length; i++) { Console.Write("Task "); Console.Write(taskIds[i]); Console.Write(": "); Console.WriteLine(statuses[i]); } } // Main } // class ManagementEMGetTaskStatus207Views0likes0CommentsEM discover devices
Problem this snippet solves: Introduced: EM_v3.0 Use the discover_devices API to discover devices to be managed by an Enterprise Manager. Important: If you plan to use iControl Proxy to communicate with discovered devices, you must discover them through the internal traffic interface; not the management interface. How to use this snippet: Prototype Python ic.Management.EM.discoverdevices(addresses = deviceaddresses, usernames = deviceusernames, passwords = devicepasswords) C#, Java, and Perl ic.ManagementEM.discover_devices(deviceAddresses, deviceUsernames, devicePasswords); Inputs Name Type Description addresses String Sequence This parameter specifies the IP addresses or hostnames of the devices you want to discover. usernames String Sequence This parameter specifies the username credentials of the devices you want to discover. passwords String Sequence This parameter specifies the password credentials of the devices you want to discover. Return Values Name Type Description task String The ID of the new discovery task. Exceptions Exception Name This exception is raised when... AccessDenied The credentials supplied by the client do not satisfy the F5 device's validation requirements. OperationFailed The API call causes an operation error. InvalidArgument The API call contains an invalid argument. Code : To view a code sample, click the relevant code type. C# (.net) Java Perl Python251Views0likes0CommentsDiscovering BIG-IP devices
Problem this snippet solves: The script you need for this task must: Identify the Enterprise Manager system on which you want to initiate the device discovery process, specifying username and password as needed. Initialize the API. Run the API. Important: Although you can use this API to discover devices using either the TMM or the management interface, you must discover devices through an internal traffic interface (TMM) if you want to use the iControl Proxy to send messages to managed devices. How to use this snippet: To discover devices: Create a script similar to the code sample shown below. From a command prompt, run your script. When the code finishes running, a list of discovered BIG-IP devices is added to the user interface on Enterprise Manager. Code : /** * A class for testing the Management::EM::discover_devices iControl interface. */ public class ManagementEMDiscoverDevices { private static int MIN_ARGS = 3; private static int NUM_DEVICE_ARGS = 3; private static String USAGE = "ManagementEMDiscoverDevices " + "[ ] ..."; private static int EM_PORT = 443; /** * The main method. * * @param args command line arguments */ public static void main(String[] args) { if ((args.length < MIN_ARGS) || (((args.length - MIN_ARGS) % NUM_DEVICE_ARGS) != 0)) { System.err.println("Usage: " + USAGE); System.exit(1); } String emAddress = args[0]; String emUsername = args[1]; String emPassword = args[2]; int numDevices = (args.length - MIN_ARGS) / NUM_DEVICE_ARGS; String[] deviceAddresses = new String[numDevices]; String[] deviceUsernames = new String[numDevices]; String[] devicePasswords = new String[numDevices]; for (int i = 0; i < deviceAddresses.length; i++) { int index = MIN_ARGS + (i * NUM_DEVICE_ARGS); deviceAddresses[i] = args[index]; deviceUsernames[i] = args[index + 1]; devicePasswords[i] = args[index + 2]; } String taskId = null; try { iControl.Interfaces ic = new iControl.Interfaces(); ic.initialize(emAddress, EM_PORT, emUsername, emPassword); taskId = ic.getManagementEM().discover_devices(deviceAddresses, deviceUsernames, devicePasswords); } catch (Exception e) { System.err.println("Failed to discover devices: " + e.getMessage()); System.exit(1); } System.out.println("Discovery task started with task ID: " + taskId); } // public static void main } // public class ManagementEMDiscoverDevices265Views0likes0Comments