Пример #1
0
def mapDrive(drive, networkPath, user, password, force=0):
    print networkPath
    if (os.path.exists(drive)):
        print drive, " Drive in use, trying to unmap..."
        if force:
            try:
                win32wnet.WNetCancelConnection2(drive, 1, 1)
                print drive, "successfully unmapped..."
            except:
                print drive, "Unmap failed, This might not be a network drive..."
                return -1
        else:
            print "Non-forcing call. Will not unmap..."
            return -1
    else:
        print drive, " drive is free..."
    if (os.path.exists(networkPath)):
        print networkPath, " is found..."
        print "Trying to map ", networkPath, " on to ", drive, " ....."
        try:
            win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive,
                                         networkPath, None, user, password)
        except:
            print "Unexpected error..."
            return -1
        print "Mapping successful"
        return 1
    else:
        print "Network path unreachable..."
        return -1
Пример #2
0
 def testAddConnectionOld(self):
     localName = self.findUnusedDriveLetter() + ':'
     for share in self.iterConnectableShares():
         win32wnet.WNetAddConnection2(share.dwType, localName,
                                      share.lpRemoteName)
         win32wnet.WNetCancelConnection2(localName, 0, 0)
         break
Пример #3
0
 def run(self):
     connected = 0
     if self.user:
         try:
             win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_ANY,
                                          None, ''.join([r'\\', self.host]),
                                          None, self.user, self.password)
         # Don't fail on error, it might just work without the connection.
         except:
             pass
         else:
             connected = 1
     # We need the remote shutdown or shutdown privileges.
     p1 = win32security.LookupPrivilegeValue(self.host,
                                             win32con.SE_SHUTDOWN_NAME)
     p2 = win32security.LookupPrivilegeValue(
         self.host, win32con.SE_REMOTE_SHUTDOWN_NAME)
     newstate = [(p1, win32con.SE_PRIVILEGE_ENABLED),
                 (p2, win32con.SE_PRIVILEGE_ENABLED)]
     # Grab the token and adjust its privileges.
     htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                             win32con.TOKEN_ALL_ACCESS)
     win32security.AdjustTokenPrivileges(htoken, False, newstate)
     win32api.InitiateSystemShutdown(self.host, self.msg, self.timeout,
                                     self.force, self.reboot)
     # Release the previous connection.
     if connected:
         win32wnet.WNetCancelConnection2(''.join([r'\\', self.host]), 0, 0)
Пример #4
0
def shutdown(host=None, user=None, passwrd=None, msg=None, timeout=0, force=1,
             reboot=0):
    """ Shuts down a remote computer, requires NT-BASED OS. """
    
    # Create an initial connection if a username & password is given.
    connected = 0
    if user and passwrd:
        try:
            win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_ANY, None,
                                         ''.join([r'\\', host]), None, user,
                                         passwrd)
        # Don't fail on error, it might just work without the connection.
        except:
            pass
        else:
            connected = 1
    # We need the remote shutdown or shutdown privileges.
    p1 = win32security.LookupPrivilegeValue(host, win32con.SE_SHUTDOWN_NAME)
    p2 = win32security.LookupPrivilegeValue(host,
                                            win32con.SE_REMOTE_SHUTDOWN_NAME)
    newstate = [(p1, win32con.SE_PRIVILEGE_ENABLED),
                (p2, win32con.SE_PRIVILEGE_ENABLED)]
    # Grab the token and adjust its privileges.
    htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                           win32con.TOKEN_ALL_ACCESS)
    win32security.AdjustTokenPrivileges(htoken, False, newstate)
    win32api.InitiateSystemShutdown(host, msg, timeout, force, reboot)
    # Release the previous connection.
    if connected:
        win32wnet.WNetCancelConnection2(''.join([r'\\', host]), 0, 0)
