コード例 #1
0
    def start(self):
        self.path["spool"] = Config.spool
        self.path["spool.real"] = Config.spool + ".real"
        if os.path.ismount(self.path["spool"]):
            Logger.warn("Failed to start FS backend, %s is already mounted" %
                        (self.path["spool"]))
            return False

        for p in self.path:
            path = self.path[p]
            try:
                os.makedirs(path)
            except OSError, err:
                if err[0] is not errno.EEXIST:
                    Logger.exception("Failed to create spool directory: %s" %
                                     path)
                    return False

            try:
                os.lchown(path, Config.uid, Config.gid)
            except OSError:
                Logger.exception("Unable to change file owner for '%s'" % path)
                return False

            if not os.path.exists(path):
                Logger.error("Spool directory %s do not exist" % (path))
                return False
コード例 #2
0
ファイル: HTAccess.py プロジェクト: bacgroup/ovd_sources
	def save(self):
		try:
			f = file(self.path, "w")
			if len(self.groups) == 0:
				f.write("deny from all")
			else:
				f.write("<LimitExcept PUT POST DELETE MKCOL MOVE>\n")
				f.write("\trequire group")
				
				for group in self.groups:
                                	f.write(" %s_rw"%(group))
					f.write(" %s_ro"%(group))
				
				f.write("\n")
				f.write("</LimitExcept>\n")
				
				f.write("<Limit PUT POST DELETE MKCOL MOVE>\n")
				f.write("\trequire group")
				for group in self.groups:
					f.write(" %s_rw"%(group))
				f.write("\n")
				
				f.write("</Limit>\n")
			
			f.close()
		
		except IOError, err:
			Logger.exception("FS: unable to write .htaccess '%s'"%self.path)
			return False
コード例 #3
0
	def send_packet(self, path, document = None):
		if self.url is None:
			self.perform_dns_request()
		
		url = "%s%s"%(self.url, path)
		Logger.debug("SMRequest::send_packet url %s"%(url))
		
		req = urllib2.Request(url)
		req.add_header("Host", "%s:%s"%(self.host, self.port))
		
		if document is not None:
			rootNode = document.documentElement
			rootNode.setAttribute("name", str(self.name))
			req.add_header("Content-type", "text/xml; charset=UTF-8")
			req.add_data(document.toxml("UTF-8"))
		
		try:
			stream = urllib2.urlopen(req)
		except IOError:
			Logger.exception("SMRequest::send_packet path: "+path)
			return False
		except httplib.BadStatusLine:
			Logger.exception("SMRequest::send_packet path: "+path+" not receive HTTP response")
			return False
		
		return stream
コード例 #4
0
ファイル: FSBackend.py プロジェクト: bloveing/openulteo
	def update_shares(self, share, quota, toAdd):
		if self.pid is None:
			try:
				f = open(self.pidFile, "r")
				pidStr = f.readline()
				if len(pidStr) == 0:
					Logger.error("Invalid FSBackend pid: %s"%(pidStr))
					return False
				
				self.pid = int(pidStr)
			except Exception:
				Logger.exception("Failed to get FSBackend pid")
				return False
		
		try:
			# TODO use a file lock
			f = open(self.sharesFile, "rw")
			lines = f.readlines()
			out = ""
			found = False
			f.close()
			
			for line in lines:
				compo = line.split(',')
				if len(compo) != 2:
					# Check comment
					strippedLine = line.strip()
					if strippedLine.startswith("#") or strippedLine.startswith(";") or len(strippedLine) == 0:
						out += line
						continue

					Logger.error("The following line '%s' is not properly formated, removing it"%(line))
					continue
				
				if share == compo[0].strip():
					if toAdd:
						# updating entry
						out += "%s, %s\n"%(share, quota)
						found = True
					continue
				
				# we restore the entry
				out += line
			
			if not found and toAdd:
				# we append a new entry
				out += "%s, %s\n"%(share, quota)
			
			f = open(self.sharesFile, "w+")
			f.write(out)
			f.close()
			
			# force share data relaod
			os.kill(self.pid, signal.SIGHUP)
			return True
			
			
		except Exception:
			Logger.exception("Failed to add entry for the share '%s'"%share)
			return False
コード例 #5
0
ファイル: Scripts.py プロジェクト: bacgroup/ovd_sources
    def __init__(self, communicationInstance):
        self.supportedExtention = {
            "sh": "bash",
            "vbs": "vbs",
            "py": "python",
            "bat": "batch",
            "unknow": "unknow"
        }
        self.communicationInstance = communicationInstance
        self.spool = os.path.join(Config.spool_dir, "scripts")
        self.scripts = {}
        if not os.path.exists(self.spool):
            os.makedirs(self.spool)

        for scriptFile in glob.glob(os.path.join(self.spool, "*")):
            script = {}
            base = os.path.basename(scriptFile)
            scriptID, ext = os.path.splitext(base)
            try:
                f = open(scriptFile)
                script["id"] = scriptID
                script["type"] = self.ext2type(ext[1:])
                script["data"] = f.read()
                f.close()
            except Exception:
                Logger.exception("Scripts::init: Failed to parse scripts")
                continue

            self.scripts[scriptID] = script
コード例 #6
0
    def uninstall_client(self):
        if not self.succefully_initialized:
            return

        self.archive_shell_dump()

        if self.profile is not None and self.profile.hasProfile():
            if not self.profile.mount():
                Logger.warn(
                    "Unable to mount profile at uninstall_client of session " +
                    self.id)
            else:
                self.profile.copySessionStop()

                if not self.profile.umount():
                    Logger.error(
                        "Unable to umount profile at uninstall_client of session "
                        + self.id)

        try:
            shutil.rmtree(self.user_session_dir)
        except Exception:
            Logger.exception("Failed to remove spool directory '%s'" %
                             self.user_session_dir)

        self.domain.onSessionEnd()
        return True
コード例 #7
0
ファイル: Role.py プロジェクト: bloveing/openulteo
	def init(self):
		Logger.info("Gateway init")

		if version[0] != 2 or version[1] < 6 or (version[1] == 7 and version[2] in [1, 2]):
			Logger.error("Gateway:: incompatibility with current Python machine '%d.%d.%d'" % version[:3])
			return False
		
		fpem = os.path.join(Config.general.conf_dir, "gateway.pem")
		if os.path.exists(fpem):
			self.ssl_ctx = SSL.Context(SSL.SSLv23_METHOD)
			self.ssl_ctx.use_privatekey_file(fpem)
			self.ssl_ctx.use_certificate_file(fpem)
			self.ssl_ctx.load_verify_locations(fpem)
			if Config.disable_sslv2:
				self.ssl_ctx.set_options(SSL.OP_NO_SSLv2)
		else:
			Logger.error("Gateway role need a certificate (%s)" % fpem)
			return False
		
		addr = (Config.address, Config.port)
		try:
			GatewayTCPHandler.role = self
			self.server = GatewayTCPServer(addr, GatewayTCPHandler, bind_and_activate=False)
			self.server.allow_reuse_address = Config.general.server_allow_reuse_address
			
			self.server.server_bind()
			self.server.server_activate()
		except socket.error:
			Logger.exception("Gateway:: socket init")
			return False
		
		Logger.info('Gateway:: running on (%s, %d)' % addr)
		return True
コード例 #8
0
ファイル: Role.py プロジェクト: bacgroup/ovd_sources
    def purgeGroup(self):
        users = System.groupMember(Config.group)
        if users is None:
            return False

        ret = True
        for user in users:
            if user == Config.dav_user:
                continue

            Logger.debug("FileServer:: deleting user '%s'" % (user))

            u = User(user)
            u.clean()
            if u.existSomeWhere():
                Logger.error("FS: unable to del user %s" % (user))
                ret = False

        htgroup = HTGroup(Config.dav_group_file)
        htgroup.purge()

        try:
            groups = [
                g.gr_name for g in grp.getgrall()
                if g.gr_name.startswith("ovd_share_")
            ]
            for g in groups:
                System.groupDelete(g)
        except Exception:
            Logger.exception("Failed to purge groups")
            ret = False

        return ret
コード例 #9
0
ファイル: FSBackend.py プロジェクト: bloveing/openulteo
	def start(self):
		self.path["spool"] = Config.spool
		self.path["spool.real"] = Config.spool+".real"
		if os.path.ismount(self.path["spool"]):
			Logger.warn("Failed to start FS backend, %s is already mounted"%(self.path["spool"]))
			return False
		
		for p in self.path:
			path = self.path[p]
			try:
				os.makedirs(path)
			except OSError, err:
				if err[0] is not errno.EEXIST:
					Logger.exception("Failed to create spool directory: %s"%path)
					return False
			
			try:
				os.lchown(path, Config.uid, Config.gid)
			except OSError:
				Logger.exception("Unable to change file owner for '%s'"%path)
				return False

			if not os.path.exists(path):
				Logger.error("Spool directory %s do not exist"%(path))
				return False
コード例 #10
0
    def rewrite_xml(self, body):
        try:
            session = parser.XML(body)
            if session.tag.lower() != 'session':
                raise Exception("not a 'session' XML response")
        except Exception:
            Logger.exception("Gateway:: parsing XML session failed")
            return None

        session.set('mode_gateway', 'on')
        for server in session.findall('server'):
            port = Protocol.RDP

            if server.attrib.has_key("port"):
                try:
                    port = int(server.attrib["port"])
                except ValueError, err:
                    Logger.warn(
                        "Gateway:: Invalid protocol: server port attribute is not a digit (%s)"
                        % (server.attrib["port"]))

            token = self.f_ctrl.send(
                ('insert_token', (server.attrib['fqdn'], port)))
            server.set('token', token)
            del server.attrib['fqdn']
            if server.attrib.has_key("port"):
                del server.attrib["port"]
コード例 #11
0
	def process(self, func_name, *args, **kwargs):
		self.lock.acquire()
		try:
			## send message to start operation
			if self.queue_in is None:
				Logger.error('[WebApps] using not initialized SessionsRepository')
				return
				
			try:
				self.queue_in.put((func_name, args, kwargs))
			except (EOFError, socket.error):
				Logger.exception('[WebApps] error when running {0}'.format(func_name))
				return

			## wait for response
			while True:
				try:
					result = self.queue_out.get(True, 5)
				except Queue.Empty, e:
					Logger.error('[WebApps] no response from SessionsRepository')
					break
				else:
					return result
		finally:
			self.lock.release()
コード例 #12
0
ファイル: Dialog.py プロジェクト: bacgroup/ovd_sources
	def req_user_loggedin(self, request):
		try:
			document = minidom.parseString(request["data"])
			rootNode = document.documentElement
			
			if rootNode.nodeName != "user":
				raise Exception("invalid root node")
			
			if not rootNode.hasAttribute("login"):
				raise Exception("invalid root node")
			
			login = rootNode.getAttribute("login")
			
		except:
			Logger.warn("Invalid xml input !!")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
		
		try:
			ret = TS.getSessionID(login)
		except Exception:
			Logger.exception("RDP server dialog failed ... ")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "internalerror")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
		
		rootNode.setAttribute("loggedin", str((ret is not None)).lower())
		
		return self.req_answer(document)
コード例 #13
0
ファイル: Dialog.py プロジェクト: bloveing/openulteo
	def req_share_delete(self, request):
		Logger.debug("FS:dialog::delete_share")
		try:
			document = minidom.parseString(request["data"])
			roodNode = document.documentElement
			if roodNode.nodeName != "share":
				raise Exception("invalid root node")
			
			share_id = roodNode.getAttribute("id")
			if len(share_id)==0 or "/" in share_id:
				raise Exception("invalid root node")
		
		except Exception:
			Logger.exception("Invalid xml input")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
		
		if not self.role_instance.shares.has_key(share_id):
			Logger.debug("Unknown share '%s'"%(share_id))
			return self.share2xml(Share(share_id, Config.backendSpool, Config.spool))
		
		share = self.role_instance.shares[share_id]
		share.delete()
		del(self.role_instance.shares[share_id])
		
		return self.share2xml(share)
コード例 #14
0
ファイル: Role.py プロジェクト: bloveing/openulteo
	def purgeGroup(self):
		users = System.groupMember(Config.group)
		if users is None:
			return False
		
		ret = True
		for user in users:
			if user == Config.dav_user:
				continue
			
			Logger.debug("FileServer:: deleting user '%s'"%(user))
			
			u = User(user)
			u.clean()
			if u.existSomeWhere():
				Logger.error("FS: unable to del user %s"%(user))
				ret =  False
		
		htgroup = HTGroup(Config.dav_group_file)
		htgroup.purge()
		
		try:
			groups = [g.gr_name for g in grp.getgrall() if g.gr_name.startswith("ovd_share_")]
			for g in groups:
				System.groupDelete(g)
                except Exception:
                        Logger.exception("Failed to purge groups")
           		ret = False
		
		return ret
コード例 #15
0
ファイル: Dialog.py プロジェクト: bacgroup/ovd_sources
	def req_debian(self, request):
		try:
			document = minidom.parseString(request["data"])
			rootNode = document.documentElement
			if rootNode.nodeName != "debian":
				raise Exception("invalid root node")
			
			request = rootNode.getAttribute("request")
			if request not in ["upgrade", "install", "remove", "available"]:
				raise Exception("usage")
			
			packageNodes = rootNode.getElementsByTagName("package")
			if request in ["install", "remove"] and len(packageNodes)==0:
				raise Exception("usage")
			
			packages = []
			for packageNode in packageNodes:
				packages.append(packageNode.getAttribute("name"))
		
		except Exception:
			Logger.exception("Invalid xml input")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
		
		if request == "available":
			req = Apt.Request_Available()
		else:
			req = Apt.Request_Packages(request, packages)
		
		req_id = self.role_instance.apt.add(req)
		
		return self.req_answer(self.debian_request2xml(req_id, req))
