Looking for some python code that will start and stop services in ArcGIS Server 10.3

13242
12
Jump to solution
06-04-2015 09:50 AM
GailJorgenson
New Contributor III

Hello,

I am trying to find some python code that will start and start ArcGIS Server 10.3 services.  The code will be used  as part of an automated cycle for reconciling and posting.  The reconcile post portion of the script is written, but I need to start the services for this to work & then restart.  Any ideas?

Thank you,

Gail

0 Kudos
1 Solution

Accepted Solutions
MichaelVolz
Esteemed Contributor

Gail:

There are AGS Admin python tools that I run through a bat file to start and stop services and the bat file also calls python scripts to manage AGS data that cannot be modified while the service is running.  These tools are available on the machine where you installed AGS software, so you would run them from that machine.  If you want to run these tools on another machine, then you could install the AGS software to get the libraries, but just don't authorize the software because that is only needed on the machine(s) where the services are running.

In the bat file I make the call to stop the service:

C:\Python27\ArcGIS10.3\python.exe C:\Program Files\ArcGIS\Server\tools\admin\manageservice.py -u "username" -p "Password -s http://"arcgis server name" -t -n "location of ags service" -o stop

Call to 1 python script (You can call as many as you want)

C:\Python27\ArcGIS10.3\python.exe "Script name".py >> "Location of log file you could write comments to for debugging and auditing purposes?

In the bat file I make the call to start the service after the python script has modified the data:

C:\Python27\ArcGIS10.3\python.exe C:\Program Files\ArcGIS\Server\tools\admin\manageservice.py -u "username" -p "Password -s http://"arcgis server name" -t -n "location of ags service" -o start

View solution in original post

0 Kudos
12 Replies
by Anonymous User
Not applicable

Hi Gail,

Take a look at the arcrest python package available on github.  It has a lot of useful python functions for interacting with arcgis server and portal.

Esri/ArcREST · GitHub

0 Kudos
GailJorgenson
New Contributor III

Thank you, Sage.  I went to the link that you provided and wasn't able to find anything specific to starting and stopping services, but I am new to GitHub so maybe I just wasn't looking in the right place.  I did a search on Start, and came up with 29 possible options, but when I reviewed them they were all specific to start time, not start service.  I also downloaded a zip file to check it out and there were a number of scripts in the downloaded file.  My review so far has not gotten the code I need.  If there was a specific file you were thinking I should look at I am happy to go find it.

Gail

0 Kudos
MichaelVolz
Esteemed Contributor

Gail:

There are AGS Admin python tools that I run through a bat file to start and stop services and the bat file also calls python scripts to manage AGS data that cannot be modified while the service is running.  These tools are available on the machine where you installed AGS software, so you would run them from that machine.  If you want to run these tools on another machine, then you could install the AGS software to get the libraries, but just don't authorize the software because that is only needed on the machine(s) where the services are running.

In the bat file I make the call to stop the service:

C:\Python27\ArcGIS10.3\python.exe C:\Program Files\ArcGIS\Server\tools\admin\manageservice.py -u "username" -p "Password -s http://"arcgis server name" -t -n "location of ags service" -o stop

Call to 1 python script (You can call as many as you want)

C:\Python27\ArcGIS10.3\python.exe "Script name".py >> "Location of log file you could write comments to for debugging and auditing purposes?

In the bat file I make the call to start the service after the python script has modified the data:

C:\Python27\ArcGIS10.3\python.exe C:\Program Files\ArcGIS\Server\tools\admin\manageservice.py -u "username" -p "Password -s http://"arcgis server name" -t -n "location of ags service" -o start

0 Kudos
JeffWard
Occasional Contributor III

You can add python.exe to your executables path so you don't have to enter the path to python every time.  See how here.

Jeff Ward
Summit County, Utah
0 Kudos
by Anonymous User
Not applicable

Sorry about that Gail.  The arcrest package can be a bit confusing for sure.  The AGSService class has functions to start and stop services.  This class can be found in the src/arcrest/manageags/_services.py module.  (ArcREST/_services.py at master · Esri/ArcREST · GitHub )

I found this burried in the 10.3 documentation.  This approach might actually be easier to incorporate into your script than using arcrest.

Example: Stop or start all services in a folder—Documentation (10.3 and 10.3.1) | ArcGIS for Server

Good luck and happy scripting!

Sage

0 Kudos
JeffWard
Occasional Contributor III

A quick way to learn how to do something with python is to put together a simple model in model builder and export that model to a python script and see what the command is and what the arguments are.

Jeff Ward
Summit County, Utah
0 Kudos
GailJorgenson
New Contributor III

I have the code for the reconcile post portion and that was created using model builder and exported to a python script.  I have not been able to find a tool to bring in to model builder that will stop services and restart them.

Thank you,

Gail

0 Kudos
JeffWard
Occasional Contributor III

