コード例 #1
0
def delete_locks(fc_owner, fc_name, db_owner):
    """delete locks for the specified table
    fc_owner (string): owner of feature class
    fc_name (string): name of feature class (e.g. LandOwnership)
    db_owner (string): path to connection file with owner creds
    """
    if not Path(db_owner).exists():
        print(f'{db_owner} does not exist')

        return

    db_connect = arcpy.ArcSDESQLExecute(db_owner)

    sql = dedent(f'''SELECT * FROM sde.SDE_process_information
        WHERE SDE_ID IN(SELECT SDE_ID FROM sde.SDE_table_locks
        WHERE registration_id = (SELECT registration_id FROM sde.SDE_table_registry
        WHERE UPPER(table_name) = UPPER('{fc_name}') AND UPPER(owner) = UPPER('{fc_owner}')));
    ''')

    db_return = db_connect.execute(sql)

    if db_return is True:
        print('no locks to delete')

        return

    for user in db_return:
        print(f'deleted lock {user[0]}')
        arcpy.DisconnectUser(db_owner, user[0])
コード例 #2
0
    def bootUsers(self):
        self.current_item += 1

        self.itemPrint()  # ↓
        try:
            time.sleep(self.time_delay)
            self.itemPrint()  # ↑

            maintenance_log.appendToFile([
                self.maintenance_item[self.current_item],
                self.maintenance_status[1] + "   wait time: " + self.time_delay
            ])

        except Exception as e:
            self.handleException(e)

        self.current_item += 1

        self.itemPrint()  # ↓
        try:
            arcpy.DisconnectUser(self.sde_connection, 'ALL')
            self.itemPrint()  # ↑

            maintenance_log.appendToFile([
                self.maintenance_item[self.current_item],
                self.maintenance_status[1]
            ])

        except Exception as e:
            self.handleException(e)
コード例 #3
0
def prepare():
    log.write(datetime.datetime.now().strftime("%H:%M:%S %m/%d/%Y ") +
              "Disconnecting users...\n")
    arcpy.AcceptConnections(WORKSPACE_SA, False)
    time.sleep(1)
    arcpy.DisconnectUser("C:\\MaintenanceScripts\\Connections\\[email protected]",
                         "ALL")
    log.write(datetime.datetime.now().strftime("%H:%M:%S %m/%d/%Y ") +
              "User sessions have been disconnected...\n")
コード例 #4
0
def update_fields():
    try:
        workspace = ec_arcpy_util.sde_workspace_via_host()

        arcpy.env.workspace = workspace
        ds = ec_arcpy_util.find_dataset("*Streets")
        fc = ec_arcpy_util.find_feature_class("*dt_streets", "Streets")

        #
        # arcgis stuff for multi-users
        arcpy.AcceptConnections(workspace, False)
        arcpy.DisconnectUser(workspace, "ALL")
        if not arcpy.Describe(ds).isVersioned:
            arcpy.RegisterAsVersioned_management(ds, "EDITS_TO_BASE")

        fields = arcpy.ListFields(fc)
        is_schema_updated = False
        for field in fields:
            if "pwid" == field.name:
                is_schema_updated = True
                break

        if not is_schema_updated:
            arcpy.AddField_management("dt_streets", "pwid", "TEXT", field_length=32, field_alias="PubWorks ID", field_is_nullable="NULLABLE")
            arcpy.AddField_management("dt_streets", "pwname", "TEXT", field_length=64, field_alias="PubWorks Name", field_is_nullable="NULLABLE")
            arcpy.AddField_management("dt_streets", "st_fullname", "TEXT", field_length=50, field_alias="Street Full Name", field_is_nullable="NULLABLE")
            arcpy.AddField_management("dt_streets", "from_addr_l", "LONG", field_alias="From/Left #", field_is_nullable="NULLABLE")
            arcpy.AddField_management("dt_streets", "to_addr_l", "LONG", field_alias="To/Left #", field_is_nullable="NULLABLE")
            arcpy.AddField_management("dt_streets", "from_addr_r", "LONG", field_alias="From/Right #", field_is_nullable="NULLABLE")
            arcpy.AddField_management("dt_streets", "to_addr_r", "LONG", field_alias="To/Right #", field_is_nullable="NULLABLE")



















    except Exception as e:
        print(e)
        logging.error("update_fields():{}".format(e))

    finally:
        logging.info("done.")
