View on GitHub

win_unc

Python library for handling UNC connections on Windows

Download this project as a .zip file Download this project as a tar.gz file

Why win_unc?

This library is for anyone who has tried to connect to or mount UNC paths in a Python script on Windows. Understanding how to wield the NET USE command is a feat in itself. Parsing its output programatically to know if your command worked is much harder.

Fortunately, this library should make your life a lot easier.

Contents

Installation

To install:

$ pip install win_unc

Getting pip on Windows

Of course, installing pip packages on Windows is not always straightforward. Here’s how:

Download the setuptools installer for your platform and run it. Note that for 64-bit Windows, you need to download the ez_setup.py script instead of the .exe installer.

Once you’ve installed setuptools, you need to add some paths to your system’s Path environment variable. You’ll probably want to add paths like these:

Then, in Windows command-line (cmd.exe), you can run the following to get pip installed:

> easy_install pip

Basic Usage

Below is a simple example:

from win_unc import (DiskDrive, UncDirectory,
                     UncDirectoryConnection, UncDirectoryMount)


# Connect a shared directory without authorization.
unc = UncDirectory(r'\\home\shared')
conn = UncDirectoryConnection(unc, persistent=True)

conn.connect()
print 'Connected?', conn.is_connected()
conn.disconnect()


# Mount another directory with authorization to the Z: drive.
creds = UncCredentials('user', 'pwd')
authz_unc = UncDirectory(r'\\remote\shared', creds)

mnt = UncDirectoryMount(authz_unc, DiskDrive('Z:'))

mnt.mount()
print 'Mounted?', mnt.is_mounted()
mnt.unmount()


# Mount a directory to any available local drive.
mnt2 = UncDirectoryMount(UncDirectory(r'\\neighbor\shared'))
mnt2.mount()
print 'Mounted at:', mnt2.disk_drive
mnt2.unmount()

Documentation

UncDirectoryConnection

The UncDirectoryConnection class describes how a UNC directory relates to the current Windows sesssion. Use this class when you want to connect or disconnect a UNC directory. You can also use it to determine if a UNC directory is connected or not.

__init__

UncDirectoryConnection(
    unc_directory,
    disk_drive=None,
    persistent=False,
    logger=no_logging)

Constructs a new UncDirectoryConnection object.

unc_directory must be a UncDirectory object which provides a UNC path and any credentials necessary to authorize the connection.

disk_drive must be None or a DiskDrive object.

persistent must be True if you want the UNC directory connection to persist across multiple Windows sessions. Otherwise, set this to False (the default).

logger must be a function that takes a single string argument. The function will be called whenever the object does something worthy of being logged.

For example, logger could look like this:

def my_logger(message):
    print message

connect

connect()

Connects the UNC directory. If the command fails, a ShellCommandError will be raised.

Connecting can also be achieved using UncDirectoryConnection’s context manager.

disconnect

disconnect()

Disconnects the UNC path. If the command fails, a ShellCommandError will be raised.

Disconnecting can also be achieved using UncDirectoryConnection’s context manager.

is_connected

is_connected()

Returns True if the system registers this UncDirectoryConnection as connected or False otherwise. A UNC path is considered connected when the system reports its status as either OK or Disconnected.

Note: This method does not rely on any internal state management of the object. It is entirely possible to construct a new UncDirectoryConnection that is already connected by the system. In this case, the result of is_connected will be True even if no calls to connect have yet been made.

Why “Disconnected” Is Considered Connected

In the context of the system, a status of Disconnected means that the UNC path’s connection has been authorized and established but it is temporarily disconnected (probably because it has been idle for some period of time).

To refresh the connection of a Disconnected UNC path, you can usually just perform some trivial task with the directory. For example, you could query its contents like this:

> dir \\unc\path

This commonly refreshes the UNC connection and restores its status to OK.

However, these steps are not usually necessary since merely accessing the UNC path in any way will cause the system to reconnect it.

get_connection_status

get_connection_status()

Returns one of the following based on this UncDirectoryConnection’s status according to the system:

StatusMeaning
'ok'connected
'disconnected'recognized but inactive
'unavailable'a previous connection attempt failed
Nonenot connected

get_path

get_path()

Returns the UNC path being used by this UncDirectoryConnection.

(This is a pass-through method for the underlying UncDirectory. See UncDirectory’s get_path method.)

get_username

get_username()

Returns the username of the credentials being used by this UncDirectoryConnection or None if no username was provided.

(This is a pass-through method for the underlying UncDirectory. See UncDirectory’s get_username method.)

get_password

get_password()

