import arcpy
import os
# Set output file names
outdir = r"D:"
service = "MapImageSharingDraftExample"
mapname = ""
sddraft_filename = service + ".sddraft"
serverurl = "https://portal35.geoscene-dev.cn/server"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
print(arcpy.GetActivePortalURL())
#arcpy.SignInToPortal(arcpy.GetActivePortalURL(), 'portaladmin', 'Admin123')
# Reference map to publish
aprx = arcpy.mp.ArcGISProject(r"D:\1.aprx")
m = aprx.listMaps(mapname)[0]
# Create MapImageSharingDraft and set service properties
sharing_draft = m.getWebLayerSharingDraft("FEDERATED_SERVER", "MAP_IMAGE", service)
sharing_draft.federatedServerUrl = serverurl
sharing_draft.summary = "My Summary"
sharing_draft.tags = "My Tags"
sharing_draft.description = "My Description"
sharing_draft.credits = "My Credits"
sharing_draft.useLimitations = "My Use Limitations"
# Create Service Definition Draft file
sharing_draft.exportToSDDraft(sddraft_output_filename)
# Stage Service
sd_filename = service + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)
arcpy.StageService_server(sddraft_output_filename, sd_output_filename)
# Share to portal
#print("Uploading Service Definition...")
#arcpy.UploadServiceDefinition_server(sd_output_filename, "https://MyFederatedServer.esri.com/server")
print("Successfully Uploaded service.")