Welcome, guest | Sign In | My Account | Store | Cart

This module enables users on the windows platform to transfer files to remote hosts. Requires pywin32 extensions by Mark Hammond

Python, 115 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/usr/bin/env python
#win32wnetfile.py

import os
import os.path
import shutil
import sys
import win32wnet

def netcopy(host, source, dest_dir, username=None, password=None, move=False):
    """ Copies files or directories to a remote computer. """
    
    wnet_connect(host, username, password)
            
    dest_dir = covert_unc(host, dest_dir)

    # Pad a backslash to the destination directory if not provided.
    if not dest_dir[len(dest_dir) - 1] == '\\':
        dest_dir = ''.join([dest_dir, '\\'])

    # Create the destination dir if its not there.
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)
    else:
        # Create a directory anyway if file exists so as to raise an error.
         if not os.path.isdir(dest_dir):
             os.makedirs(dest_dir)

    if move:
        shutil.move(source, dest_dir)
    else:
        shutil.copy(source, dest_dir)

def netdelete(host, path, username=None, password=None):
    """ Deletes files or directories on a remote computer. """
    
    wnet_connect(host, username, password)

    path = covert_unc(host, path)
    if os.path.exists(path):
        # Delete directory tree if object is a directory.        
        if os.path.isfile(path):
            os.remove(path)
        else:
            shutil.rmtree(path)
    else:
        # Remove anyway if non-existent so as to raise an error.        
        os.remove(path)

def netmove(host, source, dest_dir, username=None, password=None):
    return netcopy(host, source, dest_dir, username, password, True)

def covert_unc(host, path):
    """ Convert a file path on a host to a UNC path."""
    return ''.join(['\\\\', host, '\\', path.replace(':', '$')])
    
def wnet_connect(host, username, password):
    unc = ''.join(['\\\\', host])
    try:
        win32wnet.WNetAddConnection2(0, None, unc, None, username, password)
    except Exception, err:
        if isinstance(err, win32wnet.error):
            # Disconnect previous connections if detected, and reconnect.
            if err[0] == 1219:
                win32wnet.WNetCancelConnection2(unc, 0, 0)
                return wnet_connect(host, username, password)
        raise err

if __name__ == '__main__':

    # Copy "c:\documents" folder/file to "c:\transferred" on host "w0001".
    netcopy('w0001', 'c:\\documents', 'c:\\transferred')

    # Move with account credentials.
    netmove('w0001', 'c:\\documents', 'c:\\transferred', 'admin', 'adminpass')

    # Delete with another account.
    netdelete('w0001', 'c:\\transferred', 'testdom\\user1', 'user1pass')

    # Transfer files using different accounts, to multiple computers.    
    accounts = [
        ('administrator', 'adminpass'),
        ('desktopeng', 'depass'),
        ('testdom\\administrator', 'dompass')]
    
    computers = ['w0001', 'w0002', 'w0003', 'w0004', 'w0005', 'w0006']

    auth_failed = []
    transfer_failed = []
    
    for computer in computers:
        # Try to authenticate with the each account provided.
        for account in accounts:
            username, password = account
            try:
                wnet_connect(computer, username, password)
            except Exception, err:
                # Look for authentication failures.
                if isinstance(err, win32wnet.error) and err[0] == 1326:
                    if account == accounts[len(accounts) -1]:
                        auth_failed.append(computer)
                else:
                    transfer_failed.append(computer)
                    break
            else:
                try:
                    netcopy(computer, 'c:\\documents', 'c:\\transferred')
                except Exception, err:
                    print err
                    transfer_failed.append(computer)
                break

    # Status report
    print 'Authentication failure: %s' % (str(auth_failed).strip("[]'"))
    print 'Unknown failure: %s' % (str(transfer_failed).strip("[]'"))
                
    

Included is an example to transfer files/directories to multiple computers using different accounts. Great for administrators.

3 comments

Luke Epsilon 18 years, 5 months ago  # | flag

smb? cifs? Is this using smb or cifs as an underlying protocol for the transfer? I find both of these protocols to have painful latency and inherent slowness. I am looking for a module that has this functionality but which works fast. I guess with this module the windows user features for permissions is achieved.

Thanks, Luke

jelle feringa 16 years, 5 months ago  # | flag

not working completely well though... Hi,

I think this is a useful contribution, though I ran in some problem. Especially when copying directories. The following solves that:

# Create the destination dir if its not there.
#if not os.path.exists(dest_dir):
#    os.makedirs(dest_dir)
#else:
#    # Create a directory anyway if file exists so as to raise an error.
#     if not os.path.isdir(dest_dir):
#         os.makedirs(dest_dir)

if move:
    if os.path.isdir(source):
        shutil.copytree(source, destdir)
        shutil.rmtree(source)
    elif os.path.isfile(source):
        shutil.move(source, dest_dir)
    else:
        raise AssertionError, '%s is neither a file nor directory' % (source)
else:
    if os.path.isdir(source):
        shutil.copytree(source, dest_dir)
    elif os.path.isfile(source):
        shutil.copy(source, dest_dir)
    else:
        raise AssertionError, '%s is neither a file nor directory' % (source)

cheers,

-jelle

sdv 10 years, 7 months ago  # | flag

How to Know that destination computer has C:\ or D:\ drive ? I have an exe file which gives me the EP installed components.I need to deploy that in my network in all switched on machines.But detination dir may vary across machines.Plz help?