コード例 #16
0
ファイル: Dialog.py プロジェクト: bacgroup/ovd_sources
	def req_debian_id(self, req):
		try:
			(rid, request) = req.split("/", 2)
			req = self.role_instance.apt.get(rid)
			if req is None:
				req = Apt.Request()
				req.status = "unknown"
				return self.req_answer(self.debian_request2xml(rid, req))
			
			if request == "status":
				return self.req_answer(self.debian_request2xml(rid, req))
			
			elif request in ["stdout", "stderr"]:
				response = {}
				response["code"] = httplib.OK
				response["Content-Type"] = "text/plain"
				response["data"] = req.getLog(request)
				return response
			
			else:
				raise Exception("usage")
			
		except Exception:
			Logger.exception("Invalid xml input")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
コード例 #17
0
    def create(self):
        userData = {}
        userData['name'] = self.name

        if self.infos.has_key("displayName"):
            userData['full_name'] = self.infos["displayName"]

        if self.infos.has_key("password"):
            userData['password'] = self.infos["password"]

        userData['flags'] = win32netcon.UF_DONT_EXPIRE_PASSWD
        userData['flags'] |= win32netcon.UF_NORMAL_ACCOUNT
        userData['flags'] |= win32netcon.UF_PASSWD_CANT_CHANGE
        userData['flags'] |= win32netcon.UF_SCRIPT

        userData['priv'] = win32netcon.USER_PRIV_USER
        userData['primary_group_id'] = ntsecuritycon.DOMAIN_GROUP_RID_USERS
        userData['password_expired'] = 0  # password never expire
        userData['acct_expires'] = win32netcon.TIMEQ_FOREVER
        if self.infos.has_key("locale"):
            userData['country_code'] = Langs.getLCID(self.infos["locale"])

        try:
            win32net.NetUserAdd(None, 3, userData)
        except Exception:
            Logger.exception("unable to create user")
            return False

        self.post_create()
        return True
コード例 #18
0
ファイル: handlers.py プロジェクト: bloveing/openulteo
	def check_ssl_certs(self):
		"""
		Validate SSL Certificates
		"""
		target_host = self.config['target'].netloc
		try:
			cert = ssl.get_server_certificate((target_host, 443))
			x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
		except:
			Logger.exception('Error when loading certificate')
			return False
		# Check if certificate has expired
		if x509.has_expired():
			Logger.debug('Certificate has expired')
			return False
		# Check if certificate is self-signed
		if x509.get_issuer() == x509.get_subject():
			Logger.debug('Certificate is self-signed')
			return False
		# Check domain
		try:
			cn = [comp[1] for comp in x509.get_subject().get_components() if comp[0] == 'CN'][0]
		except Exception:
			Logger.debug('CN not found')
			return False
		if cn.startswith('*'):
			if not re.match(r'(\w+\.)*' + cn.lstrip('*.'), target_host):
				Logger.debug('CN of the certificate does not match target host')
				return False
		elif not target_host == cn:
			Logger.debug('CN of the certificate does not match target host')
			return False
		return True
コード例 #19
0
ファイル: User.py プロジェクト: bloveing/openulteo
	def create(self):
		userData = {}
		userData['name'] = self.name
		
		if self.infos.has_key("displayName"):
			userData['full_name'] = self.infos["displayName"]
			
		if self.infos.has_key("password"):
			userData['password'] = self.infos["password"]
		
		userData['flags']  = win32netcon.UF_DONT_EXPIRE_PASSWD
		userData['flags'] |= win32netcon.UF_NORMAL_ACCOUNT
		userData['flags'] |= win32netcon.UF_PASSWD_CANT_CHANGE
		userData['flags'] |= win32netcon.UF_SCRIPT
		
		userData['priv'] = win32netcon.USER_PRIV_USER
		userData['primary_group_id'] = ntsecuritycon.DOMAIN_GROUP_RID_USERS
		userData['password_expired'] = 0 # password never expire
		userData['acct_expires'] =  win32netcon.TIMEQ_FOREVER
		if self.infos.has_key("locale"):
			userData['country_code'] =  Langs.getLCID(self.infos["locale"])
		
		try:
			win32net.NetUserAdd(None, 3, userData)
		except Exception:
			Logger.exception("unable to create user")
			return False
		
		self.post_create()
		return True