コード例 #5
0
ファイル: workspace.py プロジェクト: denkide/ColumbiaCarto
def compress(workspace_path, disconnect_users=False, **kwargs):
    """Compress workspace (usually geodatabase).

    Args:
        geodatabase_path (str): Path of the workspace.
        disconnect_users (bool): Flag to disconnect users before compressing.
        **kwargs: Arbitrary keyword arguments. See below.

    Keyword Args:
        log_level (str): Level to log the function at. Default is 'info'.

    Returns:
        str: Path of the compressed workspace.

    Raises:
        ValueError: If `workspace_path` doesn't reference a compressable geodatabase.

    """
    log = leveled_logger(LOG, kwargs.setdefault('log_level', 'info'))
    log("Start: Compress workspace %s.", workspace_path)
    meta = {'workspace': metadata(workspace_path)}
    # Disconnect only possible for enterprise workspaces.
    disconnect_users = disconnect_users and meta['workspace'][
        'is_enterprise_database']
    if meta['workspace']['is_file_geodatabase']:
        _compress = arcpy.management.CompressFileGeodatabaseData
    elif meta['workspace']['is_enterprise_database']:
        _compress = arcpy.management.Compress
    else:
        raise ValueError("Compressing {} unsupported.".format(workspace_path))

    if disconnect_users:
        arcpy.AcceptConnections(sde_workspace=workspace_path,
                                accept_connections=False)
        arcpy.DisconnectUser(sde_workspace=workspace_path, users='all')
    _compress(workspace_path)
    if disconnect_users:
        arcpy.AcceptConnections(sde_workspace=workspace_path,
                                accept_connections=True)
    log("End: Compress.")
    return workspace_path