Пример #5
0
def map_drive(drive, networkPath, user, password, force=False):
    logging.info("Checking the path: {}".format(networkPath))
    if (os.path.exists(drive)):
        logging.info("{} Drive is already mounted.".format(drive))

        if force:
            logging.info("trying to unmap drive {}...".format(drive))
            try:
                win32wnet.WNetCancelConnection2(drive, 1, 1)
                logging.info("Successfully unmapped {}...".format(drive))
            except:
                logging.error(
                    "Drive Unmap failed for {}, This might not be a network drive..."
                    .format(drive))
                return False
        else:
            logging.info("Non-forcing call. Will not unmap...")
            return False
    else:
        logging.info("Drive {} is free to map...".format(drive))

    logging.info("Trying to map {} to drive {}".format(networkPath, drive))
    try:
        win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive,
                                     networkPath, None, user, password)
    except Exception as ex:
        logging.error(
            "Unexpected error while mapping {} to drive {}: {}".format(
                networkPath, drive, ex))
        return False
    logging.info("Successfully mapped {} to drive {}".format(
        networkPath, drive))
    return True
def unMapDrive(driveLetter):
    try:
        win32wnet.WNetCancelConnection2(driveLetter, 0, 0)
        return True
    except win32wnet.error, description:
        logger.error("Unable to unmap network drive %s %s" %
                     (driveLetter, description[2]))
        return False
Пример #7
0
def unmount_share(letter):
    """Unmount the share designed by the letter"""
    if letter:
        print("Unmounting share %s" % letter)
        try:
            win32wnet.WNetCancelConnection2(letter, 1, 1)  # force unmap
            print("Share %s successfully unmounted" % letter)
        except win32wnet.error:
            print("Cannot unmount specified share")