コード例 #20
0
ファイル: System.py プロジェクト: bloveing/openulteo
    def groupMember(name_):
        try:
            group = grp.getgrnam(name_)
        except KeyError:
            Logger.exception("groupMember")
            return None

        return group[3]
コード例 #21
0
ファイル: System.py プロジェクト: bacgroup/ovd_sources
    def groupDelete(name_):
        try:
            win32net.NetLocalGroupDel(None, name_)
        except win32net.error:
            Logger.exception("SessionManagement createDeleteOVD")
            return False

        return True
コード例 #22
0
ファイル: System.py プロジェクト: bacgroup/ovd_sources
    def getADDomain():
        try:
            domain = win32api.GetComputerNameEx(win32con.ComputerNameDnsDomain)
        except Exception:
            Logger.exception("System::getADDomain")
            return False

        return domain
コード例 #23
0
ファイル: System.py プロジェクト: bacgroup/ovd_sources
    def groupMember(name_):
        try:
            group = grp.getgrnam(name_)
        except KeyError:
            Logger.exception("groupMember")
            return None

        return group[3]
コード例 #24
0
ファイル: System.py プロジェクト: bacgroup/ovd_sources
 def mount_point_exist(path):
     # This function replace os.path.exists because it do not inform about error
     try:
         st = os.stat(path)
     except os.error, e:
         if e[0] != 2:
             Logger.exception("Unable to check mount point %s" % path)
         return False
コード例 #25
0
ファイル: System.py プロジェクト: bloveing/openulteo
	def mount_point_exist(path):
		# This function replace os.path.exists because it do not inform about error
		try:
			st = os.stat(path)
		except os.error, e:
			if e[0] != 2:
				Logger.exception("Unable to check mount point %s"%path)
			return False
コード例 #26
0
ファイル: System.py プロジェクト: bloveing/openulteo
	def groupDelete(name_):
		try:
			win32net.NetLocalGroupDel(None, name_)
		except win32net.error:
			Logger.exception("SessionManagement createDeleteOVD")
			return False
		
		return True
コード例 #27
0
ファイル: System.py プロジェクト: bloveing/openulteo
	def getADDomain():
		try:
			domain = win32api.GetComputerNameEx(win32con.ComputerNameDnsDomain)
		except Exception:
			Logger.exception("System::getADDomain")
			return False
			
		return domain
コード例 #28
0
ファイル: System.py プロジェクト: bacgroup/ovd_sources
    def userRemove(user_):
        try:
            win32net.NetUserDel(None, user_)

        except win32net.error:
            Logger.exception("userRemove")
            return False

        return True
コード例 #29
0
ファイル: HttpServer.py プロジェクト: bacgroup/ovd_sources
	def initialize(self):
		try:
			self.webserver = ThreadPoolingHttpServer( ("", self.tcp_port), HttpRequestHandler, 5)
		except socket.error:
			Logger.exception("Unable to initialize Communication")
			return False
		
		self.webserver.comm_instance = self
		return True
コード例 #30
0
ファイル: System.py プロジェクト: bloveing/openulteo
	def userRemove(user_):
		try:
			win32net.NetUserDel(None, user_)
		
		except win32net.error:
			Logger.exception("userRemove")
			return False
		
		return True
コード例 #31
0
ファイル: TS.py プロジェクト: bloveing/openulteo
	def disconnect(session_id):
		try:
			Logger.debug("perform_disconnect: start logoff %d"%(session_id))
			ret = win32ts.WTSDisconnectSession(None, session_id, True)
			Logger.debug("perform_disconnect: finish disconnect %d ret: %s"%(session_id, str(ret)))
		except Exception:
			Logger.exception("perform_disconnect")
			return False
		return True
コード例 #32
0
ファイル: TS.py プロジェクト: bloveing/openulteo
	def logoff(session_id):
		try:
			Logger.debug("perform_logoff: start logoff %d"%(session_id))
			ret = win32ts.WTSLogoffSession(None, session_id, True)
			Logger.debug("perform_logoff: finish logoff %d ret: %s"%(session_id, str(ret)))
		except Exception:
			Logger.exception("perform_logoff")
			return False
		return True
