Last updated at Tue, 16 Jan 2024 16:19:27 GMT

I would like to take the time to share an example of how you can use the Nexpose API to create a batch of users at one time with the use of a CSV file. Sounds too good to be true right?

I swear to you that this is not a mirage. In fact I am prepared to put my money where my mouth is and post a code example with Rapid7's very own Open Source Java API client. This will allow you to do the following:

  • Interactively specify a CSV file to Create Update and even remove existing users
    • Please see the attached example CSV.
  • Alternatively if you would rather enter the users in the interactive console this is an option as well
    • If the manual option is selected the program will interactively ask you for explicit user details

Enough talk here is the code:

import org.rapid7.nexpose.api.APIException;
import org.rapid7.nexpose.api.APIResponse;
import org.rapid7.nexpose.api.APISession;
import org.rapid7.nexpose.api.DefaultAPIErrorHandler;
import org.rapid7.nexpose.api.APISession.APISupportedVersion;
import org.rapid7.nexpose.api.generators.UserSaveRequestGroupsGenerator;
import org.rapid7.nexpose.api.generators.UserSaveRequestSitesGenerator;
import org.rapid7.nexpose.api.IAPIErrorHandler;
import org.rapid7.nexpose.api.UserConfigRequest;
import org.rapid7.nexpose.api.UserDeleteRequest;
import org.rapid7.nexpose.api.UserListingRequest;
import org.rapid7.nexpose.api.UserSaveRequest;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
 
/***************************************************************************
* COPYRIGHT (C) 2012, Rapid7 LLC, Boston, MA, USA.
* All rights reserved. This material contains unpublished, copyrighted
* work including confidential and proprietary information of Rapid7.
**************************************************************************/
 
/**
* Demonstrates the Nexpose EnginePool CRUD operations.
*
*
* @author Murali Rongali
*/
public class NexposeUser
{
   /////////////////////////////////////////////////////////////////////////
   // Public methods
   /////////////////////////////////////////////////////////////////////////
   /**
    * Main method to gather data and execute the commands.
    *
    * @param args none.
    */
   public static void main(String[] args)
   {
      String s = "";
      while (!s.equalsIgnoreCase("9"))
      {
         try
         {
            StringBuffer menu = new StringBuffer("********** Main Menu **********\n");
            menu.append("1) Login\n");
            menu.append("2) Show this sessions' last request/response\n");
            menu.append("3) User create\n");
            menu.append("4) User details\n");
            menu.append("5) User listing\n");
            menu.append("6) User delete\n");
            menu.append("7) Create users from CSV\n");
            menu.append("8) Exit\n");
            menu.append("*******************************\nR7>");
            System.out.println(menu.toString());
            s = br.readLine();
            switch (s)
            {
               case "1":
                  login();
                  break;
               case "2":
                  showRequestResponse();
                  break;
               case "3":
                  userCreate();
                  break;
               case "4":
                  userConfig();
                  break;
               case "5":
                  userListing();
                  break;
               case "6":
                  userDelete();
                  break;
               case "7":
                  createUserBulk();
                  break;
               case "8":
                  System.out.println("Bye.");
                  break;
               default:
                  System.out.println("Not a valid option.\n");
                  break;
            }
         }
         catch (IOException e)
         {
            System.out.print("\nAn error ocurred while attempting to execute your request:\n " + e + " \n\n");
         }
      }
   }
 
   /////////////////////////////////////////////////////////////////////////
   // Non-public methods
   /////////////////////////////////////////////////////////////////////////
 
   /**
    * Logs a user into Nexpose using the parameters specified by the user.
    */
   private static void login()
      throws IOException
   {
      APIResponse response = null;
      System.out.print("Enter the Nexpose console URL.\nR7> ");
      String nexposeConsoleURL = br.readLine();
      System.out.print("Enter the nexpose username.\nR7> ");
      String username = br.readLine();
      System.out.print("Enter the nexpose password.\nR7> ");
      String password = br.readLine();
      APISession session = new APISession(new URL(nexposeConsoleURL), "xml", APISupportedVersion.V1_2, username, password);
      IAPIErrorHandler errorHandler = new DefaultAPIErrorHandler();
      session.setErrorHandler(errorHandler);
      try
      {
         if (session != null) {
               response = session.login(null);
               m_session = session;
         }
         if (session.getSessionID() != null && response != null)
         {
            lastRequest = response.getFinalXML();
            lastResponse = response.getResponse();
         }
         else
         {
            System.out.println("Could not obtain a session with the specified url and credentials.");
         }
      }
      catch (APIException e)
      {
         System.out.println("Login unsuccessful: " + e);
      }
   }
 
   /**
    * Creates Engine.
    */
   private static void userCreate()
      throws IOException
   {
      APIResponse response = null;
      System.out.print("Enter the user login name.\nR7> ");
      String userID = br.readLine();
      System.out.print("Enter the full password.\nR7> ");
      String password = br.readLine();
      System.out.print("Enter the full name.\nR7> ");
      String fullName = br.readLine();
      System.out.print("Enter the email address.\nR7> ");
      String roleName = br.readLine();
      System.out.print("Enter the role name.\nR7> ");
      String emailAddress = br.readLine();
      System.out.print("Need aceess for all the groups(true/false)?\nR7> ");
      String groupsAccess = br.readLine();
      System.out.print("Need aceess for all the sites(true/false)?\nR7> ");
      String sitesAccess = br.readLine();
      System.out.print("Enabled(0|1)?\nR7> ");
      String enabled = br.readLine();
      try
      {
         UserSaveRequest request =
            new UserSaveRequest(m_session.getSessionID(), null, groupsAccess, sitesAccess, "1", emailAddress,
            enabled, fullName, "-1", userID, password, roleName, null, null);
         response = m_session.executeAPIRequest(request);
         lastRequest = response.getFinalXML();
         lastResponse = response.getResponse();
      }
      catch (APIException e)
      {
         System.out.println("UserCreate unsuccessful: " + e);
      }
   }
 