My apologies.  I built a model that stopped and started services while some updates were made.  It turns out the tools in the model that stopped and started the services were actually python script tools.  I found them online somewhere, I can't remember where.  Here's the code I have with my server info taken out.

# Demonstrates how to stop or start all services in a folder

# For Http calls
import httplib, urllib, json

# For system tools
import sys


# Defines the entry point into the script
def main(argv=None):
    # Print some info
    print
    print "This tool is a sample script that stops or starts all services in a folder."
    print 
   
    # Ask for admin/publisher user name and password
    username = ''  #put your username here or get it from a parameter
    password = '' 
   
    # Ask for server name
    serverName = ''    #your server name
    serverPort =        #your port integer type

    folder = ''        #folder that contains the service or services
    stopOrStart = 'STOP'

    # Check to make sure stop/start parameter is a valid value
    if str.upper(stopOrStart) != "START" and str.upper(stopOrStart) != "STOP":
        print "Invalid STOP/START parameter entered"
        return
   
    # Get a token
    token = getToken(username, password, serverName, serverPort)
    if token == "":
        print "Could not generate a token with the username and password provided."
        return
   
    # Construct URL to read folder
    if str.upper(folder) == "ROOT":
        folder = ""
    else:
        folder += "/"
           
    folderURL = "/arcgis/admin/services/" + folder
   
    # This request only needs the token and the response formatting parameter
    params = urllib.urlencode({'token': token, 'f': 'json'})
   
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
   
    # Connect to URL and post parameters   
    httpConn = httplib.HTTPConnection(serverName, serverPort)
    httpConn.request("POST", folderURL, params, headers)
   
    # Read response
    response = httpConn.getresponse()
    if (response.status != 200):
        httpConn.close()
        print "Could not read folder information."
        return
    else:
        data = response.read()
       
        # Check that data returned is not an error object
        if not assertJsonSuccess(data):         
            print "Error when reading folder information. " + str(data)
        else:
            print "Processed folder information successfully. Now processing services..."

        # Deserialize response into Python object
        dataObj = json.loads(data)
        httpConn.close()

        # Loop through each service in the folder and stop or start it   
        for item in dataObj['services']:

            fullSvcName = item['serviceName'] + "." + item['type']

            # Construct URL to stop or start service, then make the request               
            stopOrStartURL = "/arcgis/admin/services/" + folder + fullSvcName + "/" + stopOrStart
            httpConn.request("POST", stopOrStartURL, params, headers)
           
            # Read stop or start response
            stopStartResponse = httpConn.getresponse()
            if (stopStartResponse.status != 200):
                httpConn.close()
                print "Error while executing stop or start. Please check the URL and try again."
                return
            else:
                stopStartData = stopStartResponse.read()
               
                # Check that data returned is not an error object
                if not assertJsonSuccess(stopStartData):
                    if str.upper(stopOrStart) == "START":
                        print "Error returned when starting service " + fullSvcName + "."
                    else:
                        print "Error returned when stopping service " + fullSvcName + "."

                    print str(stopStartData)
                   
                else:
                    print "Service " + fullSvcName + " processed successfully."

            httpConn.close()         
        arcpy.SetParameterAsText(1, 'true')
        return


# A function to generate a token given username, password and the adminURL.
def getToken(username, password, serverName, serverPort):
    # Token URL is typically http://server[:port]/arcgis/admin/generateToken
    tokenURL = "/arcgis/admin/generateToken"
   
    params = urllib.urlencode({'username': username, 'password': password, 'client': 'requestip', 'f': 'json'})
   
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
   
    # Connect to URL and post parameters
    httpConn = httplib.HTTPConnection(serverName, serverPort)
    httpConn.request("POST", tokenURL, params, headers)
   
    # Read response
    response = httpConn.getresponse()
    if (response.status != 200):
        httpConn.close()
        print "Error while fetching tokens from admin URL. Please check the URL and try again."
        return
    else:
        data = response.read()
        httpConn.close()
       
        # Check that data returned is not an error object
        if not assertJsonSuccess(data):           
            return
       
        # Extract the token from it
        token = json.loads(data)       
        return token['token']           
       

# A function that checks that the input JSON object
#  is not an error object.
def assertJsonSuccess(data):
    obj = json.loads(data)
    if 'status' in obj and obj['status'] == "error":
        print "Error: JSON object returns an error. " + str(obj)
        return False
    else:
        return True
   
       
# Script start
if arcpy.GetParameterAsText(0):
    main()
else:
    arcpy.AddMessage("Previous tool exited on error")
Jeff Ward
Summit County, Utah
GailJorgenson
New Contributor III

WOW!  I am truly overwhelmed.  Thank you so much.  I am out of the office for a couple of days, but when I return I will be going through all of your suggestions to find the best method.

I will post when the script has succeeded or if I have additional questions.

Regards,

Gail

0 Kudos