コード例 #33
0
    def create_session(self, session):
        Logger.info("SessionManagement::create %s for user %s" %
                    (session.id, session.user.name))

        if session.domain.manage_user():
            if System.userExist(session.user.name):
                Logger.error(
                    "unable to create session: user %s already exists" %
                    (session.user.name))
                session.end_status = Session.SESSION_END_STATUS_ERROR
                session.switch_status(Session.SESSION_STATUS_ERROR)
                return self.destroy_session(session)

            session.user.infos["groups"] = [
                self.aps_instance.ts_group_name,
                self.aps_instance.ovd_group_name
            ]

            if session.mode == "desktop":
                session.user.infos["shell"] = "OvdDesktop"
            else:
                session.user.infos["shell"] = "OvdRemoteApps"

            rr = session.user.create()
            if rr is False:
                Logger.error("unable to create session for user %s" %
                             (session.user.name))
                session.end_status = Session.SESSION_END_STATUS_ERROR
                session.switch_status(Session.SESSION_STATUS_ERROR)
                return self.destroy_session(session)

            session.user.created = True

            try:
                rr = session.install_client()
            except Exception:
                Logger.exception("Unable to initialize session %s" %
                                 session.id)
                rr = False

            if rr is False:
                Logger.error("unable to initialize session %s" % (session.id))
                session.end_status = Session.SESSION_END_STATUS_ERROR
                session.switch_status(Session.SESSION_STATUS_ERROR)
                return self.destroy_session(session)

        else:
            # will be customize by a lock system when the users will connect in RDP
            if not session.domain.onSessionCreate():
                session.end_status = Session.SESSION_END_STATUS_ERROR
                session.switch_status(Session.SESSION_STATUS_ERROR)
                return False

        session.post_install()

        session.switch_status(Session.SESSION_STATUS_INITED)
コード例 #34
0
ファイル: Role.py プロジェクト: bloveing/openulteo
	def get_enabled_usershares(self):
		p = System.execute("net usershare list")
		if p.returncode is not 0:
			Logger.error("FS: unable to 'net usershare list': %d => %s"%(p.returncode, p.stdout.read()))
			res = []
			try:
				res = os.listdir("/var/lib/samba/usershares/")
			except Exception, e:
				Logger.exception("FS: unable to list content of /var/lib/samba/usershares")
			return res
コード例 #35
0
ファイル: TS.py プロジェクト: bacgroup/ovd_sources
 def logoff(session_id):
     try:
         Logger.debug("perform_logoff: start logoff %d" % (session_id))
         ret = win32ts.WTSLogoffSession(None, session_id, True)
         Logger.debug("perform_logoff: finish logoff %d ret: %s" %
                      (session_id, str(ret)))
     except Exception:
         Logger.exception("perform_logoff")
         return False
     return True
コード例 #36
0
ファイル: TS.py プロジェクト: bacgroup/ovd_sources
 def disconnect(session_id):
     try:
         Logger.debug("perform_disconnect: start logoff %d" % (session_id))
         ret = win32ts.WTSDisconnectSession(None, session_id, True)
         Logger.debug("perform_disconnect: finish disconnect %d ret: %s" %
                      (session_id, str(ret)))
     except Exception:
         Logger.exception("perform_disconnect")
         return False
     return True
コード例 #37
0
    def unload(self, sid):
        try:
            # Unload user reg
            win32api.RegUnLoadKey(win32con.HKEY_USERS, sid)
            win32api.RegUnLoadKey(win32con.HKEY_USERS, sid + '_Classes')
        except Exception:
            Logger.exception("Unable to unload user reg")
            return False

        return True
コード例 #38
0
ファイル: User.py プロジェクト: bloveing/openulteo
	def unload(self, sid):
		try:
			# Unload user reg
			win32api.RegUnLoadKey(win32con.HKEY_USERS, sid)
			win32api.RegUnLoadKey(win32con.HKEY_USERS, sid+'_Classes')
		except Exception:
			Logger.exception("Unable to unload user reg")
			return False
		
		return True
コード例 #39
0
ファイル: Communicator.py プロジェクト: bloveing/openulteo
	def __init__(self, remote=None, communicator=None):
		Communicator.__init__(self, communicator=communicator)
		
		self.set_socket(self.make_socket())
		
		if remote is not None:
			try:
				self.connect(remote)
			except socket.error:
				Logger.exception("%s:: socket connection failed"%self.__class__.__name__)
