Skip to content

Instantly share code, notes, and snippets.

@pmacMaps
Last active January 17, 2023 22:10
Show Gist options
  • Save pmacMaps/bb3e6681335411dd775669a65249ae10 to your computer and use it in GitHub Desktop.
Save pmacMaps/bb3e6681335411dd775669a65249ae10 to your computer and use it in GitHub Desktop.
Start or Stop an ArcGIS Server Service (ArcPy Script)
# Sample script to start/stop ArcGIS Server service
# import modules
import arcpy, os, sys, time, datetime, urllib, urllib2, json
# generate token for server
def gentoken(server, port, adminUser, adminPass, expiration=60):
# Re-usable function to get a token required for Admin changes
query_dict = {'username': adminUser,
'password': adminPass,
'expiration': str(expiration),
'client': 'requestip'}
query_string = urllib.urlencode(query_dict)
url = "https://{}:{}/arcgis/admin/generateToken".format(server, port)
token = json.loads(urllib.urlopen(url + "?f=json", query_string).read())
if "token" not in token:
message = '\n{}\n'.format(token['messages'])
return message
else:
return token['token']
# end gentoken
# start or stop services in a list
def stopStartServices(server, port, adminUser, adminPass, stopStart, service, token=None):
''' Function to stop, start or delete a service.
Requires Admin user/password, as well as server and port (necessary to construct token if one does not exist).
stopStart = Stop|Start|Delete
service = A REST service; must be in the <name>.<type> notation
If a token exists, you can pass one in for use.
'''
# container for messages
# function returns message that can be added to log file
message = ''
# Get and set the token
if token is None:
token = gentoken(server, port, adminUser, adminPass)
else:
pass
# modify the service
service = urllib.quote(service.encode('utf8'))
op_service_url = "https://{}:{}/arcgis/admin/services/{}/{}?token={}&f=json".format(server, port, service, stopStart, token)
status = urllib2.urlopen(op_service_url, ' ').read()
if 'success' in status:
message += '\n{} === {}\n'.format(service, stopStart)
else:
message += '\n{}\n'.format(status)
return message
# end stopStartServices
# Attempt to run geoprocessing tools
try:
# Time stamp variables
currentTime = datetime.datetime.now()
# Format date as 3-24-2017
dateToday = currentTime.strftime("%m-%d-%Y")
# placeholder for messages for text file
logMsg = ''
# Create text file for logging results of script
logFile = r'C:\Scripts\Logs\Directory\Start_Stop_Services_Report_{}.txt'.format(dateToday)
agsServer = 'Server Name'
port = '0000'
username = 'username'
password = 'password'
map_service = 'SomeService.MapServer'
# Generate token for server
logMsg += 'Generating ArcGIS Server token\n'
token = gentoken(agsServer,port,username,password)
logMsg += '\nGenerated token is {}\n'.format(token)
# stop service
logMsg += '\nStopping {} service\n'.format(map_service)
stopServicesMessages = stopStartServices(agsServer,port,username,password,'Stop',map_service,token)
# get messages from stop services function
logMsg += '\n{}\n'.format(stopServicesMessages)
# Do other stuff here
# start service
logMsg += '\Starting {} service\n'.format(map_service)
startServicesMessages = stopStartServices(agsServer,port,username,password,'Start',map_service,token)
# get messages from stop services function
logMsg += '\n{}\n'.format(startServicesMessages)
# If an error occurs running geoprocessing tool(s) capture error and write message
# handle error outside of Python system
except EnvironmentError as e:
tbE = sys.exc_info()[2]
# Write the line number the error occured to the log file
logMsg += "\nFailed at Line {}\n".format(tbE.tb_lineno)
# Write the error message to the log file
logMsg += "Error: {}\n".format(str(e))
except Exception as e:
# If an error occurred, write line number and error message to log
tb = sys.exc_info()[2]
logMsg += "\nFailed at Line {}\n".format(tb.tb_lineno)
logMsg += "Error: {}".format(e.message)
finally:
# write message to log file
try:
with open(logFile, 'w') as f:
f.write(str(logMsg))
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment