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)
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
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 testAddConnection(self): localName = self.findUnusedDriveLetter() + ":" for share in self.iterConnectableShares(): share.lpLocalName = localName win32wnet.WNetAddConnection2(share) win32wnet.WNetCancelConnection2(localName, 0, 0) break
def connectWindowsShare(share, username, password): """ Connects a windows-share. @param share: Windows share in UNC path representation. @type share: C{unicode} @raise PersistenecError: raised if connection to a SMB-share failed """ if sys.platform == _WIN32_PLATFORM: components = os.path.normpath(share).split("\\") if len(components) < 3: raise PersistenceError( "Wrong file share configuration information!") else: if not os.path.exists(share): try: win32wnet.WNetAddConnection2( win32netcon.RESOURCETYPE_DISK, None, #unused_drive, share, None, username, password, 0) except pywintypes.error, error: raise PersistenceError( "Could not connect to '%s'.\nReason: %s" % (share, error[2]))
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)
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)
def testAddConnectionOld(self): localName = self.findUnusedDriveLetter() + ':' for share in self.iterConnectableShares(): win32wnet.WNetAddConnection2(share.dwType, localName, share.lpRemoteName) win32wnet.WNetCancelConnection2(localName, 0, 0) break
def mount(self): buf = self.getFreeLetter() if buf is None: Logger.warn("No drive letter available: unable to init profile") return self.mountPoint = "%s:" % (buf) try: win32wnet.WNetAddConnection2( win32netcon.RESOURCETYPE_DISK, self.mountPoint, r"\\%s\%s" % (self.profile["server"], self.profile["dir"]), None, self.profile["login"], self.profile["password"]) except Exception, err: Logger.error("Unable to mount drive") Logger.debug("WNetAddConnection2 return %s" % (err)) Logger.debug( "Unable to mount drive, '%s', try the net use command equivalent: '%s'" % (str(err), "net use %s \\\\%s\\%s %s /user:%s" % (self.mountPoint, self.profile["server"], self.profile["dir"], self.profile["password"], self.profile["login"]))) self.mountPoint = None return False
def check_inst_scripts(hostname): scripts_path = f'\\\\{hostname}\\InstScripts$' # Connect to the instrument shared network resource username = f'{hostname}\\{_get_env_var("INSTRUMENT_SCRIPTS_CREDENTIALS_USR")}' password = _get_env_var("INSTRUMENT_SCRIPTS_CREDENTIALS_PSW") try: # dwType, lpLocalName, lpRemoteName[, lpProviderName, Username, Password, flags] # noinspection PyArgumentList win32wnet.WNetAddConnection2(0, None, scripts_path, None, username, password) except PywintypesError as e: sys.stderr.write( f'Error {e.winerror} connecting to {hostname}: {e.strerror}\n') cannot_connect.append(hostname) return repo = git.Repo(path=scripts_path) if len(repo.remotes) > 1: print( f'WARNING: {hostname} has multiple remote repositories: \n{repo.git.remote("-v")}\n' ) multiple_repos.append(hostname) current_head = repo.head.commit.hexsha if current_head != remote_head: print( f'WARNING: {hostname} HEAD with commit ID "{current_head}" ' f'is different from remote master HEAD with commit ID "{remote_head}".' ) different_head.append(hostname) return hostname
def mount_share(share_path, param_username, param_password): """Uses the pywin32 library to mount a share and updates the filename""" # check if such a path has already been mounted print "Mounting the share " + share_path handle = win32wnet.WNetOpenEnum(win32netcon.RESOURCE_CONNECTED, win32netcon.RESOURCETYPE_DISK, 0, None) resources = win32wnet.WNetEnumResource(handle) is_mounted = False used_letters = "" letter = None for resource in resources: if share_path == resource.lpRemoteName and resource.lpLocalName: # found a mounted drive with the same path so we set the correct letter # lpLocalName is None when the mount does not redirect a local device # we do not want to consider such a mount is_mounted = True letter = resource.lpLocalName if resource.lpLocalName: used_letters += resource.lpLocalName # append so we can search a free letter later win32wnet.WNetCloseEnum(handle) if not is_mounted: for letter in ascii_uppercase[::-1]: if letter not in used_letters: letter += ":" break net_resource = win32wnet.NETRESOURCE() net_resource.dwType = win32netcon.RESOURCETYPE_DISK net_resource.lpLocalName = letter net_resource.lpRemoteName = share_path net_resource.lpProvider = None win32wnet.WNetAddConnection2(net_resource, param_username, param_password) print("Share successfully mounted with letter %s " % letter) return letter
def connect_drive(sharename, user=None, password=None, letter=None): """Map a drive to the given windows share, optionally using username and password""" letter = letter or get_free_drive_letter() + ':' win32wnet.WNetAddConnection2(DISK, letter, sharename, None, user, password, 0) return letter
def TestConnection(): if len(possible_shares) == 0: print "Couldn't find any potential shares to connect to" return localName = "Z:" # need better way! for share in possible_shares: print "Attempting connection of", localName, "to", share.lpRemoteName try: win32wnet.WNetAddConnection2(share.dwType, localName, share.lpRemoteName) except win32wnet.error, details: print "Couldn't connect: " + details[2] continue # Have a connection. try: fname = os.path.join(localName + "\\", os.listdir(localName + "\\")[0]) try: print "Universal name of '%s' is '%s'" % ( fname, win32wnet.WNetGetUniversalName(fname)) except win32wnet.error, details: print "Couldn't get universal name of '%s': %s" % (fname, details[2]) print "User name for this connection is", win32wnet.WNetGetUser( localName)
def registerShares(self): alreadyAuthenticatedCIFSShares = {} for (name, share) in self.parseRegistry().items(): if not self.isShareValid(share): print >> sys.stderr, "Unable to add share: %s (missing items)" % ( str(share)) continue self.shares[name] = share if "profile" in self.shares.keys(): profile = self.shares["profile"] mount_uri = self.getMountURI(profile["uri"]) if mount_uri is not None: server = None if mount_uri.startswith(r"\\"): server = mount_uri.split('\\')[2] if profile.has_key("login"): login = profile["login"] else: login = None if profile.has_key("password"): password = profile["password"] else: password = None if alreadyAuthenticatedCIFSShares.has_key(server): login = None password = None try: win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, "U:", mount_uri, None, login, password) profile["local_path"] = "U:\\Data\\" if login is not None: alreadyAuthenticatedCIFSShares[server] = (login, password) except Exception, err: cmd = "net use U: %s" % (mount_uri) if password is not None: cmd += " " + password if login is not None: cmd += " /user:"******"Unable to mount share with default URI: ", err print "Try with this command: ", cmd if self.mode == 'advanced': try: Platform.launch("VFS.exe -p U:\\", False) except: print "Failed to start VFS program"
def map_network_drive(path, drive_letter="X:", username=None, password=None, persistent=False): flag = 'win32netcon.CONNECT_UPDATE_PROFILE' if persistent else 0 win32wnet.WNetAddConnection2(DISK, drive_letter, path, None, username, password, flag)
def add(self, resource, username, password): with self.__lock: name = resource.lpRemoteName if name not in self.__resources: # https://docs.microsoft.com/en-us/windows/win32/api/winnetwk/nf-winnetwk-wnetaddconnection2a # https://mhammond.github.io/pywin32/win32wnet__WNetAddConnection2_meth.html win32wnet.WNetAddConnection2(resource, password, username, 0) self.__resources[name] += 1
def TestConnection(): if len(possible_shares) == 0: print("Couldn't find any potential shares to connect to") return localName = findUnusedDriveLetter() + ':' for share in possible_shares: print("Attempting connection of", localName, "to", share.lpRemoteName) try: win32wnet.WNetAddConnection2(share.dwType, localName, share.lpRemoteName) except win32wnet.error as details: print("Couldn't connect: " + details.strerror) continue # Have a connection. try: fname = os.path.join(localName + "\\", os.listdir(localName + "\\")[0]) try: print("Universal name of '%s' is '%s'" % (fname, win32wnet.WNetGetUniversalName(fname))) except win32wnet.error as details: print("Couldn't get universal name of '%s': %s" % (fname, details.strerror)) print("User name for this connection is", win32wnet.WNetGetUser(localName)) finally: win32wnet.WNetCancelConnection2(localName, 0, 0) # and do it again, but this time by using the more modern # NETRESOURCE way. nr = win32wnet.NETRESOURCE() nr.dwType = share.dwType nr.lpLocalName = localName nr.lpRemoteName = share.lpRemoteName win32wnet.WNetAddConnection2(nr) win32wnet.WNetCancelConnection2(localName, 0, 0) # and one more time using WNetAddConnection3 win32wnet.WNetAddConnection3(0, nr) win32wnet.WNetCancelConnection2(localName, 0, 0) # Only do the first share that succeeds. break
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
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
def connectRemoteShare(server, username, password): import win32api import win32net import win32netcon, win32wnet try: win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, 'Z:', '\\\\' + server + '\D$', None, username, password, 0) print("connection established successfully") except: print("connection not established")
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
def host_connection(host, username, password): # unc = ''.join(['\\\\', host])+"$" logger.info(" Host : {}, Username :{}, Password:{}", host, username, password) isconnected = False try: win32wnet.WNetAddConnection2(0, None, host, None, username, password) isconnected = True except Exception as err: logger.debug( " Problem with network connection and authetication: host_connection() ", err) return isconnected
def WNetAddConnect(machine_name_no_backslash): # Nothing to do if this is the current machine. if not machine_name_no_backslash: return # "machine" or "Machine" ? Arp returns "Machine". usernam, passwd = lib_credentials.GetCredentials( "Login", machine_name_no_backslash) mach_nam_with_backslash = "\\\\" + machine_name_no_backslash win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_ANY, None, mach_nam_with_backslash, None, usernam, passwd, 0)
def mapDrive(driveLetter, remotePath): netResource = win32wnet.NETRESOURCE() netResource.dwType = RESOURCETYPE_DISK netResource.lpLocalName = driveLetter netResource.lpRemoteName = remotePath try: win32wnet.WNetAddConnection2(netResource) return True except win32wnet.error, description: errMsg = "Unable to map network drive %s '%s'" % (driveLetter, description[2]) logger.error(errMsg) return False
def wnet_connect(self, host, username, password): if host == 'localhost': dest_dir = '\\archive' else: dest_dir = '\\documents' unc = ''.join(['\\\\', host]) try: win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, '',unc+dest_dir, None, username,password, 0) # PluginUtils.show_message(self, self.tr("success"), self.tr("Successfully")) except Exception, err: aa = 0
def main(): net_resource = win32wnet.NETRESOURCE() net_resource.lpRemoteName = SHARE_FULL_NAME flags = 0 # flags |= CONNECT_INTERACTIVE print("Trying to create connection to: {:s}".format(SHARE_FULL_NAME)) try: win32wnet.WNetAddConnection2(net_resource, SHARE_PWD, SHARE_USER, flags) # Connect to network except pywintypes.error as e: print(e) else: print("Success!")
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')
def wnet_connect(host, username = None, password = None): netpath = r'\\builddev.altiris.com\buildtest' 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
def mapNetworkDrive(drive, remotePath): try: gLogger.info("Mapping network drive %s to %s" % (remotePath, drive)) win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive, remotePath) gLogger.info(" Success") except win32wnet.error, details: (error_num, method_name, error_str) = details if winerror.ERROR_ALREADY_ASSIGNED == error_num: gLogger.warning("Drive letter %s already assigned!" % drive) else: gLogger.error("Error code %d (0x%x) returned by %s():" % \ (error_num, error_num, method_name)) gLogger.error(" %s" % error_str)
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