Пример #8
0
def wnet_connect(host, username, password):
    unc = ''.join(['\\\\', str(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
Пример #9
0
def wnet_connect(host, username, password):
    import win32wnet

    unc = ''.join(['\\\\', host])
    try:
        win32wnet.WNetAddConnection2(0, None, unc, None, username, password)
    except Exception, err:
        if isinstance(err, win32wnet.error):
            if err[0] == 1219:
                win32wnet.WNetCancelConnection2(unc, 0, 0)
                return wnet_connect(host, username, password)
        raise err
Пример #10
0
    def remove(self, resource):
        with self.__lock:
            name = resource.lpRemoteName
            if name not in self.__resources:
                return

            self.__resources[name] -= 1
            if self.__resources[name] == 0:
                del self.__resources[name]

                # https://docs.microsoft.com/en-us/windows/win32/api/winnetwk/nf-winnetwk-wnetcancelconnection2a
                # https://mhammond.github.io/pywin32/win32wnet__WNetCancelConnection2_meth.html
                win32wnet.WNetCancelConnection2(name, 0, 1)
Пример #11
0
 def connect_to_share_path(self, ip, user, password):
     '''
     Establish a share connection.
     
     Example:
     | Connect To Share Path | ${IMAGE_SHARE_IP} | ${IMAGE_SHARE_USERNAME} | ${IMAGE_SHARE_PASSWORD} |
     '''
     try:
         unc = unc = ''.join(['\\\\', ip])
         win32wnet.WNetAddConnection2(0, None, unc, None, user, password)
     except:
         win32wnet.WNetCancelConnection2(unc, 0, 0)
         win32wnet.WNetAddConnection2(0, None, unc, None, user, password)
Пример #12
0
 def _wnet_connect(self):
     unc = ''.join(['\\\\', self.ip])
     netresource = win32wnet.NETRESOURCE()
     netresource.lpRemoteName = unc
     try:
         win32wnet.WNetAddConnection2(netresource, self.username, self.password, 0)
     except Exception as err:
         if isinstance(err, win32wnet.error):
             # Disconnect previous connections if detected, and reconnect.
             if err.winerror == 1219:
                 win32wnet.WNetCancelConnection2(unc, 0, 0)
                 return self._wnet_connect()
         raise err
Пример #13
0
 def disconnect_from_network_share(self):
     if self.connected == False:
         return
     try:
         logger.info("Trying to disconnect from the network share %s" %
                     self.network_share)
         win32wnet.WNetCancelConnection2(self.network_share, 1, True)
         logger.info("Successfully disconnected from the network")
         self.connected = False
     except win32wnet.error, (n, f, e):
         if n == winerror.ERROR_NOT_CONNECTED:  #2250: This network connection does not exist
             logger.info("Was already disconnected from network")
         else:
             raise
Пример #14
0
    def umount(self):
        if self.mountPoint is None:
            return True

        try:
            win32wnet.WNetCancelConnection2(self.mountPoint, 0, True)

        except Exception:
            Logger.exception("Unable to umount drive")
            Logger.debug(
                "Unable to umount drive, net use command equivalent: '%s'" %
                ("net use %s: /delete" % (self.mountPoint)))
            return False
        return True
Пример #15
0
def wnet_connect(server, username = None, password = None):
  global user, pwrd, netpath, host, domain
  networkPath = netpath
  unc = ''.join(['\\\\', host])
  print unc
  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
Пример #16
0
 def disconnect_drive(self, drive, force=False):
     if os.path.exists(drive):
         self.log.info("Drive: {} in use. Trying to Unmap..".format(drive))
         force = 0 if not force else 1
         try:
             win32wnet.WNetCancelConnection2(drive, 1, force)
             self.log.info("Drive: {} successfully unmapped".format(drive))
             return 1
         except:
             strmsg = "Unmapping failed. This may not be a network drive..."
             self.log.info(strmsg)
             return -1
     else:
         self.log.info("Drive: {} is already free".format(drive))
         return 0
Пример #17
0
def wnet_connect(host, username=None, password=None):
    #netpath = r'\\ali-netapp1.linus.sen.symantec.com\polaris'
    netpath = r'\\ali-netapp1.linus.sen.symantec.com'
    networkPath = netpath
    unc = ''.join(['\\\\', host])
    print unc
    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
Пример #18
0
def cifs_umount(mount):
    try:
        Output.verbose("Doing umount of {0}".format(
            mount.settings["Windows_letter"]))
        win32wnet.WNetCancelConnection2(mount.settings["Windows_letter"], 0,
                                        False)
        cifs_uncache_is_mounted(mount)
    except pywintypes.error as e:
        if e.winerror == 2401:  # (2401, "WNetCancelConnection2", "There are open files on the connection.")
            mount.ui.notify_user(e.strerror)
        elif e.winerror == 2250:  # (2250, 'WNetCancelConnection2', 'This network connection does not exist.')
            mount.ui.notify_user(e.strerror)
        else:
            Output.error("failed : {0}".format(e))
            debug_send("umount:\n{0}".format(e))
Пример #19
0
def unmap_drive(drive, force=False):
    #Check if the drive is in use
    if (os.path.exists(drive)):
        logging.info("drive in use, trying to unmap...")
        if not force:
            logging.info("Executing un-forced call...")
        try:
            win32wnet.WNetCancelConnection2(drive, 1, force)
            logging.info("{} successfully unmapped...".format(drive))
            return True
        except:
            logging.info("Unmap failed, try again...")
            return False
    else:
        logging.info("{} Drive is already free...".format(drive))
        return True
Пример #20
0
def unmapDrive(drive, force=0):
    #Check if the drive is in use
    if (os.path.exists(drive)):
        print "drive in use, trying to unmap..."
        if force == 0:
            print "Executing un-forced call..."
        try:
            win32wnet.WNetCancelConnection2(drive, 1, force)
            print drive, "successfully unmapped..."
            return 1
        except:
            print "Unmap failed, try again..."
            return -1
    else:
        print drive, " Drive is already free..."
        return -1
Пример #21
0
    def connect_copy(self):
        """ Function used by W2W_Copy to establish a win32wnet connection
            before copying the files.

        Example:
        | self.connect_copy | This function should be called by W2W_Copy to establish a connection |
        """
        unc = ''.join(['\\\\', self.host])
        try:
            win32wnet.WNetAddConnection2(0, None, unc, None, self.username,
                                         self.password)
        except Exception as err:
            if isinstance(err, win32wnet.error):
                # Disconnect previous connections if detected, and reconnect.
                if err[0] == 1219:
                    win32wnet.WNetCancelConnection2(unc, 0, 0)
                    return self.connect_copy()
            raise err
Пример #22
0
    def connect(self):
        """
        Open a WNET connection to a remote server if any exception
        occures Disconnect previous connections if detected, and reconnect.
        """
        self.unc = ''.join(['\\\\', self.host])
        logger.debug(self.unc)
        retry = self.retry
        while retry:
            try:
                win32wnet.WNetAddConnection2(0, None, self.unc, None,
                                             self.username, self.password)
                logger.debug("wnet connection successful")
                break
            except Exception as err:
                retry -= 1
                logger.debug('Exception: retrying connection')
                if isinstance(err, win32wnet.error):
                    # Disconnect previous connections if detected, and reconnect.
                    if err[0] == 1219:
                        logger.debug('Connection error 1219')
                        try:
                            win32wnet.WNetCancelConnection2(self.unc, 0, 0)
                            win32wnet.WNetAddConnection2(
                                0, None, self.unc, None, self.username,
                                self.password)
                        except:
                            logger.debug(
                                'Either cancel connection or create connection failed'
                            )
                            continue
                if retry:
                    logger.debug('Retrying %s time' %
                                 (str(self.retry - retry)))
                    continue

                logger.debug(str(err))
                raise AssertionError('Unable to establish connection')
Пример #23
0
                                os.path.dirname(target_dir), log,
                                manager.default_encoding)
                            for filename in os.listdir(target_dir):  #
                                full_filename = os.path.join(
                                    target_dir, filename)
                                stat = os.stat(full_filename)
                                if os.path.isdir(
                                        full_filename) and filename.lower(
                                        ).startswith('backup '):
                                    dir_out, total_size = windows_list_dir(
                                        full_filename, log,
                                        manager.default_encoding)
                                    break
                        finally:
                            win32wnet.WNetCancelConnection2(
                                param_encode(self.target,
                                             manager.default_encoding), 0,
                                False)
                    except Exception, e:
                        log.error(
                            'checking target directory: %s',
                            WindowsErrorDecode(e, manager.default_encoding))
                        status += 'target_free_space=%s\r\n' % WindowsErrorDecode(
                            e, manager.default_encoding)

            if total_free_bytes:
                status += 'target_free_space=%d\r\n' % total_free_bytes
            if total_size:
                status += 'target_size=%d\r\n' % total_size

        # run wbadmin get versions
        wba_versions_args = [
Пример #24
0
    def load(self, job, manager):

        errors, warnings, extra = WbadminBase.load(self, job, manager)

        log = manager.log
        now = manager.now

        #
        # check job config
        #

        self.include = job.get('include', None)
        if self.include and not self.destination:
            errors['include'] = 'destination required'

        self.user = job.get('user', None)
        if self.user and not self.destination:
            errors['user'] = '******'

        self.password = job.get('password', None)
        self.register_password(self.password)

        if self.user and not self.destination:
            errors['password'] = '******'

        if (self.user and not self.password) or (not self.user
                                                 and self.password):
            errors['password'] = '******'

        if not errors:
            if not self.destination:
                self.type, self.target = 'default', None
            else:
                self.type, self.target = self.destination.match(
                    now, self.night_shift)

                if self.type != None and self.type != 'none':
                    # check the target
                    if self.target and not is_volumeid(
                            self.target) and not os.path.isdir(self.target):
                        try:
                            os.makedirs(self.target)
                        except WindowsError, e:
                            unc = os.path.splitunc(self.target)[0]
                            if unc and self.user and self.password:
                                try:
                                    win32wnet.WNetAddConnection2(
                                        win32netcon.RESOURCETYPE_DISK, None,
                                        param_encode(unc,
                                                     manager.default_encoding),
                                        None,
                                        param_encode(self.user,
                                                     manager.default_encoding),
                                        param_encode(self.password,
                                                     manager.default_encoding))
                                    try:
                                        if not os.path.isdir(self.target):
                                            try:
                                                os.makedirs(self.target)
                                            except WindowsError, e:
                                                errors[
                                                    'destination'] = 'directory not found: %s (%s)' % (
                                                        self.target,
                                                        WindowsErrorDecode(e))
                                    finally:
                                        win32wnet.WNetCancelConnection2(
                                            param_encode(
                                                unc, manager.default_encoding),
                                            0, False)
                                except Exception, e:
                                    errors[
                                        'destination'] = 'directory not found: %s (%s)' % (
                                            self.target, WindowsErrorDecode(e))
                            else:
                                errors[
                                    'destination'] = 'directory not found: %s (%s)' % (
                                        self.target, WindowsErrorDecode(e))