Returns the password of the credentials being used by this UncDirectoryConnection or None if no password was provided.

(This is a pass-through method for the underlying UncDirectory. See UncDirectory’s get_password method.)

unc (member)

The UncDirectory for this UncDirectoryConnection.

disk_drive (member)

The DiskDrive of the mount point for this UncDirectoryConnection or None if no mount point is provided.

persistent (member)

True if the Windows system should remember this connection for future sessions of the current user or False otherwise.

logger (member)

The logging function to use for logging purposes. This must point to a function that takes exactly one string argument containing the message of a log.

Context Management

The UncDirectoryConnection class supports context management via the ”with syntax”.

For example,

conn = UncDirectoryConnection(UncDirectory(r'\\localhost'))
conn.connect()
# do stuff...
conn.disconnect()

is equivalent to

with UncDirectoryConnection(UncDirectory(r'\\localhost')) as conn:
    # do stuff...

When entering UncDirectoryConnection’s context manager, the UNC path is connected and, when exiting, the UNC path is disconnected. However, the context manager tries to maintain the state of the system: if the UNC path was already connected when entering the context manager, it will not be disconnected when exiting. Of course, calling connect or disconnect directly from within the with-block will affect the system’s state after the context manager exits.

UncDirectoryMount

The UncDirectoryMount class is a UncDirectoryConnection that specifically represents a connection with a mount point. Unless noted here, this class is identical to UncDirectoryConnection.

__init__

UncDirectoryConnection(
    unc_directory,
    disk_drive=None,
    persistent=False,
    logger=no_logging)

Constructs a new UncDirectoryMount.

For unc_directory, persistent, and logger see UncDirectoryConnection’s constructor.

disk_drive must be None or a DiskDrive.

mount

An alias for UncDirectoryConnection’s connect method.

mount

An alias for UncDirectoryConnection’s disconnect method.

is_mounted

An alias for UncDirectoryConnection’s is_connected method.

Context Management

See UncDirectoryConnection’s context manager.

UncDirectory

The UncDirectory class describes the path to a UNC directory and (optionally) any credentials that are needed to authorize a connection to the path.

__init__

UncDirectory(
    path,
    unc_credentials=None)

Constructs a new UncDirectory object.

path must be a string representing a UNC path. If path cannot be construed as a valid UNC path, an InvalidUncPathError will be raised.

unc_credentials may be either None or a UncCredentials object.


UncDirectory(
    unc_directory)

Constructs a new UncDirectory object as a clone of unc_directory. The clone will be a “shallow” copy, so the underlying UncCredentials object used by the clone will have the same id as the original.

unc_directory must be a UncDirectory object to clone.

get_path

get_path()

Returns the UNC path for this UncDirectory. The UNC path may differ slightly from the one provided at the construction of the object since the constructor does some cleaning of the path before it is used.

get_normalized_path

get_normalized_path()

Returns the normalized path for this UncDirectory. Differing UNC paths that all point to the same network location will have the same normalized path.

For example, the following UNC paths all have a normalized path of \\remote:

get_username

get_username()

Returns the username of the credentials being used by this UncDirectory or None if no username was provided.

(This is a pass-through method for the underlying UncCredentials object. See UncCredentials’ get_username method.)

get_password

get_password()

Returns the password of the credentials being used by this UncDirectory or None if no password was provided.

(This is a pass-through method for the underlying UncCredentials object. See UncCredentials’ get_password method.)

get_auth_string

get_auth_string()

Returns the authorization string associated with the credentials of this UncDirectory.

(This is a pass-through method for the underlying UncCredentials object. See UncCredentials’ get_auth_string method.)

get_auth_path

get_auth_path()

Returns the path of this UncDirectory with the authorization string prepended (see get_auth_string). If this UncDirectory has no associated credentials, the returned path will be the same as get_path.

The result of this method can be parsed by get_unc_directory_from_string to get a new UncDirectory.

The following table shows some examples of how this authorized path string is formatted:

UsernamePasswordPathAuthorized Path String
NoneNoner'\\remote\path'r'\\remote\path'
'user'Noner'\\remote\path'r'user@\\remote\path'
'user''pwd'r'\\remote\path'r'user:pwd@\\remote\path'
None'pwd'r'\\remote\path'r':pwd@\\remote\path'
'user'''r'\\remote\path'r'user:@\\remote\path'

UncCredentials

The UncCredentials class represents a set of credentials (username and password) to be used with a UNC connection.

__init__

UncCredentials(
    username=None,
    password=None)

Constructs a new UncCredentials object.

username must be None or a string representing a Windows username (logon).