コード例 #6
0
    # Set the time.
    Time = time.strftime("%I:%M:%S %p", time.localtime())

    # Create a text file for logging
    log = r"C:\Scripts_2016\Dans_Scripts\Log\CompressLog.txt"
    write_log("***********************************************************",
              log)
    write_log("Starting maintenance for " + Date, log)
    try:
        arcpy.env.overwriteOutput = True
        # Block new connections to the database.
        arcpy.AcceptConnections(SDEconnection, False)

        # Disconnect all users from the database.
        arcpy.DisconnectUser(SDEconnection, "ALL")

        # Get a list of versions to pass into the ReconcileVersions tool.
        versionList = arcpy.ListVersions(SDEconnection)

        # Execute the ReconcileVersions tool.
        write_log(
            "-----------------------------------------------------------", log)
        write_log("RECONCILE", log)
        write_log(
            "-----------------------------------------------------------", log)
        reconcileLog = r"C:\Scripts_2016\Dans_Scripts\Log\ReconcileLog" + Date + ".txt"
        arcpy.ReconcileVersions_management(SDEconnection, "ALL_VERSIONS",
                                           "sde.QA", versionList,
                                           "LOCK_ACQUIRED", "NO_ABORT",
                                           "BY_OBJECT", "FAVOR_TARGET_VERSION",
コード例 #7
0
import arcpy

users = arcpy.ListUsers("Database Connections/Connection to sde_sde_db_rac.sde")
# for user in users:
#     print("Username: {0}, Connected at: {1}".format(
#         user.Name, user.ConnectionTime))


# import arcpy

# Set the admistrative workspace connection
# arcpy.env.workspace = "Database Connections/[email protected]"

# Create a list of users
'''
NOTE: When the arcpy.env.workspace environment is set, a workspace
does not need to be provided to the function.
'''
# users = arcpy.ListUsers()

# Create a list of SDE ID's.
# Use a list comprehension to get the ID values in a new list.
id_users = [user.ID for user in users]
print(id_users)

# import arcpy

arcpy.DisconnectUser("Database Connections/Connection to sde_sde_db_rac.sde", "ALL")
コード例 #8
0
def mainFunction(geodatabase,disconnectUsers): # Get parameters from ArcGIS Desktop tool by seperating by comma e.g. (var1 is 1st parameter,var2 is 2nd parameter,var3 is 3rd parameter)  
    try:
        # --------------------------------------- Start of code --------------------------------------- #

        # If disconnecting users
        if (disconnectUsers == "true"):
            # Block any new connections to the geodatabase
            arcpy.AcceptConnections(geodatabase, False)
            arcpy.AddMessage("Disconnecting all users from " + geodatabase + "...")
            # Logging
            if (enableLogging == "true"):
                logger.info("Disconnecting all users from " + geodatabase + "...")
            arcpy.DisconnectUser(geodatabase, "ALL")
        
        # Compress the geodatabase
        arcpy.AddMessage("Compressing geodatabase - " + geodatabase + "...")
        # Logging
        if (enableLogging == "true"):
            logger.info("Compressing geodatabase - " + geodatabase + "...")
        arcpy.env.workspace = geodatabase
        arcpy.Compress_management(geodatabase)

        # Load in datasets to a list
        dataList = arcpy.ListTables() + arcpy.ListFeatureClasses() + arcpy.ListDatasets()
        # Load in datasets from feature datasets to the list
        for dataset in arcpy.ListDatasets("", "Feature"):
            arcpy.env.workspace = os.path.join(geodatabase,dataset)
            dataList += arcpy.ListFeatureClasses() + arcpy.ListDatasets()

        # Reset the workspace
        arcpy.env.workspace = geodatabase

        # Get the user name for the workspace
        userName = arcpy.Describe(geodatabase).connectionProperties.user.lower()

        # Remove any datasets that are not owned by the connected user.
        userDataList = [ds for ds in dataList if ds.lower().find(".%s." % userName) > -1]        

        # Execute rebuild indexes
        arcpy.AddMessage("Rebuilding the indexes for all tables in the database....")
        # Logging
        if (enableLogging == "true"):
            logger.info("Rebuilding the indexes for all tables in the database....")
        # Note: to use the "SYSTEM" option the workspace user must be an administrator.
        arcpy.RebuildIndexes_management(geodatabase, "SYSTEM", userDataList, "ALL")
        
        # Execute analyze datasets
        arcpy.AddMessage("Analyzing and updating the database statistics....")
        # Logging
        if (enableLogging == "true"):
            logger.info("Analyzing and updating the database statistics....")
        # Note: to use the "SYSTEM" option the workspace user must be an administrator.
        arcpy.AnalyzeDatasets_management(geodatabase, "SYSTEM", userDataList, "ANALYZE_BASE","ANALYZE_DELTA","ANALYZE_ARCHIVE")

        # If disconnecting users
        if (disconnectUsers == "true"):
            # Allow any new connections to the geodatabase
            arcpy.AddMessage("Allowing all users to connect to " + geodatabase + "...")
            # Logging
            if (enableLogging == "true"):
                logger.info("Allowing all users to connect to " + geodatabase + "...")
            arcpy.AcceptConnections(geodatabase, True)
            
        # --------------------------------------- End of code --------------------------------------- #  
            
        # If called from gp tool return the arcpy parameter   
        if __name__ == '__main__':
            # Return the output if there is any
            if output:
                arcpy.SetParameterAsText(1, output)
        # Otherwise return the result          
        else:
            # Return the output if there is any
            if output:
                return output      
        # Logging
        if (enableLogging == "true"):
            # Log end of process
            logger.info("Process ended.")
            # Remove file handler and close log file        
            logMessage.flush()
            logMessage.close()
            logger.handlers = []
    # If arcpy error
    except arcpy.ExecuteError:           
        # Build and show the error message
        errorMessage = arcpy.GetMessages(2)   
        arcpy.AddError(errorMessage)           
        # Logging
        if (enableLogging == "true"):
            # Log error          
            logger.error(errorMessage)
            # Log end of process
            logger.info("Process ended.")            
            # Remove file handler and close log file        
            logMessage.flush()
            logMessage.close()
            logger.handlers = []   
        if (sendErrorEmail == "true"):
            # Send email
            sendEmail(errorMessage)
    # If python error
    except Exception as e:
        errorMessage = ""
        # Build and show the error message
        for i in range(len(e.args)):
            if (i == 0):
                # Python version check
                if sys.version_info[0] >= 3:
                    # Python 3.x
                    errorMessage = str(e.args[i]).encode('utf-8').decode('utf-8')
                else:
                    # Python 2.x
                    errorMessage = unicode(e.args[i]).encode('utf-8')
            else:
                # Python version check
                if sys.version_info[0] >= 3:
                    # Python 3.x
                    errorMessage = errorMessage + " " + str(e.args[i]).encode('utf-8').decode('utf-8')
                else:
                    # Python 2.x
                    errorMessage = errorMessage + " " + unicode(e.args[i]).encode('utf-8')
        arcpy.AddError(errorMessage)              
        # Logging
        if (enableLogging == "true"):
            # Log error            
            logger.error(errorMessage)
            # Log end of process
            logger.info("Process ended.")            
            # Remove file handler and close log file        
            logMessage.flush()
            logMessage.close()
            logger.handlers = []   
        if (sendErrorEmail == "true"):
            # Send email
            sendEmail(errorMessage)            
コード例 #9
0
# Set up logger in current folder.
file_loc = os.path.dirname(__file__)
logging.basicConfig(
    filename='server_maintenance.log',
    filemode='w',
    format='%(asctime)s | %(lineno)s | %(levelname)s | %(message)s',
    level=logging.INFO)

# Reconcile all versions and compress database
try:
    logging.debug('Disconnecting users')
    # Stop connections
    arcpy.AcceptConnections(SDE, False)
    # Disconnect users
    arcpy.DisconnectUser(SDE, "ALL")

    # Get version list
    version_list = arcpy.ListVersions(SDE)
    logging.info('Reconciling versions...')
    # Reconcile edits
    arcpy.ReconcileVersions_management(
        SDE,
        reconcile_mode="ALL_VERSIONS",
        target_version="dbo.DEFAULT",
        edit_versions=version_list,
        acquire_locks="LOCK_AQUIRED",
        abort_if_conflicts="NO_ABORT",
        conflict_definition="BY_OBJECT",
        conflict_resolution="FAVOR_TARGET_VERSION",
        with_post="POST",
コード例 #10
0
ファイル: DisconnectUsers.py プロジェクト: maslke/Arcpy
# -*- coding:utf-8 -*-

# disconnect users release the lock

import arcpy

#创建的sde连接文件
connection = 'Database Connections/[email protected]'

users = arcpy.ListUsers(connection)
print len(users)
arcpy.AcceptConnections(connection, False)
arcpy.DisconnectUser(connection, 'All')

users = arcpy.ListUsers(connection)
print len(users)  #should be 1
コード例 #11
0
'''
Created on Mar 12, 2013

@author: kyleg
'''

if __name__ == '__main__':
    pass

import arcpy

# Set Admin workspace variable
admin_workspace = r"Database Connections\SDEPROD_SDE.sde"

# Block connections
arcpy.AcceptConnections(admin_workspace, False)

# Disconnect users
arcpy.DisconnectUser(admin_workspace, 'ALL')

# Reconcile/Post using default parameters.
arcpy.ReconcileVersions_management(admin_workspace, 'ALL_VERSIONS',
                                   'sde.DEFAULT', with_post='POST')

# Compress the geodatabase
#arcpy.Compress_management(admin_workspace)

# Allow connections.
arcpy.AcceptConnections(admin_workspace, True)
コード例 #12
0
ファイル: esri_rename.py プロジェクト: vijaydairyf/ec-city
import inspect

import arcpy

try:
    arcpy.env.workspace = r"C:\Users\spowell\AppData\Roaming\ESRI\Desktop10.6\ArcCatalog\localhost.sde"
    #
    # arcgis stuff for multi-users
    arcpy.AcceptConnections(arcpy.env.workspace, False)
    arcpy.DisconnectUser(arcpy.env.workspace, "ALL")
    arcpy.Delete_management("boundary/county_parcel_1")
    arcpy.Rename_management("boundary/county_parcel", "boundary/county_parcel_1", "FeatureClass")
    arcpy.Rename_management("boundary/county_parcel_1", "boundary/county_parcel", "FeatureClass")

except Exception as e:
    print(f"{inspect.stack()[0][3]} {e}")
コード例 #13
0
import time
import datetime
import arcpy

#Set Variables
hour = 16  #Hour of the day to stop (24 hour).
minute = 30  #Minute of that hour to stop.
sdeCon = r'<path_to_gdb_admin_connection_file\<file_name>.sde'
computerName = '<instance_name>'
pauseMinutes = .5

#Figure out when to stop and how long to pause
stop = datetime.time(hour, minute)
now = datetime.datetime.now()
finishTime = datetime.datetime.combine(now, stop)

pause = pauseMinutes * 60

while finishTime > datetime.datetime.now():
    userList = arcpy.ListUsers(sdeCon)
    idList = [(user.ID, user.Name) for user in userList
              if user.ClientName.lower() != computerName.lower()]
    if len(idList) == 0:
        print "Nobody else is connected"
    for id in idList:
        print 'Disconnecting user {0}'.format(id[1])
        arcpy.DisconnectUser(sdeCon, id[0])
    time.sleep(pause)
else:
    print "Quittin' time"
コード例 #14
0
{3:s}
""".format(FROM, ", ".join(TO), SUBJECT, MSG)

# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, MESSAGE)
server.quit()

#block new connections to the database.
arcpy.AcceptConnections('Database Connections/admin.sde', False)

# wait 15 minutes
time.sleep(900)

#disconnect all users from the database.
arcpy.DisconnectUser('Database Connections/admin.sde', "ALL")

# Get a list of versions to pass into the ReconcileVersions tool.
versionList = arcpy.ListVersions('Database Connections/admin.sde')

# Execute the ReconcileVersions tool.
arcpy.ReconcileVersions_management('Database Connections/admin.sde',
                                   "ALL_VERSIONS", "sde.DEFAULT", versionList,
                                   "LOCK_ACQUIRED", "NO_ABORT", "BY_OBJECT",
                                   "FAVOR_TARGET_VERSION", "POST",
                                   "DELETE_VERSION",
                                   "c:/temp/reconcilelog.txt")

# Run the compress tool.
arcpy.Compress_management('Database Connections/admin.sde')
コード例 #15
0
    # Export all zips to web directory
    print("Copying all zips to web directory")
    m_bytes_prod_web = os.path.join(temp_env, prod_version, 'web')

    for dir in bytes_dirs:
        if dir is not 'web':
            zip_folder_path = os.path.join(temp_env, prod_version, dir)
            for f in os.listdir(zip_folder_path):
                if f.endswith('.zip'):
                    shutil.copy(os.path.join(zip_folder_path, f),
                                os.path.join(m_bytes_prod_web, f))
    print("All zips are now available in web folder")

    # Disconnect users from Production SDE to prohibit any schema locks if necessary
    arcpy.AcceptConnections(sde_prod_env, False)
    arcpy.DisconnectUser(sde_prod_env, "ALL")

    '''
    Export all necessary files from Bytes web directory to Production, Archive, and M: drive
    '''

    # Assign item list variable holding bytes files.
    bytes_dir_list = os.listdir(temp_env)

    # Loop through MapPLUTO Bytes Production directories for those that match current production version.

    for item in bytes_dir_list:
        if prod_version == item or prod_version.upper() == item:
            bytes_file_path = os.path.join(temp_env, item)

    # Assign item list variable holding versioned bytes files. --------------------------------------------
コード例 #16
0
def mainFunction(
    configFile
):  # Get parameters from ArcGIS Desktop tool by seperating by comma e.g. (var1 is 1st parameter,var2 is 2nd parameter,var3 is 3rd parameter)
    try:
        # Logging
        if (enableLogging == "true"):
            # Setup logging
            logger, logMessage = setLogging(logFile)
            # Log start of process
            logger.info("Process started.")

        # --------------------------------------- Start of code --------------------------------------- #

        # If configuration provided
        if (configFile):
            # Set CSV delimiter
            csvDelimiter = ","
            # Open the CSV file
            with open(configFile, 'rb') as csvFile:
                # Read the CSV file
                rows = csv.reader(csvFile, delimiter=csvDelimiter)

                # For each row in the CSV
                count = 0
                for row in rows:
                    # Ignore the first line containing headers
                    if (count > 0):
                        # Get the full dataset name
                        dataset = row[0]

                        # Get the database connection string from the input
                        splitDataset = dataset.split('.sde')
                        database = splitDataset[0] + ".sde"

                        # Disconnect users from the database
                        arcpy.DisconnectUser(database, "ALL")

                        # Get dataset properties
                        datasetDesc = arcpy.Describe(dataset)

                        # Add Global IDs
                        # Logging
                        if (enableLogging == "true"):
                            logger.info("Adding Global IDs for " + dataset +
                                        "...")
                        arcpy.AddMessage("Adding Global IDs for " + dataset +
                                         "...")
                        arcpy.AddGlobalIDs_management(dataset)

                        # If dataset isn't versioned
                        if (datasetDesc.isVersioned == 0):
                            # Register As Versioned
                            # Logging
                            if (enableLogging == "true"):
                                logger.info(
                                    "Registering dataset as versioned - " +
                                    dataset + "...")
                            arcpy.AddMessage(
                                "Registering dataset as versioned - " +
                                dataset + "...")
                            arcpy.RegisterAsVersioned_management(
                                dataset, "NO_EDITS_TO_BASE")
                        else:
                            # Logging
                            if (enableLogging == "true"):
                                logger.info("Dataset already versioned - " +
                                            dataset + "...")
                            arcpy.AddMessage("Dataset already versioned - " +
                                             dataset + "...")
                    count = count + 1
        # No configuration provided
        else:
            arcpy.AddError("No configuration file provided...")
            # Logging
            if (enableLogging == "true"):
                # Log error
                logger.error("No configuration file provided...")
                # Remove file handler and close log file
                logging.FileHandler.close(logMessage)
                logger.removeHandler(logMessage)
            if (sendErrorEmail == "true"):
                # Send email
                sendEmail("No configuration file provided...")

        # --------------------------------------- End of code --------------------------------------- #

        # If called from gp tool return the arcpy parameter
        if __name__ == '__main__':
            # Return the output if there is any
            if output:
                arcpy.SetParameterAsText(1, output)
        # Otherwise return the result
        else:
            # Return the output if there is any
            if output:
                return output
        # Logging
        if (enableLogging == "true"):
            # Log end of process
            logger.info("Process ended.")
            # Remove file handler and close log file
            logging.FileHandler.close(logMessage)
            logger.removeHandler(logMessage)
        pass
    # If arcpy error
    except arcpy.ExecuteError:
        # Build and show the error message
        errorMessage = arcpy.GetMessages(2)
        arcpy.AddError(errorMessage)
        # Logging
        if (enableLogging == "true"):
            # Log error
            logger.error(errorMessage)
            # Remove file handler and close log file
            logging.FileHandler.close(logMessage)
            logger.removeHandler(logMessage)
        if (sendErrorEmail == "true"):
            # Send email
            sendEmail(errorMessage)
    # If python error
    except Exception as e:
        errorMessage = ""
        # Build and show the error message
        for i in range(len(e.args)):
            if (i == 0):
                errorMessage = str(e.args[i])
            else:
                errorMessage = errorMessage + " " + str(e.args[i])
        arcpy.AddError(errorMessage)
        # Logging
        if (enableLogging == "true"):
            # Log error
            logger.error(errorMessage)
            # Remove file handler and close log file
            logging.FileHandler.close(logMessage)
            logger.removeHandler(logMessage)
        if (sendErrorEmail == "true"):
            # Send email
            sendEmail(errorMessage)
コード例 #17
0
# imports a list of feature classes from a file geodatabase into a sde database

import arcpy
import sys

sde = r"\\path\to\sde\connection.sde"
arcpy.env.workspace = sde

# disconnect users

print(".....disconnecting users...")
arcpy.DisconnectUser(sde, "ALL")

# delete existing layers

print("\t\t...Deleting feature classes")
features = ['featureClass1','featureClass2','featureClass3']

for values in features:
    print values,
    try:
        arcpy.Delete_management(values)
        print("\t\t ...deleted")
    except:
        print(" \t\t...failed to delete")

# set environment to fgdb for this part

fgdb = r"\\path\to\fileGeodatabase.gdb"
arcpy.env.workspace = fgdb
コード例 #18
0
    config.read(r'BuildingFootprint_config_template.ini')

    # Set log path
    log_path = config.get("PATHS", "distribute_log_path")
    log = open(log_path, "a")

    # Define zip, sde, and metadata paths
    zip_dir_path = config.get("PATHS", "zip_dir_path")
    zip_path = os.path.join(zip_dir_path, "Building_Footprints.zip")
    sde_path = config.get("PATHS", "sde_path")
    lyr_dir_path = config.get("PATHS", 'lyr_dir_path')
    template_path = config.get("PATHS", 'template_path')

    # Disconnect all users
    arcpy.AcceptConnections(sde_path, False)
    arcpy.DisconnectUser(sde_path, "ALL")

    # Set start time
    StartTime = datetime.datetime.now().replace(microsecond=0)

    # Set translator path for exporting metdata from SDE

    print("Setting arcdir")
    Arcdir = arcpy.GetInstallInfo("desktop")["InstallDir"]
    translator = Arcdir + "Metadata/Translator/ARCGIS2FGDC.xml"
    xslt_geoprocess = Arcdir + "Metadata/Stylesheets/gpTools/remove geoprocessing history.xslt"
    xslt_storage = Arcdir + "Metadata/Stylesheets/gpTools/remove local storage info.xslt"
    print("Arcdir set")

    # Allow for overwriting in SDE PROD environment
コード例 #19
0
'''
Created on Mar 12, 2013

@author: kyleg
'''
import arcpy
#admin_workspace = r"Database Connections\SQL61_AVIATION_DB.sde"
#admin_workspace = r"Database Connections\SDEDev-sde.sde"
admin_workspace = r"Database Connections\SDEPROD_sde.sde"
arcpy.env.workspace = admin_workspace
users = arcpy.ListUsers(admin_workspace) #
print users
arcpy.DisconnectUser(admin_workspace, "All")
arcpy.AcceptConnections(admin_workspace, True)
コード例 #20
0
arcpy.env.workspace = r"\\Apexgis\GIS\ApexSDE\current"
arcpy.env.overwriteOutput = 1
arcpy.Delete_management('in_memory')

# Clear users logged in

admin_workspace = r'C:\Users\Jlong\AppData\Roaming\ESRI\Desktop10.5\ArcCatalog\APEXWCD_ADMIN.sde'

users = arcpy.ListUsers(admin_workspace)
for user in users:
    print("Username: {0}, Connected at: {1},{2}".format(
        user.Name, user.ConnectionTime, user.ID))
    if user.Name == 'WCD':
        print("Disconnecting----{}".format(user.Name))
        arcpy.DisconnectUser(admin_workspace, user.ID)
    if user.Name == 'WCDVIEWER':
        print("Disconnecting----{}".format(user.Name))
        arcpy.DisconnectUser(admin_workspace, user.ID)


def clearWSLocks(inputWS):
    '''Attempts to clear locks on a workspace, returns stupid message.'''
    if all([
            arcpy.Exists(inputWS),
            arcpy.Compact_management(inputWS),
            arcpy.Exists(inputWS)
    ]):
        return 'Workspace (%s) clear to continue...' % inputWS
    else:
        return '!!!!!!!! ERROR WITH WORKSPACE %s !!!!!!!!' % inputWS
コード例 #21
0
import arcpy

try:
    data_set = arcpy.GetParameterAsText(0)
    is_compress_db = False
    if arcpy.GetArgumentCount() > 1:
        is_compress_db = arcpy.GetParameterAsText(1)
    work_space = arcpy.env["scriptWorkspace"]
    assert work_space

    data_set_desc = arcpy.Describe(data_set)
    if not data_set_desc.isVersioned:
        arcpy.AddMessage(f"Disallowing new connections.")
        arcpy.AcceptConnections(work_space, False)
        arcpy.AddMessage(f"Disconnecting all Users.")
        arcpy.DisconnectUser(work_space, "ALL")
        arcpy.AddMessage(f"Registering {data_set} as Versioned.")
        arcpy.RegisterAsVersioned_management(data_set, "EDITS_TO_BASE")
        if is_compress_db:
            arcpy.AddMessage(
                f"Compressing geodatabase, this could take some time.")
            arcpy.Compress_management(work_space)
        arcpy.AddMessage(f"Accepting User Connections.")
        arcpy.AcceptConnections(work_space, True)
    else:
        arcpy.AddMessage(
            f"Nothing to version, {data_set} is already registered as versioned."
        )

except Exception as e:
    arcpy.AddError(f"Problem in the script.\n {e}")
コード例 #22
0
    pass

################################################################################################################################

#                                        ACTUAL DATABASE MAINTENANCE ACTIVITY BEGINS HERE:

################################################################################################################################

#                                                       DISCONNECT USERS:

print("Booting all users...")

try:

    # method to disconnect all SDE users
    arcpy.DisconnectUser(db, 'ALL')

    with open(maintenance_log_FileName, 'a+') as maintenance_Log:
        maintenance_Log.write('\nBoot all connectedUsers: SUCCESS!')
        maintenance_log.close()

    print("...all users Booted!\n ")

except Exception as e:
    print(e)
    error_count = error_count + 1
    script_fails_time = datetime.datetime.now()
    with open(
            "C:\\GIS_Scripts\\SDE_Maintenance\\Update_2018-08-14\\Error_Log.txt",
            'a+') as error_Log:
        error_Log.write(
コード例 #23
0
# Import system modules
import arcpy, os

# set workspace
workspace = r"Database Connections\[email protected]_EGDB_20170105A.sde"

# set the workspace environment
arcpy.env.workspace = workspace

# No more users to connect to database
arcpy.AcceptConnections(workspace, False)

# Disconnect Users
arcpy.DisconnectUser(workspace, "ALL")

# Disconnect all users from the database.
arcpy.DisconnectUser('Database Connections/[email protected]_EGDB_20170105A.sde', "ALL")

# Get a list of versions to pass into the ReconcileVersions tool.
versionList = arcpy.ListVersions('Database Connections/[email protected]_EGDB_20170105A.sde')

# Execute the ReconcileVersions tool.
arcpy.ReconcileVersions_management('Database Connections/[email protected]_EGDB_20170105A.sde', "ALL_VERSIONS", "sde.DEFAULT", versionList, "LOCK_ACQUIRED", "ABORT_CONFLICTS", "BY_OBJECT", "FAVOR_TARGET_VERSION", "POST", "KEEP_VERSION", r"C:/Users/daniel.scott/Desktop/log.txt")

# Compress database
arcpy.Compress_management(workspace)
print 'Compression Complete'

# Get a list of stand alone feature classes
dataList = arcpy.ListFeatureClasses()
コード例 #24
0
'''
Created on Mar 12, 2013

@author: kyleg
'''
import arcpy
import ListUsersProd

ListUsersProd.main()

admin_workspace = r"Database Connections\SDEPROD_SDE.sde"
arcpy.env.workspace = admin_workspace
user_name = "GIS"
users = arcpy.ListUsers(admin_workspace)  #

for item in users:
    if item.Name == user_name:
        print(item.ID, item.Name, item.ClientName, item.IsDirectConnection)
        arcpy.DisconnectUser(admin_workspace, item.ID)

arcpy.AcceptConnections(admin_workspace, True)
コード例 #25
0
ファイル: zip_code_update.py プロジェクト: tghays/RetailGIS
hdlr = logging.FileHandler(log_path)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s',
                              datefmt='%m/%d/%Y %I:%M:%S %p')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
logger.info('\n\n\nCSG ZIP CODE UPDATE {0}'.format(log_date))

# Connect to SDE and remove users
admin = r'C:\Users\thays\AppData\Roaming\ESRI\Desktop10.4\ArcCatalog\GISAdmin.sde'

# Restrict Connections to Lowes_GIS and Disconnect users
logger.info('rejecting connections to geodatabase')
print('rejecting connections to geodatabase')
arcpy.AcceptConnections(admin, False)
arcpy.DisconnectUser(admin, "ALL")
logger.info('Disconnected users from gdb')
arcpy.env.overwriteOutput = True

# GIS Admin connection
arcpy.env.workspace = admin
edit = arcpy.da.Editor(admin)
edit.startEditing(False, False)

target_fc = admin + r'\T5034_GSP_ZIP_PNT'
cent_source = r"C:\Users\thays\OneDrive - Lowe's Companies Inc\Desktop\geodatabase\zip_update\2018-08\T5034_GSP_ZIP_PNT.mdb\T5034_GSP_ZIP_PNT"

print('getting source data')
logger.info('getting source data')
source_dict = {}
source_fields = [f.name for f in arcpy.ListFields(cent_source)][1:-2]
コード例 #26
0
proj_4326 = Proj(init='EPSG:4326')

try:
    settings = Settings(yml_file)
    if not __debug__:
        # must start Python with - o to use
        download_parcel_ftp(settings)
    shape_file_loc = find_parcel_shape(settings.download_path,
                                       settings.database)
    if not shape_file_loc:
        logging.error(f"Could not locate {settings.database}")
        exit(-1)
    #
    # arcgis stuff for multi-users
    arcpy.AcceptConnections(settings.workspace, False)
    arcpy.DisconnectUser(settings.workspace, "ALL")
    arcpy.env.workspace = settings.workspace

    # Manage FC names for copy
    #
    # if first time, create featuredataset HGAC
    ds = ec_arcpy_util.find_dataset("".join(("*", settings.data_set)))

    if ds is None:
        sr_2278 = arcpy.SpatialReference(2278)
        ds = arcpy.CreateFeatureDataset_management(settings.workspace,
                                                   settings.data_set, sr_2278)

    #
    # do a little clean up
    # if *_previous fc exists, delete
# Set an gdb admin connection variable.
adminConn = r"D:\EGT16\EGT16.sde"
LogMessage("Connecting to the geodatabase as the gdb admin user (sde)")

# Set a few environment variables
arcpy.env.workspace = adminConn
arcpy.env.overwriteOutput = True

# For demo purposes we will block connections to the geodatabase during schema rec/post/compress.
LogMessage("The database is no longer accepting connections")
arcpy.AcceptConnections(adminConn, False)

# Disconnect any connected users.
LogMessage("Disconnecting all users")
arcpy.DisconnectUser(adminConn, 'ALL')

# Get a list of versions to pass into the ReconcileVersions tool.
# Only reconcile versions that are children of Default
LogMessage("Compiling a list of versions to reconcile")
verList = arcpy.da.ListVersions(adminConn)
versionList = [
    ver.name for ver in verList if ver.parentVersionName == 'sde.DEFAULT'
]

# Execute the ReconcileVersions tool.
try:
    LogMessage("Reconciling versions")
    arcpy.ReconcileVersions_management(adminConn, "ALL_VERSIONS",
                                       "sde.DEFAULT", versionList,
                                       "LOCK_ACQUIRED", "NO_ABORT",
コード例 #28
0
# Owner directory
OwnerFileDir = "C:/Users/daniel.scott/Desktop/DataOwner/"
AdminFileDir = "C:/Users/daniel.scott/Desktop/DataOwner/"
# Admin directory
LogFile = open(
    r"W:\daniel.scott\arcgis\egdb\Phase1\EGDBmaintenance_" + datetime120 +
    ".csv", "w")
## Begin Script
ownerDB = os.listdir(OwnerFileDir)
for DB in ownerDB:
    try:
        arcpy.env.workspace = OwnerFileDir
        arcpy.AddMessage("Not Disconnecting users from " + DB + "\n")
        LogFile.write("Not Disconnecting users from," + DB + "\n")
        #arcpy.AcceptConnections(DB, False)
        arcpy.DisconnectUser(DB, "ALL")
        arcpy.AddMessage("Compressing " + DB + "\n")
        LogFile.write("Compressing," + DB + "\n")
        arcpy.Compress_management(DB)
        arcpy.AddMessage("Allowing connections to " + DB + "\n")
        LogFile.write("Allowing connections to," + DB + "\n")
        arcpy.AcceptConnections(DB, True)
    except arcpy.ExecuteError:
        msgs = arcpy.GetMessages(2)
        arcpy.AddError(msgs)
        arcpy.AddMessage(msgs)
        LogFile.write(msgs)
        ErrorCount = ErrorCount + 1
    except:
        if (arcpy.DisconnectUser == "true"):
            arcpy.AcceptConnections(DB, True)
コード例 #29
0

        emailed_count = emailed_count+1

# Pause for existing warned Users only if e-mail sent.
if sent_msg > 0:

    print 'Notified {0} users about upcoming maintenance.\nStarting 15 minute pause.'.format(sent_msg)
    time.sleep(900)
    print 'Resuming maintenance after 15 minute warning.'

    # Refuse new connections to database.
    print 'Refusing new connections'
    arcpy.AcceptConnections(db_connection, False)

else:
    print 'Refusing new connections'
    arcpy.AcceptConnections(db_connection, False)

# Disconnect all users from database.
print 'Disconnecting all users'
arcpy.DisconnectUser(db_connection, "ALL")

# Enable for testing mode only.
### Allow new connections to start database data sync processing
##print 'Allowing new connections'
##arcpy.AcceptConnections(db_connection, True)



コード例 #30
0
ファイル: SpeedyID.py プロジェクト: alanvenneman/Programming
    os.remove(r"C:\temp\TestDB.sde")
except:
    pass

#Reconcile and compress SDE
try:
    sde = arcpy.CreateDatabaseConnection_management(
        r"C:\temp", "TestDB", "SQL_SERVER", "GIS3", "OPERATING_SYSTEM_AUTH",
        "", "*****", "SAVE_USERNAME", "water_test", "", "TRANSACTIONAL",
        "sde.DEFAULT", "")
    arcpy.env.workspace = str(sde)
    print str(sde) + " is no longer accepting connections"
    arcpy.AcceptConnections(sde, False)  #block new connections to the database
    try:
        print "Disconnecting all users"
        arcpy.DisconnectUser(sde,
                             "ALL")  #disconnect all users from the database
    except:
        print ""
        raw_input(
            "Insufficient privileges to disconnect users.  Press ENTER to exit."
        )
        quit()
    print "Compiling a list of versions to reconcile"
    versionList = arcpy.ListVersions(
        sde)  #list of versions to pass into the ReconcileVersions tool
    print "Reconciling all versions"
    arcpy.ReconcileVersions_management(sde, "ALL_VERSIONS", "sde.DEFAULT",
                                       versionList, "LOCK_ACQUIRED",
                                       "NO_ABORT", "BY_OBJECT",
                                       "FAVOR_TARGET_VERSION", "POST",
                                       "DELETE_VERSION", "")