Skip To Content

Example: Register folders and databases listed in a text file

This example script uses a text file list of the folders and databases you want to register with an ArcGIS Server site. Although you can register databases and folders with federated ArcGIS Server sites using ArcGIS Pro or the ArcGIS Enterprise portal and register databases and folders with stand-alone ArcGIS Server sites using ArcGIS Pro or ArcGIS Server Manager, it may be faster to use this script if you have many data source locations to register.

Tip:

See Data sources for ArcGIS Server for information on why you register data locations with an ArcGIS Server site.

Structure the input text file as follows:

#dsName|dsType|serverPath|clientPath|hostname

dsName=<data store name>|dsType={FOLDER | DATABASE}|serverPath=<path to folder or database connection file used by the ArcGIS Server site>|clientPath=<path to folder or database connection file used by the publishing client>

  • dsName—A name for the data store item. It can be any name that you supply.
  • dsType—The type of data store item being registered. For this example, you can use FOLDER or DATABASE.
  • serverPath—The path to the data as seen by the server machine.
  • clientPath—The path to the data as seen by the publishers' machines. If not supplied, the server path will be used. If you supply the keyword managed, it means you are registering this data store item as the ArcGIS Server site's managed database.
  • hostname—The name of the publisher machine. This is needed only when the clientPath is a folder-based path. If this property is omitted, the name of the machine running the script will be used.

In this example, two folder paths and two database connection files are listed in the text file. The second folder path (testData) has a different location for the ArcGIS Server site and the local ArcGIS client.

#dsName|dsType|serverPath|clientPath|hostname

dsName=sharedData|dsType=FOLDER|serverPath=\\sharedserver\data|clientPath=\\sharedserver\data
dsName=testData|dsType=FOLDER|serverPath=\\test_server\data|clientPath=c:\mydata|hostname=qalab_publisher
dsName=entGeodatabase|dsType=DATABASE|serverPath=C:\data\db_connections\Connection to enterprisegdb1.sde|clientPath=C:\data\db_Connections\Connection to enterprisegdb1.sde
dsName=spatialDatabase|dsType=DATABASE|serverPath=C:\data\db_Connections\Connection to projectdb.sde|clientPath=C:\data\db_Connections\Connection to projectdb.sde

The following sample script prompts you for connection information for the ArcGIS Server site to create an ArcGIS Server connection file. It also prompts you to specify the location of the text file containing the list of data sources and registers the data sources in the file with the ArcGIS Server site.

import sys
import os
import getpass
import arcpy
import codecs


def main(argv=None):
    
    # Ask for admin user name and password
    
    username = input("Enter user name: ")
    password = getpass.getpass("Enter password: ")
    
    # Ask for server name & port
    serverName = input("Enter server name: ")
    serverPort = input("Enter server port: ")
 
    # Create a connection file to the server and save it in the same location as that of the script
    serverURL="http://"+serverName+":"+str(serverPort)+"/arcgis/admin"
    try:
        arcpy.mapping.CreateGISServerConnectionFile("PUBLISH_GIS_SERVICES",os.curdir,serverName+".ags",serverURL,"ARCGIS_SERVER",username=username,password=password)
    except Exception as e:
        print(e)
    
    agsConnection = os.path.join(os.curdir, serverName+".ags")
    
    if not os.path.isfile(agsConnection):
        print("Unable to connect to ArcGIS Server. Exiting.")
        sys.exit(1)

    # Input File that contains the data store information
    dataStoresFile = input("Path to pipe-delimited text file containing datastore information: ")
    
    num = 0 
    datastores = {}
    
    for datastoreRow in readlinesFromInputFile(dataStoresFile):
            
        datastoreEntry = {}
        
        for index in range(len(datastoreRow)):
            
            datastoreProp = datastoreRow[index].split("=")
            
            if datastoreProp[0] == "dsName":
                datastoreEntry["connection_name"] = datastoreProp[1]
            if datastoreProp[0] == "dsType":
                datastoreEntry["datastore_type"] = datastoreProp[1]
            if datastoreProp[0] == "serverPath":
                datastoreEntry["server_path"] = datastoreProp[1]
            if datastoreProp[0] == "clientPath":
                datastoreEntry["client_path"] = datastoreProp[1]
            if datastoreProp[0] == "hostname":
                datastoreEntry["hostname"] = datastoreProp[1]
         
            # Add the datastore information to a dictionary
            datastores["datastore" + str(num)] = datastoreEntry
        
        num +=1

    # Call helper functions to register datastores
    addDataStores(datastores,agsConnection)


# A function that reads lines from the input file
def readlinesFromInputFile(filename, delim='|'):
    file = codecs.open(filename,'r','utf-8-sig')
    for line in file.readlines():
        # Remove the trailing whitespaces and the newline characters
        line = line.rstrip()
        
        if line.startswith('#') or len(line) == 0:
            pass # Skip the lines that contain # at the beginning or any empty lines
        else:
            # Split the current line into list
            yield line.split(delim)
    file.close()


def addDataStores(datastoresDict,agsConnection):
    
    for datastoreToAdd in datastoresDict:
        # Build the dictionary with the role name and description               
        datastoresDict[datastoreToAdd]["connection_file"] =  agsConnection
        
        print("Adding the datastore: " + datastoresDict[datastoreToAdd]['connection_name'])
        
        try:
            arcpy.AddDataStoreItem(**datastoresDict[datastoreToAdd])
            print("Successfully added the datastore: " + datastoresDict[datastoreToAdd]['connection_name'])
        except Exception as e:
            print("Adding of the datastore: " + datastoresDict[datastoreToAdd]['connection_name'] + " failed.")
            print(e)

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))