Usernames may include a domain prefix (i.e. “domain\username”), but if username cannot be construed as a valid Windows username, then an InvalidUsernameError will be raised. Realize that providing None and '' (the empty string) for username have very different meanings. Windows usernames cannot be empty.

password must be None or a string representing a password. Realize that providing None (no password) and '' (the empty string) have very different meanings. The empty string is a meaningful, legitimate password.


UncCredentials(
    unc_credentials)

Constructs a new UncCredentials object as a clone of unc_credentials.

unc_credentials must be a UncCredentials object to clone.

get_username

get_username()

Returns the username of this UncCredentials object or None if no username was provided.

get_password

get_password()

Returns the password of this UncCredentials object or None if no password was provided.

is_empty

is_empty()

Returns True if this UncCredentials object does not contain any meaningful credentials and False otherwise.

get_auth_string

get_auth_string()

Returns a standard representation of this UncCredentials object as a string that can be parsed into a new UncCredentials object by get_creds_from_string.

The following table shows some examples of how this authorization string is formatted:

UsernamePasswordAuthorization String
NoneNone''
'user'None'user'
'user''pwd''user:pwd'
None'pwd':pwd
'user'''user:

DiskDrive

The DiskDrive class represents a Windows disk drive. Disk drives are always identified by a single alphabet character. They may map to hardware devices, local directories, or remote directories.

__init__

DiskDrive(
    drive_letter)

Constructs a new DiskDrive.

drive_letter must be a single letter from A to Z for representing a drive letter. There is some leniency as to what strings are recognized.

The following are all interpreted as the drive letter G:


DiskDrive(
    disk_drive)

Constructs a new DiskDrive as a clone of disk_drive.

disk_drive must be a DiskDrive object to clone.

get_drive

get_drive()

Returns this path for this DiskDrive. The path will always be an upper-case letter followed by a colon (:). For example, if the drive letter is 'G' then this will return 'G:'.

Parsing Functions

These parsing functions can be used to deserialize (often called “unpickling” in the Python community) various objects in the win_unc library.

is_unc_directory_string

from win_unc.unc_directory import is_unc_directory_string

is_unc_directory_string(string)

Returns True when string represents a UncDirectory as defined by UncDirectory’s get_auth_path method or False otherwise.

get_unc_directory_from_string

from win_unc.unc_directory import get_unc_directory_from_string

unc = get_unc_directory_from_string(string)

Parses a standardized string from UncDirectory’s get_auth_path method and returns a new UncDirectory based on it. This may raise any errors that can be raised by UncDirectory’s constructor.

get_creds_from_string

from win_unc.unc_credentials import get_creds_from_string

creds = get_creds_from_string(string)

Parses a standardized string from UncCredentials’ get_auth_string method and returns a new UncCredentials object based on it. This may raise any errors than can be raised by UncCredentials’ constructor.

System Querying Functions

These functions query the system for the current state of UNC connections and mounts.

get_current_connections

from win_unc.query import get_current_connections

conns = get_current_connections()

Returns a list of UncDirectoryConnection or UncDirectoryMount objects. Each object represents a connection or mount currently recognized by the system.

get_connection_for_unc_directory

from win_unc.query import get_connection_for_unc_directory

conn = get_connection_for_unc_directory()

Returns a UncDirectoryConnection or UncDirectoryMount representing a connected or mounted UNC directory that matches a given UNC directory (unc) or None if no system connections or mounts match unc.

unc must be a UncDirectory.

get_connection_for_disk_drive

from win_unc.query import get_connection_for_disk_drive

conn = get_connection_for_disk_drive()

Returns a UncDirectoryMount representing a mounted UNC directory that matches a disk drive (disk_drive) or None if no system mounts match disk_drive.

disk_drive must be a DiskDrive.

Exception Classes

win_unc uses a set of exception classes to describe errors that could arise when using the library. They can be imported from the win_unc.errors module and they each inherit from WinUncError.

For each exception class, the magic __str__ method returns a description of the error.

WinUncError

The WinUncError class inherits from Exception and acts as an umbrella for all exception classes that can be raised by the win_unc package. This class does not have its own interface other than what is provided by Exception. It is not meant to be raised or instantiated.

InvalidUncPathError

Represents the error that occurs when an invalid UNC path is provided to UncDirectory’s constructor.

InvalidUsernameError

Represents the error that occurs when an invalid Windows username (logon) is provided to UncCredentials’ constructor.

NoDrivesAvailableError

Represents the error that occurs when an available disk drive is needed but cannot be found.

ShellCommandError

Represents the error that occurs when a shell command has been executed and returns an error code.

License

This package is released under the MIT License.