示例:停止或启动文件夹中的所有服务
本例将通读某一指定的 GIS 服务器文件夹,并根据用户提供的参数停止或启动文件夹中的所有服务。如果用户尝试启动一个已启动的服务,或停止一个已停止的服务,则脚本将继续前进至文件夹中的下一个服务。
运行此脚本时,您需要提供一个具有 ArcGIS Server 管理权限的用户名和密码。利用此信息可获取一个令牌,以便允许您作出读取文件夹以及停止和启动服务的 Web 服务调用。
您还需要提供服务器名称以及要停止或启动服务的文件夹。您可以为根文件夹提供 root,但请注意,对根文件夹进行遍历将会影响预先配置的几何服务和搜索服务。
最终参数会询问是否要停止或启动文件夹中的所有服务。使用 ArcGIS Server Administrator API 停止和启动服务的 Web 服务调用非常相似,因此,在此脚本中允许这两种调用并不困难。
初次请求文件夹中的服务列表时,响应将以 JavaScript 对象表示法 (JSON) 的形式返回。Python 的 json.loads() 函数将 JSON 转换成一个可遍历的 Python 对象。
尽管此脚本具有一些错误检查和报告,但是为简洁起见,已排除了其他检查。
# Demonstrates how to stop or start all services in a folder
# For Http calls
import httplib, urllib, json
# For system tools
import sys
# For reading passwords without echoing
import getpass
# 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 = raw_input("Enter user name: ")
password = getpass.getpass("Enter password: ")
# Ask for server name
serverName = raw_input("Enter server name: ")
serverPort = 6080
folder = raw_input("Enter the folder name or ROOT for the root location: ")
stopOrStart = raw_input("Enter whether you want to START or STOP all services: ")
# 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()
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 __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
9/15/2013