コード例 #40
0
ファイル: Profile.py プロジェクト: bacgroup/ovd_sources
    def copySessionStop(self):
        # etre sur que le type est logoff !

        d = shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, 0, 0)
        profile_tmp_dir = os.path.join(d, "ulteo", "profile",
                                       self.session.user.name)
        profile_tmp_dir = System.local_encode(profile_tmp_dir)
        profile_filter = System.local_encode(Config.profile_filters_filename)

        d = os.path.join(self.mountPoint,
                         "conf.Windows.%s" % System.getWindowsVersionName())
        trial = 5
        while not os.path.exists(d):
            try:
                os.makedirs(d)
            except OSError:
                trial -= 1
                if trial == 0:
                    Logger.exception("Failed to create directory %s" % d)
                    return False

                time.sleep(random.randint(1, 10) / 100.0)
                Logger.debug2(
                    "conf.Windows mkdir failed (concurrent access because of more than one ApS)"
                )
                continue

        # Copy user registry
        src = os.path.join(self.session.windowsProfileDir, "NTUSER.DAT")
        dst = os.path.join(d, "NTUSER.DAT")

        if os.path.exists(src):
            try:
                win32file.CopyFile(src, dst, False)
            except:
                Logger.error("Unable to copy registry to profile")
        else:
            Logger.warn("Weird: no NTUSER.DAT in user home dir ...")

        # Copy configuration File
        if self.profile['profile_mode'] == 'standard':
            cmd = self.getRsyncMethod(Profile.toCygPath(profile_tmp_dir),
                                      Profile.toCygPath(d),
                                      Profile.toCygPath(profile_filter))
            Logger.debug("rsync cmd '%s'" % (cmd))

            p = System.execute(cmd)
            if p.returncode is not 0:
                Logger.error("Unable to copy conf to profile")
                Logger.debug(
                    "Unable to copy conf to profile, cmd '%s' return %d: %s" %
                    (cmd, p.returncode, p.stdout.read()))

        if os.path.exists(profile_tmp_dir):
            System.DeleteDirectory(profile_tmp_dir)
コード例 #41
0
ファイル: TS.py プロジェクト: bacgroup/ovd_sources
    def getSessionID(username_):
        domain_ = None
        if "@" in username_:
            (username_, domain_) = username_.split("@", 1)

        localdomain = win32api.GetComputerName()

        sessions = win32ts.WTSEnumerateSessions(None)
        session_closing = []

        for session in sessions:
            if not 0 < session["SessionId"] < 65536:
                continue

            try:
                login = win32ts.WTSQuerySessionInformation(
                    None, session["SessionId"], win32ts.WTSUserName)
                if login.lower() != username_.lower():
                    continue

                domain = win32ts.WTSQuerySessionInformation(
                    None, session["SessionId"], win32ts.WTSDomainName)
                if domain_ is not None and domain.lower() == localdomain.lower(
                ):
                    Logger.debug(
                        "Ts session %d is not from the domain user %s but from a local user"
                        % (session["SessionId"], username_))
                    continue

                elif domain_ is None and domain.lower() != localdomain.lower():
                    Logger.debug(
                        "Ts session %d is not from the local user %s but from a domain user"
                        % (session["SessionId"], username_))
                    continue

                if Config.checkShell:
                    shell = win32ts.WTSQuerySessionInformation(
                        None, session["SessionId"], win32ts.WTSInitialProgram)
                    if not os.path.basename(shell).lower().startswith("ovd"):
                        Logger.debug("Ts session %d is not relative to OVD" %
                                     (session["SessionId"]))
                        continue

            except pywintypes.error, err:
                if err[0] == 7007:  # A close operation is pending on the session.
                    session_closing.append(session)
                if err[0] == 7022:  # Session not found.
                    continue
                else:
                    Logger.exception("Unable to list session %d" %
                                     session["SessionId"])
                continue

            return session["SessionId"]
コード例 #42
0
ファイル: GPO.py プロジェクト: bloveing/openulteo
	def createGPT(self):
		try:
			f = open(self.gptFile, 'w+')
			f.write("[General]\r\n")
			f.write("%s=%s\r\n"%(GPO.GPT_KEY, GPO.GUID))
			f.write("version=65537\r\n")
			f.close()
		except Exception:
			Logger.exception("Failed to create new gpt file")
			return False
		return True
コード例 #43
0
ファイル: GPO.py プロジェクト: bacgroup/ovd_sources
 def createGPT(self):
     try:
         f = open(self.gptFile, 'w+')
         f.write("[General]\r\n")
         f.write("%s=%s\r\n" % (GPO.GPT_KEY, GPO.GUID))
         f.write("version=65537\r\n")
         f.close()
     except Exception:
         Logger.exception("Failed to create new gpt file")
         return False
     return True
コード例 #44
0
ファイル: System.py プロジェクト: bacgroup/ovd_sources
    def getRAMTotal():
        infos = win32api.GlobalMemoryStatusEx()

        try:
            total = infos["TotalPhys"] / 1024

        except Exception:
            Logger.exception("getRAMTotal")
            return 0.0

        return total
コード例 #45
0
ファイル: System.py プロジェクト: bacgroup/ovd_sources
    def getRAMTotal():
        infos = System._getMeminfo()

        try:
            total = int(infos["MemTotal"])

        except Exception:
            Logger.exception("getRAMTotal")
            return 0.0

        return total