   /**
    * Creates UserConfig.
    */
   private static void userConfig()
      throws IOException
   {
      APIResponse response = null;
      System.out.print("Enter the user id.\nR7> ");
      String userID = br.readLine();
      try
      {
         //User create request
         UserConfigRequest userConfigRequest = new UserConfigRequest(m_session.getSessionID(), "", userID);
         response = m_session.executeAPIRequest(userConfigRequest);
         System.out.println(response.getResponse());
         lastRequest = response.getFinalXML();
         lastResponse = response.getResponse();
      }
      catch (APIException e)
      {
         System.out.println("UserConfig unsuccessful: " + e);
      }
   }
 
   /**
    * userListing.
    */
   private static void userListing()
      throws IOException
   {
      APIResponse response = null;
      try
      {
         UserListingRequest userListingRequest = new UserListingRequest(m_session.getSessionID(), null);
         response = m_session.executeAPIRequest(userListingRequest);
         System.out.println(response.getResponse());
         lastRequest = response.getFinalXML();
         lastResponse = response.getResponse();
      }
      catch (APIException e)
      {
         System.out.println("UserListing unsuccessful: " + e);
      }
   }
 
   /**
    * User delete.
    */
   private static void userDelete()
      throws IOException
   {
      APIResponse response = null;
      System.out.print("Enter the userID.\nR7> ");
      String userID = br.readLine();
      try
      {
         UserDeleteRequest userDeleteRequest = new UserDeleteRequest(m_session.getSessionID(), null, userID);
         response = m_session.executeAPIRequest(userDeleteRequest);
         lastRequest = response.getFinalXML();
         lastResponse = response.getResponse();
      }
      catch (APIException e)
      {
         System.out.println("EnginePoolDetails unsuccessful: " + e);
      }
   }
 
   /**
    * user bulk create.
    */
   private static void createUserBulk()
      throws IOException
   {
      APIResponse response = null;
      System.out.print("Enter the path of CSV file.\nR7> ");
      String fileName = br.readLine();
 
      try
      {
         //create BufferedReader to read csv file
         BufferedReader br = new BufferedReader( new FileReader(fileName));
         String strLine = "";
         String[] sites;
         String[] groups;
         List<String> sitesList = new ArrayList<String> ();
         List<String> groupsList = new ArrayList<String> ();
         //read comma separated file line by line
         while ((strLine = br.readLine()) != null)
         {
            String[] user = strLine.split(",");
            if (!strLine.substring(0,1).equalsIgnoreCase("#")) {
               if (user.length > 8) {
                  sites = user[8].split("&");
                  for (String s: sites)
                  {
                     sitesList.add(s);
                  }
               }
               if (user.length > 9) {
                  groups = user[9].split("&");
                  for (String s: groups)
                  {
                     groupsList.add(s);
                  }
               }
               UserSaveRequestSitesGenerator sitesGenerator = new UserSaveRequestSitesGenerator();
               sitesGenerator.setSites(sitesList);
               UserSaveRequestGroupsGenerator groupsGenerator = new UserSaveRequestGroupsGenerator();
               groupsGenerator.setGroups(groupsList);
 
               UserSaveRequest request =
                  new UserSaveRequest(m_session.getSessionID(), null, user[5], user[6], "1", user[3],
                     user[7], user[2], "-1", user[0], user[1], user[4], null, null);
               response = m_session.executeAPIRequest(request);
               lastRequest = response.getFinalXML();
               lastResponse = response.getResponse();
            }
         }
      }
      catch (APIException e)
      {
         System.out.println("EnginePoolDetails unsuccessful: " + e);
      }
   }
 
   /**
    * Shows the request/response pair.
    */
   private static void showRequestResponse()
   {
      System.out.print("\n|============================ START REQUEST ============================|\n" + lastRequest);
      System.out.print("|============================= END REQUEST =============================|\n\n");
      System.out.print("\n|============================ START RESPONSE ============================|\n" + lastResponse);
      System.out.print("\n|============================= END RESPONSE =============================|\n\n");
   }
 
   /**
    * Return a universally unique string.
    *
    * @return String that is a UUID.
    */
   public static String getUuid()
   {
      return UUID.randomUUID().toString();
   }
 
   /////////////////////////////////////////////////////////////////////////
   // Non-public fields
   /////////////////////////////////////////////////////////////////////////
 
   // The session that will be setup and torn down with every test case
   private static APISession m_session;
 
   // The url for the nexpose target.
   private static String ms_url;
 
   // The user name to connect the nexpose target.
   private static String ms_userName;
 
   // The password to connect the nexpose target.
   private static String ms_password;
 
   //To read from the system input.
   public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
   //Contains the last request sent to nexpose.
   public static String lastRequest = "none yet\n";
 
   //Contains the last response received from nexpose.
   public static String lastResponse = "none yet";
 
}

Stay tuned here, as we'll have more short tips like this over the next few weeks!