コード例 #46
0
ファイル: System.py プロジェクト: bloveing/openulteo
	def getRAMTotal():
		infos = win32api.GlobalMemoryStatusEx()
		
		try:
			total = infos["TotalPhys"]/1024
		
		except Exception:
			Logger.exception("getRAMTotal")
			return 0.0
		
		return total
コード例 #47
0
    def __init__(self, remote=None, communicator=None):
        Communicator.__init__(self, communicator=communicator)

        self.set_socket(self.make_socket())

        if remote is not None:
            try:
                self.connect(remote)
            except socket.error:
                Logger.exception("%s:: socket connection failed" %
                                 self.__class__.__name__)
コード例 #48
0
	def run(self):
		try:
			reactor.listenTCP(self.tcp_port, self.site)
		except BindError:
			Logger.exception("Unable to bind port %d, system is going to stop"%self.tcp_port)
			self.status = AbstractCommunication.STATUS_ERROR
			return
		
		self.status = AbstractCommunication.STATUS_RUNNING
		reactor.run(installSignalHandlers=0)
		self.status = AbstractCommunication.STATUS_STOP
コード例 #49
0
ファイル: System.py プロジェクト: bloveing/openulteo
    def getRAMTotal():
        infos = System._getMeminfo()

        try:
            total = int(infos["MemTotal"])

        except Exception:
            Logger.exception("getRAMTotal")
            return 0.0

        return total
コード例 #50
0
ファイル: __init__.py プロジェクト: bloveing/openulteo
	def isSessionManagerRequest(self, request):
		buf = self.session_manager
		
		if not util.isIP(buf):
			try:
				buf = socket.gethostbyname(buf)
			except Exception:
				Logger.exception("Communication::isSessionManagerRequest: fail to get address info for '%s'"%buf)
				return False
		
		return  request["client"] == buf
コード例 #51
0
ファイル: User.py プロジェクト: bloveing/openulteo
	def getSid(self):
		#get the sid
		try:
			# We use hostname in order to be sure to add local user to the group, not the domain one
			sid, _, _ = win32security.LookupAccountName(None, self.host+"\\"+self.name)
			sid = win32security.ConvertSidToStringSid(sid)
		except Exception:
			Logger.exception("Unable to get SID")
			return None
		
		return sid
コード例 #52
0
ファイル: DomainMicrosoft.py プロジェクト: bloveing/openulteo
	def getGroupList(self, username):
		if username is None:
			return None
		
		try:
			gids = [g.gr_gid for g in grp.getgrall() if username in g.gr_mem]
			gid = pwd.getpwnam(username).pw_gid
			gids.append(grp.getgrgid(gid).gr_gid)
			return ["'%s'"%(grp.getgrgid(gid).gr_name) for gid in gids]
		except Exception:
			Logger.exception("Failed to get groups of the user %s"%username)
			return None
コード例 #53
0
ファイル: System.py プロジェクト: bloveing/openulteo
    def getCPUInfos():
        infos = System.parseProcFile("/proc/cpuinfo")

        try:
            name = infos["model name"]
            nb = int(infos["processor"]) + 1

        except Exception:
            Logger.exception("getCPUInfos")
            return (1, "Unknown")

        return (nb, name)
コード例 #54
0
ファイル: Role.py プロジェクト: bacgroup/ovd_sources
 def get_enabled_usershares(self):
     p = System.execute("net usershare list")
     if p.returncode is not 0:
         Logger.error("FS: unable to 'net usershare list': %d => %s" %
                      (p.returncode, p.stdout.read()))
         res = []
         try:
             res = os.listdir("/var/lib/samba/usershares/")
         except Exception, e:
             Logger.exception(
                 "FS: unable to list content of /var/lib/samba/usershares")
         return res
コード例 #55
0
ファイル: System.py プロジェクト: bloveing/openulteo
	def groupCreate(name_):
		try:
			data = {}
			data['name'] = name_
			data['comment'] = ''
		
			win32net.NetLocalGroupAdd(None, 1, data)
		except win32net.error:
			Logger.exception("SessionManagement createGroupOVD")
			return False
		
		return True
コード例 #56
0
    def getGroupList(self, username):
        if username is None:
            return None

        try:
            gids = [g.gr_gid for g in grp.getgrall() if username in g.gr_mem]
            gid = pwd.getpwnam(username).pw_gid
            gids.append(grp.getgrgid(gid).gr_gid)
            return ["'%s'" % (grp.getgrgid(gid).gr_name) for gid in gids]
        except Exception:
            Logger.exception("Failed to get groups of the user %s" % username)
            return None