def copyConfigToPath(self, instPath=''): if flags.imageInstall and instPath: # for image installs we only want to write out # /etc/sysconfig/network destfile = os.path.normpath(instPath + networkConfFile) if not os.path.isdir(os.path.dirname(destfile)): iutil.mkdirChain(os.path.dirname(destfile)) shutil.move("/tmp/sysconfig-network", destfile) return # /etc/sysconfig/network-scripts/ifcfg-DEVICE # /etc/sysconfig/network-scripts/keys-DEVICE # /etc/dhcp/dhclient-DEVICE.conf # TODORV: do we really don't want overwrite on live cd? for devName, device in self.netdevices.items(): self._copyFileToPath(device.path, instPath) self._copyFileToPath(device.keyfilePath, instPath) dhclientfile = os.path.join("/etc/dhcp/dhclient-%s.conf" % devName) self._copyFileToPath(dhclientfile, instPath) # /etc/sysconfig/network self._copyFileToPath(networkConfFile, instPath, overwrite=flags.livecdInstall) # /etc/resolv.conf self._copyFileToPath("/etc/resolv.conf", instPath, overwrite=flags.livecdInstall) # /etc/udev/rules.d/70-persistent-net.rules self._copyFileToPath("/etc/udev/rules.d/70-persistent-net.rules", instPath, overwrite=flags.livecdInstall)
def copyConfigToPath(self): if flags.imageInstall: # for image installs we only want to write out # /etc/sysconfig/network destfile = os.path.normpath(ROOT_PATH + networkConfFile) if not os.path.isdir(os.path.dirname(destfile)): iutil.mkdirChain(os.path.dirname(destfile)) shutil.move("/tmp/sysconfig-network", destfile) return # /etc/sysconfig/network-scripts/ifcfg-* # /etc/sysconfig/network-scripts/keys-* # we can copy all of them self._copyIfcfgFiles() # /etc/dhcp/dhclient-DEVICE.conf # TODORV: do we really don't want overwrite on live cd? for devName, device in self.netdevices.items(): dhclientfile = os.path.join("/etc/dhcp/dhclient-%s.conf" % devName) self._copyFileToPath(dhclientfile, ROOT_PATH) # /etc/sysconfig/network self._copyFileToPath(networkConfFile, ROOT_PATH, overwrite=flags.livecdInstall) # /etc/resolv.conf self._copyFileToPath("/etc/resolv.conf", ROOT_PATH, overwrite=flags.livecdInstall) # /etc/udev/rules.d/70-persistent-net.rules self._copyFileToPath("/etc/udev/rules.d/70-persistent-net.rules", ROOT_PATH, overwrite=flags.livecdInstall) self._copyFileToPath(ipv6ConfFile, ROOT_PATH, overwrite=flags.livecdInstall)
def initLog(self, id, instPath): upgrade = id.getUpgrade() if not os.path.isdir(instPath + "/root"): iutil.mkdirChain(instPath + "/root") if upgrade: logname = '/root/upgrade.log' else: logname = '/root/install.log' instLogName = instPath + logname try: shutil.rmtree (instLogName) except OSError: pass self.instLog = open(instLogName, "w+") syslogname = "%s%s.syslog" % (instPath, logname) try: shutil.rmtree (syslogname) except OSError: pass syslog.start (instPath, syslogname) if upgrade: self.modeText = _("Upgrading %s\n") else: self.modeText = _("Installing %s\n")
def mount(self, device, mountpoint, readOnly=0, bindMount=0, instroot=""): if not self.isMountable(): return iutil.mkdirChain("%s/%s" %(instroot, mountpoint)) # if flags.selinux: # log.info("Could not mount nfs filesystem with selinux context enabled.") # return anacondalog.debug("nfsFileSystem: Mounting nfs %s => %s" %(device, "%s/%s" %(instroot, mountpoint))) ComSystem.execLocalOutput("mount -t nfs -o nolock %s %s/%s" %(device, instroot, mountpoint))
def _copyFileToPath(self, file, instPath='', overwrite=False): if not os.path.isfile(file): return False destfile = os.path.join(instPath, file.lstrip('/')) if (os.path.isfile(destfile) and not overwrite): return False if not os.path.isdir(os.path.dirname(destfile)): iutil.mkdirChain(os.path.dirname(destfile)) shutil.copy(file, destfile) return True
def _initRPM(self): self.etcrpm_dir = self.instPath + "/etc/rpm" self.librpm_dir = self.instPath + "/var/lib/rpm" # Configure /etc/rpm iutil.mkdirChain(self.etcrpm_dir) # Setup /etc/rpm/platform shutil.copy("/etc/rpm/platform", self.etcrpm_dir) # Setup /etc/rpm/sysinfo/Dirnames iutil.mkdirChain(self.etcrpm_dir + "/sysinfo") fd = open(self.etcrpm_dir + "/sysinfo/Dirnames", "w") fd.write("/\n") fd.close() # Setup provides if needed # Setup /var/lib/rpm iutil.mkdirChain(self.librpm_dir) iutil.mkdirChain(self.librpm_dir + "/log") # Touch the log file fd = open(self.librpm_dir + "/log/log.0000000001", "w") fd.close() # Configure the DB_CONFIG buf = """ # ================ Environment set_data_dir . set_create_dir . set_lg_dir ./log set_tmp_dir ./tmp set_flags db_log_autoremove on # -- thread_count must be >= 8 set_thread_count 64 # ================ Logging # ================ Memory Pool set_cachesize 0 1048576 0 set_mp_mmapsize 268435456 # ================ Locking set_lk_max_locks 16384 set_lk_max_lockers 16384 set_lk_max_objects 16384 mutex_set_max 163840 # ================ Replication """ fd = open(self.librpm_dir + "/DB_CONFIG", "w") fd.write(buf) fd.close()
def createUser (self, name=None, password=None, isCrypted=False, groups=[], homedir=None, shell=None, uid=None, algo=None, lock=False, root="/mnt/sysimage", gecos=None, mkmailspool=True): childpid = os.fork() if not childpid: if not root in ["","/"]: os.chroot(root) del(os.environ["LIBUSER_CONF"]) self.admin = libuser.admin() try: if self.admin.lookupUserByName(name): os._exit(1) userEnt = self.admin.initUser(name) groupEnt = self.admin.initGroup(name) grpLst = filter(lambda grp: grp, map(lambda name: self.admin.lookupGroupByName(name), groups)) userEnt.set(libuser.GIDNUMBER, [groupEnt.get(libuser.GIDNUMBER)[0]] + map(lambda grp: grp.get(libuser.GIDNUMBER)[0], grpLst)) if not homedir: iutil.mkdirChain('/home') homedir = "/home/" + name userEnt.set(libuser.HOMEDIRECTORY, homedir) if shell: userEnt.set(libuser.LOGINSHELL, shell) if uid >= 0: userEnt.set(libuser.UIDNUMBER, uid) if gecos: userEnt.set(libuser.GECOS, gecos) self.admin.addUser(userEnt, mkmailspool=mkmailspool) self.admin.addGroup(groupEnt) if password: if isCrypted: self.admin.setpassUser(userEnt, password, True) else: self.admin.setpassUser(userEnt, cryptPassword(password, algo=algo), True) if lock: self.admin.lockUser(userEnt) # Add the user to all the groups they should be part of. grpLst.append(self.admin.lookupGroupByName(name)) for grp in grpLst: grp.add(libuser.MEMBERNAME, name) self.admin.modifyGroup(grp) os._exit(0) except Exception, e: log.critical("Error when creating new user: %s" % str(e)) os._exit(1)
def createUser(self, name=None, password=None, isCrypted=False, groups=[], homedir=None, shell=None, uid=None, algo=None, lock=False, root="/mnt/sysimage", gecos=None, mkmailspool=True): childpid = os.fork() if not childpid: if not root in ["", "/"]: os.chroot(root) del (os.environ["LIBUSER_CONF"]) self.admin = libuser.admin() try: if self.admin.lookupUserByName(name): os._exit(1) userEnt = self.admin.initUser(name) groupEnt = self.admin.initGroup(name) grpLst = filter( lambda grp: grp, map(lambda name: self.admin.lookupGroupByName(name), groups)) userEnt.set( libuser.GIDNUMBER, [groupEnt.get(libuser.GIDNUMBER)[0]] + map(lambda grp: grp.get(libuser.GIDNUMBER)[0], grpLst)) if not homedir: iutil.mkdirChain('/home') homedir = "/home/" + name userEnt.set(libuser.HOMEDIRECTORY, homedir) if shell: userEnt.set(libuser.LOGINSHELL, shell) if uid >= 0: userEnt.set(libuser.UIDNUMBER, uid) if gecos: userEnt.set(libuser.GECOS, gecos) self.admin.addUser(userEnt, mkmailspool=mkmailspool) self.admin.addGroup(groupEnt) if password: if isCrypted: self.admin.setpassUser(userEnt, password, True) else: self.admin.setpassUser( userEnt, cryptPassword(password, algo=algo), True) if lock: self.admin.lockUser(userEnt) # Add the user to all the groups they should be part of. grpLst.append(self.admin.lookupGroupByName(name)) for grp in grpLst: grp.add(libuser.MEMBERNAME, name) self.admin.modifyGroup(grp) os._exit(0) except Exception, e: log.critical("Error when creating new user: %s" % str(e)) os._exit(1)
def write(self, instPath='', anaconda=None, devices=None): # If the hostname was not looked up, but typed in by the user, # domain might not be computed, so do it now. domainname = None if "." in self.hostname: fqdn = self.hostname else: fqdn = socket.getfqdn(self.hostname) if fqdn in [ "localhost.localdomain", "localhost", "localhost6.localdomain6", "localhost6", self.hostname ] or "." not in fqdn: fqdn = None if fqdn: domainname = fqdn.split('.', 1)[1] if domainname in ["localdomain", "localdomain6"]: domainname = None else: domainname = None if self.domains == ["localdomain"] or not self.domains: if domainname: self.domains = [domainname] # /etc/udev/rules.d/70-persistent-net.rules rules = "/etc/udev/rules.d/70-persistent-net.rules" destRules = instPath + rules if (not instPath) or (not os.path.isfile(destRules)) or \ flags.livecdInstall: if not os.path.isdir("%s/etc/udev/rules.d" % (instPath, )): iutil.mkdirChain("%s/etc/udev/rules.d" % (instPath, )) if os.path.isfile(rules) and rules != destRules: shutil.copy(rules, destRules) else: f = open(destRules, "w") f.write(""" # This file was automatically generated by the /lib/udev/write_net_rules # program run by the persistent-net-generator.rules rules file. # # You can modify it, as long as you keep each rule on a single line. """) for dev in self.netdevices.values(): addr = dev.get("HWADDR") if not addr: continue devname = dev.get("DEVICE") basename = devname while basename != "" and basename[-1] in string.digits: basename = basename[:-1] # rules are case senstive for address. Lame. addr = addr.lower() s = "" if len(dev.get("DESC")) > 0: s = "# %s (rule written by anaconda)\n" % ( dev.get("DESC"), ) else: s = "# %s (rule written by anaconda)\n" % (devname, ) s = s + 'SUBSYSTEM==\"net\", ACTION==\"add\", DRIVERS=="?*", ATTR{address}=="%s", ATTR{type}=="1", KERNEL=="%s*", NAME="%s"\n' % ( addr, basename, devname, ) f.write(s) f.close() hostname = self.hostname if not self.hostname: hostname = "sabayon" # systemd uses /etc/hostname with open(instPath + "/etc/hostname", "w") as f: f.write(hostname) f.write("\n") f.flush() # samba smb_cfg = instPath + "/etc/samba/smb.conf" if os.path.isfile(smb_cfg): g = open(smb_cfg, "r") smb_conf = g.readlines() g = open(smb_cfg, "w") for line in smb_conf: if (line.find("netbios name = ") != -1) and (not line.strip().startswith("#")): line = " netbios name = %s\n" % (self.hostname, ) g.write(line) g.flush() g.close() # /etc/hosts host_file = instPath + "/etc/hosts" host_data = [] if os.path.isfile(host_file) and os.access(host_file, os.R_OK): f = open(host_file, "r") host_data = [x.strip() for x in f.readlines()] f.close() f = open(host_file, "w") found = False for line in host_data: if line.startswith("127.0.0.1"): if self.hostname not in line.split(): line += " %s" % (self.hostname, ) found = True f.write(line + "\n") if not found: f.write("127.0.0.1\t\t%s\n" % (self.hostname, )) f.flush() f.close() log.info("hostname set to = %s" % (self.hostname, )) # dhclient.conf -> force NetworkManager to not change hostname dh_conf = instPath + "/etc/dhcp/dhclient.conf" if os.path.isfile(dh_conf): f = open(dh_conf, "w") f.write('send host-name "' + self.hostname + '";\n') f.write('supersede host-name "' + self.hostname + '";\n') f.flush() f.close()
def write(self, instPath=None, devices=None): # import pdb;pdb.set_trace() if devices is None: devices = self.netdevices.values() if len(devices) == 0: return # make sure the directory exists if not os.path.isdir("%s/etc/sysconfig/network-scripts" % (instPath,)): iutil.mkdirChain("%s/etc/sysconfig/network-scripts" % (instPath,)) # /etc/sysconfig/network-scripts/ifcfg-* useIPv6 = "no" # for dev in self.netdevices.values(): for dev in devices: device = dev.get("device") fn = "%s/etc/sysconfig/network-scripts/ifcfg-%s" % (instPath, device) f = open(fn, "w") os.chmod(fn, 0644) if len(dev.get("DESC")) > 0: f.write("# %s\n" % (dev.get("DESC"),)) # if bootproto is dhcp, unset any static settings (#218489) if dev.get("BOOTPROTO").lower() in ["dhcp", "ibft"]: dev.unset("IPADDR") dev.unset("NETMASK") dev.unset("GATEWAY") # handle IPv6 settings correctly for the ifcfg file ipv6addr = dev.get("IPV6ADDR").lower() ipv6prefix = dev.get("IPV6PREFIX").lower() dev.unset("IPV6ADDR") dev.unset("IPV6PREFIX") if ipv6addr == "dhcp": dev.set(("IPV6INIT", "yes")) elif ipv6addr != "" and ipv6addr is not None: dev.set(("IPV6INIT", "yes")) if ipv6prefix != "" and ipv6prefix is not None: dev.set(("IPV6ADDR", ipv6addr + "/" + ipv6prefix)) else: dev.set(("IPV6ADDR", ipv6addr)) if dev.get("IPV6_AUTOCONF").lower() == "yes": dev.set(("IPV6INIT", "yes")) f.write(str(dev)) # write out the hostname as DHCP_HOSTNAME if given (#81613) if dev.get("bootproto").lower() == "dhcp" and self.hostname and self.overrideDHCPhostname: f.write("DHCP_HOSTNAME=%s\n" % (self.hostname,)) if dev.get("dhcpclass"): f.write("DHCP_CLASSID=%s\n" % dev.get("dhcpclass")) if dev.get("MTU") and dev.get("MTU") != 0: f.write("MTU=%s\n" % dev.get("MTU")) f.close() if dev.get("key"): fn = "%s/etc/sysconfig/network-scripts/keys-%s" % (instPath, device) f = open(fn, "w") os.chmod(fn, 0600) f.write("KEY=%s\n" % dev.get("key")) f.close() if dev.get("useIPv6"): useIPv6 = "no" # for dev in self.netdevices.values():#================================== # device = dev.get("device") # fn = "%s/etc/sysconfig/network-scripts/ifcfg-%s" % (instPath,device for dev in self.netdevices.values(): device = dev.get("device") dv = str(dev) dv_ls = dv.split("\n") dv_ll = "" for i in range(0, len(dv_ls)): if "HWADDR" in dv_ls[i]: dv_ll = dv_ls[i] fn = "%s/etc/sysconfig/network-scripts/ifcfg-%s" % (instPath, device) f = open(fn) dh_num = 0 while True: line = f.readline() if len(line) == 0: break if "dhcp" in line: dh_num = 1 break f.close() if dh_num == 1: conf = "DEVICE=%s\nTYPE=Ethernet\nONBOOT=yes\n%s\nBOOTPROTO=none\nUSERCTL=no\n" % (device, dv_ll) f = open(fn, "w") os.chmod(fn, 0644) if len(dev.get("DESC")) > 0: f.write("# %s\n" % (dev.get("DESC"),)) f.write(conf) f.close() for dev in self.netdevices.values(): device = dev.get("device") dv = str(dev) dv_ls = dv.split("\n") dv_ll = "" for i in range(0, len(dv_ls)): if "HWADDR" in dv_ls[i]: dv_ll = dv_ls[i] # =============================================================== # write hostname file # f = file("%s/hostname" %(instPath) ,"w") # f.write("%s %s\n127.0.0.1 localhost.localdomain localhost\n::1 localhost6.localdomain6 localhost6" %(self.ipv4_addr,self.newHostname)) # f.close() # ========================================================== # /etc/sysconfig/network f = open(instPath + "/etc/sysconfig/network", "w") f.write("NETWORKING=yes\n") f.write("NETWORKING_IPV6=%s\n" % (useIPv6,)) f.write("HOSTNAME=") # use instclass hostname if set(kickstart) to override if self.hostname: f.write(self.hostname + "\n") else: f.write("localhost\n") if self.gateway: f.write("GATEWAY=%s\n" % (self.gateway,)) f.close() # /etc/hosts f = open(instPath + "/etc/hosts", "w") localline = "" log.info("self.hostname = %s", self.hostname) ip = self.lookupHostname() # If the hostname is not resolvable, tie it to 127.0.0.1 if not ip and self.hostname != "localhost": localline += self.hostname + " " l = string.split(self.hostname, ".") if len(l) > 1: localline += l[0] + " " localline += "localhost localhost\n" f.write("# Do not remove the following line, or various programs\n") f.write("# that require network functionality will fail.\n") f.write("127.0.0.1\t\t" + localline) f.write("::1\t\tlocalhost6.localdomain6 localhost6\n") if ip: nameline = "%s\t\t%s" % (ip, self.hostname) n = string.split(self.hostname, ".") if len(n) > 1: nameline = nameline + " " + n[0] f.write("%s\n" % (nameline,)) # If the hostname was not looked up, but typed in by the user, # domain might not be computed, so do it now. if self.domains == ["localdomain"] or not self.domains: if "." in self.hostname: # chop off everything before the leading '.' domain = self.hostname[(string.find(self.hostname, ".") + 1) :] self.domains = [domain] # /etc/resolv.conf f = open(instPath + "/etc/resolv.conf", "w") # if self.domains != ['localdomain'] and self.domains: # f.write("search %s\n" % (string.joinfields(self.domains, ' '),)) for ns in self.nameservers(): if ns: f.write("nameserver %s\n" % (ns,)) f.close()
anaconda.platform = platform.getPlatform(anaconda) if not iutil.isS390() and os.access("/dev/tty3", os.W_OK): anaconda_log.logger.addFileHandler ("/dev/tty3", log) warnings.showwarning = AnacondaShowWarning iutil.setup_translations(gettext) # reset python's default SIGINT handler signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGSEGV, isys.handleSegv) setupEnvironment() # make sure we have /var/log soon, some programs fail to start without it iutil.mkdirChain("/var/log") pidfile = open("/var/run/anaconda.pid", "w") pidfile.write("%s\n" % (os.getpid(),)) del pidfile # add our own additional signal handlers signal.signal(signal.SIGHUP, startDebugger) # we need to do this really early so we make sure its done before rpm # is imported iutil.writeRpmPlatform() extraModules = [] # XXX: this would be better as a callback graphical_failed = 0 instClass = None # the install class to use vncS = vnc.VncServer() # The vnc Server object.
def mount(self, *args, **kwargs): """ Mount this filesystem. Arguments: None Keyword Arguments: options -- mount options (overrides all other option strings) chroot -- prefix to apply to mountpoint mountpoint -- mountpoint (overrides self.mountpoint) """ options = kwargs.get("options", "") chroot = kwargs.get("chroot", "/") mountpoint = kwargs.get("mountpoint") if not self.exists: raise FSError("filesystem has not been created") if not mountpoint: mountpoint = self.mountpoint if not mountpoint: raise FSError("no mountpoint given") if self.status: return if not isinstance(self, NoDevFS) and not os.path.exists(self.device): raise FSError("device %s does not exist" % self.device) # XXX os.path.join is FUBAR: # # os.path.join("/mnt/foo", "/") -> "/" # #mountpoint = os.path.join(chroot, mountpoint) chrootedMountpoint = os.path.normpath("%s/%s" % (chroot, mountpoint)) iutil.mkdirChain(chrootedMountpoint) if flags.selinux: ret = isys.resetFileContext(mountpoint, chroot) log.info("set SELinux context for mountpoint %s to %s" \ % (mountpoint, ret)) # passed in options override default options if not options or not isinstance(options, str): options = self.options try: rc = isys.mount(self.device, chrootedMountpoint, fstype=self.mountType, options=options, bindMount=isinstance(self, BindFS)) except Exception as e: raise FSError("mount failed: %s" % e) if rc: raise FSError("mount failed: %s" % rc) if flags.selinux and "ro" not in options.split(","): ret = isys.resetFileContext(mountpoint, chroot) log.info("set SELinux context for newly mounted filesystem " "root at %s to %s" % (mountpoint, ret)) isys.setFileContext("%s/lost+found" % mountpoint, lost_and_found_context, chroot) self._mountpoint = chrootedMountpoint
def mount(self, *args, **kwargs): """ Mount this filesystem. Arguments: None Keyword Arguments: options -- mount options (overrides all other option strings) chroot -- prefix to apply to mountpoint mountpoint -- mountpoint (overrides self.mountpoint) """ options = kwargs.get("options", "") chroot = kwargs.get("chroot", "/") mountpoint = kwargs.get("mountpoint") if not self.exists: raise FSError("filesystem has not been created") if not mountpoint: mountpoint = self.mountpoint if not mountpoint: raise FSError("no mountpoint given") if self.status: return if not isinstance(self, NoDevFS) and not os.path.exists(self.device): raise FSError("device %s does not exist" % self.device) # XXX os.path.join is FUBAR: # # os.path.join("/mnt/foo", "/") -> "/" # #mountpoint = os.path.join(chroot, mountpoint) chrootedMountpoint = os.path.normpath("%s/%s" % (chroot, mountpoint)) iutil.mkdirChain(chrootedMountpoint) if flags.selinux: ret = isys.resetFileContext(mountpoint, chroot) log.info("set SELinux context for mountpoint %s to %s" \ % (mountpoint, ret)) # passed in options override default options if not options or not isinstance(options, str): options = self.options try: rc = isys.mount(self.device, chrootedMountpoint, fstype=self.mountType, options=options, bindMount=isinstance(self, BindFS)) except Exception as e: raise FSError("mount failed: %s" % e) if rc: raise FSError("mount failed: %s" % rc) if flags.selinux: ret = isys.resetFileContext(mountpoint, chroot) log.info("set SELinux context for newly mounted filesystem " "root at %s to %s" %(mountpoint, ret)) isys.setFileContext("%s/lost+found" % mountpoint, lost_and_found_context, chroot) self._mountpoint = chrootedMountpoint
def write(self, instPath): # make sure the directory exists if not os.path.isdir("%s/etc/sysconfig/network-scripts" % (instPath, )): iutil.mkdirChain("%s/etc/sysconfig/network-scripts" % (instPath, )) # /etc/sysconfig/network-scripts/ifcfg-* useIPv6 = "no" for dev in self.netdevices.values(): device = dev.get("device") fn = "%s/etc/sysconfig/network-scripts/ifcfg-%s" % (instPath, device) f = open(fn, "w") os.chmod(fn, 0644) if len(dev.get("DESC")) > 0: f.write("# %s\n" % (dev.get("DESC"), )) # if bootproto is dhcp, unset any static settings (#218489) if dev.get('BOOTPROTO').lower() in ['dhcp', 'ibft']: dev.unset('IPADDR') dev.unset('NETMASK') dev.unset('GATEWAY') # handle IPv6 settings correctly for the ifcfg file ipv6addr = dev.get('IPV6ADDR').lower() ipv6prefix = dev.get('IPV6PREFIX').lower() dev.unset('IPV6ADDR') dev.unset('IPV6PREFIX') if ipv6addr == 'dhcp': dev.set(('IPV6INIT', 'yes')) elif ipv6addr != '' and ipv6addr is not None: dev.set(('IPV6INIT', 'yes')) if ipv6prefix != '' and ipv6prefix is not None: dev.set(('IPV6ADDR', ipv6addr + '/' + ipv6prefix)) else: dev.set(('IPV6ADDR', ipv6addr)) if dev.get('IPV6_AUTOCONF').lower() == 'yes': dev.set(('IPV6INIT', 'yes')) f.write(str(dev)) # write out the hostname as DHCP_HOSTNAME if given (#81613) if (dev.get('bootproto').lower() == 'dhcp' and self.hostname and self.overrideDHCPhostname): f.write("DHCP_HOSTNAME=%s\n" % (self.hostname, )) if dev.get('dhcpclass'): f.write("DHCP_CLASSID=%s\n" % dev.get('dhcpclass')) if dev.get('MTU') and dev.get('MTU') != 0: f.write("MTU=%s\n" % dev.get('MTU')) f.close() if dev.get("key"): fn = "%s/etc/sysconfig/network-scripts/keys-%s" % (instPath, device) f = open(fn, "w") os.chmod(fn, 0600) f.write("KEY=%s\n" % dev.get('key')) f.close() if dev.get("useIPv6"): useIPv6 = "yes" # /etc/sysconfig/network f = open(instPath + "/etc/sysconfig/network", "w") f.write("NETWORKING=yes\n") f.write("NETWORKING_IPV6=%s\n" % (useIPv6, )) f.write("HOSTNAME=") # use instclass hostname if set(kickstart) to override if self.hostname: f.write(self.hostname + "\n") else: f.write("localhost.localdomain\n") if self.gateway: f.write("GATEWAY=%s\n" % (self.gateway, )) f.close() # /etc/hosts f = open(instPath + "/etc/hosts", "w") localline = "" log.info("self.hostname = %s", self.hostname) ip = self.lookupHostname() # If the hostname is not resolvable, tie it to 127.0.0.1 if not ip and self.hostname != "localhost.localdomain": localline += self.hostname + " " l = string.split(self.hostname, ".") if len(l) > 1: localline += l[0] + " " localline += "localhost.localdomain localhost\n" f.write("# Do not remove the following line, or various programs\n") f.write("# that require network functionality will fail.\n") f.write("127.0.0.1\t\t" + localline) f.write("::1\t\tlocalhost6.localdomain6 localhost6\n") if ip: nameline = "%s\t\t%s" % (ip, self.hostname) n = string.split(self.hostname, ".") if len(n) > 1: nameline = nameline + " " + n[0] f.write("%s\n" % (nameline, )) # If the hostname was not looked up, but typed in by the user, # domain might not be computed, so do it now. if self.domains == ["localdomain"] or not self.domains: if '.' in self.hostname: # chop off everything before the leading '.' domain = self.hostname[(string.find(self.hostname, '.') + 1):] self.domains = [domain] # /etc/resolv.conf f = open(instPath + "/etc/resolv.conf", "w") if self.domains != ['localdomain'] and self.domains: f.write("search %s\n" % (string.joinfields(self.domains, ' '), )) for ns in self.nameservers(): if ns: f.write("nameserver %s\n" % (ns, )) f.close() # /etc/modprobe.conf if useIPv6 == "no": iutil.mkdirChain(instPath + "/etc") f = open(instPath + "/etc/modprobe.conf", "a") f.write("alias net-pf-10 off\n") f.write("alias ipv6 off\n") f.write("options ipv6 disable=1\n") f.close()
def write(self, instPath=None, devices=None): # import pdb;pdb.set_trace() if devices is None: devices = self.netdevices.values() if len(devices) == 0: return # make sure the directory exists if not os.path.isdir("%s/etc/sysconfig/network-scripts" %(instPath,)): iutil.mkdirChain("%s/etc/sysconfig/network-scripts" %(instPath,)) # /etc/sysconfig/network-scripts/ifcfg-* useIPv6 = "no" # for dev in self.netdevices.values(): for dev in devices: device = dev.get("device") fn = "%s/etc/sysconfig/network-scripts/ifcfg-%s" % (instPath, device) f = open(fn, "w") os.chmod(fn, 0644) if len(dev.get("DESC")) > 0: f.write("# %s\n" % (dev.get("DESC"),)) # if bootproto is dhcp, unset any static settings (#218489) if dev.get('BOOTPROTO').lower() in ['dhcp', 'ibft']: dev.unset('IPADDR') dev.unset('NETMASK') dev.unset('GATEWAY') # handle IPv6 settings correctly for the ifcfg file ipv6addr = dev.get('IPV6ADDR').lower() ipv6prefix = dev.get('IPV6PREFIX').lower() dev.unset('IPV6ADDR') dev.unset('IPV6PREFIX') if ipv6addr == 'dhcp': dev.set(('IPV6INIT', 'yes')) elif ipv6addr != '' and ipv6addr is not None: dev.set(('IPV6INIT', 'yes')) if ipv6prefix != '' and ipv6prefix is not None: dev.set(('IPV6ADDR', ipv6addr + '/' + ipv6prefix)) else: dev.set(('IPV6ADDR', ipv6addr)) if dev.get('IPV6_AUTOCONF').lower() == 'yes': dev.set(('IPV6INIT', 'yes')) f.write(str(dev)) # write out the hostname as DHCP_HOSTNAME if given (#81613) if (dev.get('bootproto').lower() == 'dhcp' and self.hostname and self.overrideDHCPhostname): f.write("DHCP_HOSTNAME=%s\n" %(self.hostname,)) if dev.get('dhcpclass'): f.write("DHCP_CLASSID=%s\n" % dev.get('dhcpclass')) if dev.get('MTU') and dev.get('MTU') != 0: f.write("MTU=%s\n" % dev.get('MTU')) f.close() if dev.get("key"): fn = "%s/etc/sysconfig/network-scripts/keys-%s" % (instPath, device) f = open(fn, "w") os.chmod(fn, 0600) f.write("KEY=%s\n" % dev.get('key')) f.close() if dev.get("useIPv6"): useIPv6 = "no" # for dev in self.netdevices.values():#================================== # device = dev.get("device") # fn = "%s/etc/sysconfig/network-scripts/ifcfg-%s" % (instPath,device for dev in self.netdevices.values(): device = dev.get("device") dv = str(dev) dv_ls = dv.split("\n") dv_ll = "" for i in range(0,len(dv_ls)): if "HWADDR" in dv_ls[i]: dv_ll = dv_ls[i] fn = "%s/etc/sysconfig/network-scripts/ifcfg-%s"%(instPath,device) f = open(fn) dh_num = 0 while True: line = f.readline() if len(line) == 0: break if "dhcp" in line: dh_num = 1 break f.close() if dh_num == 1: conf = "DEVICE=%s\nTYPE=Ethernet\nONBOOT=yes\n%s\nBOOTPROTO=none\nUSERCTL=no\n" % (device, dv_ll) f = open(fn, "w") os.chmod(fn, 0644) if len(dev.get("DESC")) > 0: f.write("# %s\n" % (dev.get("DESC"),)) f.write(conf) f.close() for dev in self.netdevices.values(): device = dev.get("device") dv = str(dev) dv_ls = dv.split("\n") dv_ll = "" for i in range(0,len(dv_ls)): if "HWADDR" in dv_ls[i]: dv_ll = dv_ls[i] # dv_device_ls = dv_ls[0].split("=") # dv_device = dv_device_ls[1] if device in self.dve_dvelist: # for device in self.dve_dvelist: ###################### fn = "%s/etc/sysconfig/network-scripts/ifcfg-%s" % (instPath,device) if len(self.dve_dvelist) > 1: conf = "DEVICE=%s\nTYPE=Ethernet\nUSERCTL=no\n%s\nONBOOT=yes\nMASTER=bond0\nSLAVE=yes\nBOOTPROTO=none\n"%(device, dv_ll) else: conf = "DEVICE=%s\nTYPE=Ethernet\nUSERCTL=no\n%s\nONBOOT=yes\nBOOTPROTO=none\nBRIDGE=switch0\n"%(device, dv_ll) f = open(fn, "w") os.chmod(fn, 0644) if len(dev.get("DESC")) > 0: f.write("# %s\n" % (dev.get("DESC"),)) f.write(conf) f.close() if len(self.dve_dvelist) > 1: fn = "%s/etc/sysconfig/network-scripts/ifcfg-bond0"%instPath conf = "DEVICE=bond0\nTYPE=Ethernet\nONBOOT=yes\nBOOTPROTO=none\nUSERCTL=no\nBRIDGE=switch0\n" f = open(fn, "w") os.chmod(fn, 0644) if len(dev.get("DESC")) > 0: f.write("# %s\n" % (dev.get("DESC"),)) f.write(conf) f.close() fn = "%s/etc/modprobe.d/bond.conf"%instPath strs = "alias bond0 bonding\noptions bond0 mode=active-backup miimon=100\n" f = open(fn, "w") os.chmod(fn, 0644) f.write(strs) f.close() if len(self.dve_dvelist) > 0: fn = "%s/etc/sysconfig/network-scripts/ifcfg-switch0"%instPath IPADDR = self.br0_ip#"192.168.1.50"#################### NETMASK = self.br0_pr#"255.255.255.0"################## if NETMASK == "24": NETMASK = "255.255.255.0" if not self.r_button_dhcp: if len(IPADDR) > 0 and len(NETMASK) > 0: ir = IPADDR.split(".") nk = NETMASK.split(".") network = [] for i in range(0,len(ir)): network.append(str(int(ir[i])&int(nk[i]))) NETWORK = ".".join(network) for i in range(0, len(ir)): if int(nk[i]) > 0: nk[i] = "0" else: nk[i] = "255" bt = [] for i in range(0, len(ir)): bt.append(str(int(nk[i])|int(network[i]))) BROADCAST = ".".join(bt) if self.gateway: gateway_l = "GATEWAY=%s"%self.gateway else: gateway_l = "" conf = "DEVICE=switch0\nIPADDR=%s\nNETMASK=%s\nNETWORK=%s\nBROADCAST=%s\nONBOOT=yes\nBOOTPROTO=static\nUSERCTL=no\n%s\n"%(IPADDR, NETMASK, NETWORK, BROADCAST, gateway_l) else: conf = "DEVICE=switch0\nONBOOT=yes\nBOOTPROTO=dhcp\nUSERCTL=no\n" else: conf = "DEVICE=switch0\nONBOOT=yes\nBOOTPROTO=dhcp\nUSERCTL=no\n" f = open(fn, "w") os.chmod(fn, 0644) if len(dev.get("DESC")) > 0: f.write("# %s\n" % (dev.get("DESC"),)) f.write(conf) f.close() #=============================================================== # write hostname file #f = file("%s/hostname" %(instPath) ,"w") #f.write("%s %s\n127.0.0.1 localhost.localdomain localhost\n::1 localhost6.localdomain6 localhost6" %(self.ipv4_addr,self.newHostname)) #f.close() #========================================================== # /etc/sysconfig/network f = open(instPath + "/etc/sysconfig/network", "w") f.write("NETWORKING=yes\n") f.write("NETWORKING_IPV6=%s\n" % (useIPv6,)) f.write("HOSTNAME=") # use instclass hostname if set(kickstart) to override if self.hostname: f.write(self.hostname + "\n") else: f.write("localhost\n") if self.gateway: f.write("GATEWAY=%s\n" % (self.gateway,)) f.close() # /etc/hosts f = open(instPath + "/etc/hosts", "w") localline = "" log.info("self.hostname = %s", self.hostname) ip = self.lookupHostname() # If the hostname is not resolvable, tie it to 127.0.0.1 if not ip and self.hostname != "localhost": localline += self.hostname + " " l = string.split(self.hostname, ".") if len(l) > 1: localline += l[0] + " " localline += "localhost localhost\n" f.write("# Do not remove the following line, or various programs\n") f.write("# that require network functionality will fail.\n") f.write("127.0.0.1\t\t" + localline) f.write("::1\t\tlocalhost6.localdomain6 localhost6\n") if ip: nameline = "%s\t\t%s" % (ip, self.hostname) n = string.split(self.hostname, ".") if len(n) > 1: nameline = nameline + " " + n[0] f.write("%s\n" %(nameline,)) # If the hostname was not looked up, but typed in by the user, # domain might not be computed, so do it now. if self.domains == ["localdomain"] or not self.domains: if '.' in self.hostname: # chop off everything before the leading '.' domain = self.hostname[(string.find(self.hostname, '.') + 1):] self.domains = [domain] # /etc/resolv.conf f = open(instPath + "/etc/resolv.conf", "w") #if self.domains != ['localdomain'] and self.domains: # f.write("search %s\n" % (string.joinfields(self.domains, ' '),)) for ns in self.nameservers(): if ns: f.write("nameserver %s\n" % (ns,)) f.close()
anaconda.platform = platform.getPlatform(anaconda) if not iutil.isS390() and os.access("/dev/tty3", os.W_OK): anaconda_log.logger.addFileHandler("/dev/tty3", log) warnings.showwarning = AnacondaShowWarning iutil.setup_translations(gettext) # reset python's default SIGINT handler signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGSEGV, isys.handleSegv) setupEnvironment() # make sure we have /var/log soon, some programs fail to start without it iutil.mkdirChain("/var/log") pidfile = open("/var/run/anaconda.pid", "w") pidfile.write("%s\n" % (os.getpid(), )) del pidfile # add our own additional signal handlers signal.signal(signal.SIGHUP, startDebugger) # we need to do this really early so we make sure its done before rpm # is imported iutil.writeRpmPlatform() extraModules = [] # XXX: this would be better as a callback graphical_failed = 0 instClass = None # the install class to use vncS = vnc.VncServer() # The vnc Server object.
def write(self, instPath): # make sure the directory exists if not os.path.isdir("%s/etc/sysconfig/network-scripts" %(instPath,)): iutil.mkdirChain("%s/etc/sysconfig/network-scripts" %(instPath,)) # /etc/sysconfig/network-scripts/ifcfg-* useIPv6 = "no" for dev in self.netdevices.values(): device = dev.get("device") fn = "%s/etc/sysconfig/network-scripts/ifcfg-%s" % (instPath, device) f = open(fn, "w") os.chmod(fn, 0644) if len(dev.get("DESC")) > 0: f.write("# %s\n" % (dev.get("DESC"),)) # if bootproto is dhcp, unset any static settings (#218489) if dev.get('BOOTPROTO').lower() in ['dhcp', 'ibft']: dev.unset('IPADDR') dev.unset('NETMASK') dev.unset('GATEWAY') # handle IPv6 settings correctly for the ifcfg file ipv6addr = dev.get('IPV6ADDR').lower() ipv6prefix = dev.get('IPV6PREFIX').lower() dev.unset('IPV6ADDR') dev.unset('IPV6PREFIX') if ipv6addr == 'dhcp': dev.set(('IPV6INIT', 'yes')) elif ipv6addr != '' and ipv6addr is not None: dev.set(('IPV6INIT', 'yes')) if ipv6prefix != '' and ipv6prefix is not None: dev.set(('IPV6ADDR', ipv6addr + '/' + ipv6prefix)) else: dev.set(('IPV6ADDR', ipv6addr)) if dev.get('IPV6_AUTOCONF').lower() == 'yes': dev.set(('IPV6INIT', 'yes')) f.write(str(dev)) # write out the hostname as DHCP_HOSTNAME if given (#81613) if (dev.get('bootproto').lower() == 'dhcp' and self.hostname and self.overrideDHCPhostname): f.write("DHCP_HOSTNAME=%s\n" %(self.hostname,)) if dev.get('dhcpclass'): f.write("DHCP_CLASSID=%s\n" % dev.get('dhcpclass')) if dev.get('MTU') and dev.get('MTU') != 0: f.write("MTU=%s\n" % dev.get('MTU')) f.close() if dev.get("key"): fn = "%s/etc/sysconfig/network-scripts/keys-%s" % (instPath, device) f = open(fn, "w") os.chmod(fn, 0600) f.write("KEY=%s\n" % dev.get('key')) f.close() if dev.get("useIPv6"): useIPv6 = "yes" # /etc/sysconfig/network f = open(instPath + "/etc/sysconfig/network", "w") f.write("NETWORKING=yes\n") f.write("NETWORKING_IPV6=%s\n" % (useIPv6,)) f.write("HOSTNAME=") # use instclass hostname if set(kickstart) to override if self.hostname: f.write(self.hostname + "\n") else: f.write("localhost.localdomain\n") if self.gateway: f.write("GATEWAY=%s\n" % (self.gateway,)) f.close() # /etc/hosts f = open(instPath + "/etc/hosts", "w") localline = "" log.info("self.hostname = %s", self.hostname) ip = self.lookupHostname() # If the hostname is not resolvable, tie it to 127.0.0.1 if not ip and self.hostname != "localhost.localdomain": localline += self.hostname + " " l = string.split(self.hostname, ".") if len(l) > 1: localline += l[0] + " " localline += "localhost.localdomain localhost\n" f.write("# Do not remove the following line, or various programs\n") f.write("# that require network functionality will fail.\n") f.write("127.0.0.1\t\t" + localline) f.write("::1\t\tlocalhost6.localdomain6 localhost6\n") if ip: nameline = "%s\t\t%s" % (ip, self.hostname) n = string.split(self.hostname, ".") if len(n) > 1: nameline = nameline + " " + n[0] f.write("%s\n" %(nameline,)) # If the hostname was not looked up, but typed in by the user, # domain might not be computed, so do it now. if self.domains == ["localdomain"] or not self.domains: if '.' in self.hostname: # chop off everything before the leading '.' domain = self.hostname[(string.find(self.hostname, '.') + 1):] self.domains = [domain] # /etc/resolv.conf f = open(instPath + "/etc/resolv.conf", "w") if self.domains != ['localdomain'] and self.domains: f.write("search %s\n" % (string.joinfields(self.domains, ' '),)) for ns in self.nameservers(): if ns: f.write("nameserver %s\n" % (ns,)) f.close() # /etc/modprobe.conf if useIPv6 == "no": iutil.mkdirChain(instPath + "/etc") f = open(instPath + "/etc/modprobe.conf", "a") f.write("alias net-pf-10 off\n") f.write("alias ipv6 off\n") f.write("options ipv6 disable=1\n") f.close()
def setup(self, command=None, argv=None): iutil.mkdirChain(self.smart_dir) iutil.mkdirChain(self.anaconda.backend.instPath + "/install/tmp") buf = """#!/bin/bash export PATH="${PATH}" export D="%s" export OFFLINE_ROOT="$D" export IPKG_OFFLINE_ROOT="$D" export OPKG_OFFLINE_ROOT="$D" export INTERCEPT_DIR="/" export NATIVE_ROOT="/" exec 1>>/tmp/scriptlet.log 2>&1 echo $2 $1/$3 $4 if [ $2 = "/bin/sh" ]; then $2 -x $1/$3 $4 else $2 $1/$3 $4 fi if [ $? -ne 0 ]; then if [ $4 -eq 1 ]; then mkdir -p $1/etc/rpm-postinsts num=100 while [ -e $1/etc/rpm-postinsts/${num}-* ]; do num=$((num + 1)); done name=`head -1 $1/$3 | cut -d' ' -f 2` echo "#!$2" > $1/etc/rpm-postinsts/${num}-${name} echo "# Arg: $4" >> $1/etc/rpm-postinsts/${num}-${name} cat $1/$3 >> $1/etc/rpm-postinsts/${num}-${name} chmod +x $1/etc/rpm-postinsts/${num}-${name} else echo "Error: pre/post remove scriptlet failed" fi fi """ % (self.anaconda.backend.instPath) fd = open( self.anaconda.backend.instPath + "/install/scriptlet_wrapper", "w") fd.write(buf) fd.close() os.chmod(self.anaconda.backend.instPath + "/install/scriptlet_wrapper", 0755) self.smart_ctrl = init(command, argv=argv, datadir=self.smart_dir, configfile=None, gui=False, shell=False, quiet=True, interface=None, forcelocks=False, loglevel=None) # Override the dummy interface with the locally defined one iface.object = AnacondaInterface(self.smart_ctrl, self.anaconda) initDistro(self.smart_ctrl) initPlugins() initPycurl() initPsyco() sysconf.set("rpm-root", self.anaconda.backend.instPath, soft=True) sysconf.set("rpm-extra-macros._tmppath", "/install/tmp", soft=True) sysconf.set("rpm-extra-macros._cross_scriptlet_wrapper", self.anaconda.backend.instPath + "/install/scriptlet_wrapper", soft=True) sysconf.set("rpm-nolinktos", "1") sysconf.set("rpm-noparentdirs", "1") if self.anaconda.upgrade: # Note: # This is a fix, we didn't remove the channels that we added in # previous installs, so remove them here. #FIXME: Do we need disable user's channels ? self.removeWrlLoclRepo() # Enable the installed RPM DB channels = sysconf.get("channels") or {} if 'rpmsys' not in channels: self.runSmart('channel', ['--add', 'rpmsys', 'type=rpm-sys', '-y']) iface.object.hideStatus() else: # Ensure we start with a blank channel set... sysconf.remove("channels") self.repos = AnacondaSmartRepo("anaconda-config", self.anaconda) # Setup repository for localpath in [ "/mnt/install/source", "/mnt/install/cdimage", "/mnt/install/isodir", "" ]: if os.path.isdir("%s/Packages" % localpath) and os.access( "%s/Packages/.feedpriority" % localpath, os.R_OK): f = open("%s/Packages/.feedpriority" % localpath) for line in f: (priority, feed) = line.split() if os.path.isdir("%s/Packages/%s/repodata" % (localpath, feed)): repo = SmartRepo("media_%s" % feed) repo.name = "Install Media feed for %s" % feed repo.cost = priority repo.baseurl = [ "file://%s/Packages/%s" % (localpath, feed) ] self.repos.add(repo) f.close() if self.anaconda.ksdata: for ksrepo in self.anaconda.ksdata.repo.repoList: # If no location was given, this must be a repo pre-configured # repo that we just want to enable. if not ksrepo.baseurl and not ksrepo.mirrorlist: self.repos.enable(ksrepo.name) continue anacondaBaseURLs = [ksrepo.baseurl] # smart doesn't understand nfs:// and doesn't want to. We need # to first do the mount, then translate it into a file:// that # smart does understand. # "nfs:" and "nfs://" prefixes are accepted in ks_repo --baseurl if ksrepo.baseurl and ksrepo.baseurl.startswith("nfs:"): #if not network.hasActiveNetDev() and not self.anaconda.intf.enableNetwork(): # self.anaconda.intf.messageWindow(_("No Network Available"), # _("Some of your software repositories require " # "networking, but there was an error enabling the " # "network on your system."), # type="custom", custom_icon="error", # custom_buttons=[_("_Exit installer")]) # sys.exit(1) dest = tempfile.mkdtemp("", ksrepo.name.replace(" ", ""), "/mnt") # handle "nfs://" prefix if ksrepo.baseurl[4:6] == '//': ksrepo.baseurl = ksrepo.baseurl.replace('//', '', 1) anacondaBaseURLs = [ksrepo.baseurl] try: isys.mount(ksrepo.baseurl[4:], dest, "nfs") except Exception as e: log.error("error mounting NFS repo: %s" % e) ksrepo.baseurl = "file://%s" % dest repo = SmartRepo(ksrepo.name) repo.mirrorlist = ksrepo.mirrorlist repo.name = ksrepo.name if not ksrepo.baseurl: repo.baseurl = [] else: repo.baseurl = [ksrepo.baseurl] repo.anacondaBaseURLs = anacondaBaseURLs if ksrepo.cost: repo.cost = ksrepo.cost if ksrepo.excludepkgs: repo.exclude = ksrepo.excludepkgs if ksrepo.includepkgs: repo.includepkgs = ksrepo.includepkgs if ksrepo.noverifyssl: repo.sslverify = False if ksrepo.proxy: self.setProxy(ksrepo, repo) self.repos.add(repo) self.smart_ctrl.saveSysConf() self.smart_ctrl.restoreMediaState() self.doRepoSetup(self.anaconda)
def createUser(self, user_name, *args, **kwargs): """Create a new user on the system with the given name. Optional kwargs: algo -- The password algorithm to use in case isCrypted=True. If none is given, the cryptPassword default is used. gecos -- The GECOS information (full name, office, phone, etc.). Defaults to "". groups -- A list of existing group names the user should be added to. Defaults to []. homedir -- The home directory for the new user. Defaults to /home/<name>. isCrypted -- Is the password kwargs already encrypted? Defaults to False. lock -- Is the new account locked by default? Defaults to False. password -- The password. See isCrypted for how this is interpreted. If the password is "" then the account is created with a blank password. If None or False the account will be left in its initial state (locked) root -- The directory of the system to create the new user in. homedir will be interpreted relative to this. Defaults to /mnt/sysimage. shell -- The shell for the new user. If none is given, the libuser default is used. uid -- The UID for the new user. If none is given, the next available one is used. gid -- The GID for the new user. If none is given, the next available one is used. """ childpid = os.fork() root = kwargs.get("root", iutil.getSysroot()) if not childpid: if not root in ["", "/"]: os.chroot(root) os.chdir("/") del (os.environ["LIBUSER_CONF"]) self.admin = libuser.admin() try: if self.admin.lookupUserByName(user_name): os._exit(1) userEnt = self.admin.initUser(user_name) groupEnt = self.admin.initGroup(user_name) if kwargs.get("gid", -1) >= 0: groupEnt.set(libuser.GIDNUMBER, kwargs["gid"]) grpLst = filter( lambda grp: grp, map(lambda name: self.admin.lookupGroupByName(name), kwargs.get("groups", []))) userEnt.set( libuser.GIDNUMBER, [groupEnt.get(libuser.GIDNUMBER)[0]] + map(lambda grp: grp.get(libuser.GIDNUMBER)[0], grpLst)) if kwargs.get("homedir", False): userEnt.set(libuser.HOMEDIRECTORY, kwargs["homedir"]) else: iutil.mkdirChain('/home') userEnt.set(libuser.HOMEDIRECTORY, "/home/" + user_name) if kwargs.get("shell", False): userEnt.set(libuser.LOGINSHELL, kwargs["shell"]) if kwargs.get("uid", -1) >= 0: userEnt.set(libuser.UIDNUMBER, kwargs["uid"]) if kwargs.get("gecos", False): userEnt.set(libuser.GECOS, kwargs["gecos"]) # need to create home directory for the user or does it already exist? # userEnt.get returns lists (usually with a single item) mk_homedir = not os.path.exists( userEnt.get(libuser.HOMEDIRECTORY)[0]) self.admin.addUser(userEnt, mkmailspool=kwargs.get("mkmailspool", True), mkhomedir=mk_homedir) self.admin.addGroup(groupEnt) if not mk_homedir: stats = os.stat(userEnt.get(libuser.HOMEDIRECTORY)[0]) orig_uid = stats.st_uid orig_gid = stats.st_gid log.info("Home directory for the user %s already existed, " "fixing the owner." % user_name) # home directory already existed, change owner of it properly iutil.chown_dir_tree( userEnt.get(libuser.HOMEDIRECTORY)[0], userEnt.get(libuser.UIDNUMBER)[0], groupEnt.get(libuser.GIDNUMBER)[0], orig_uid, orig_gid) pw = kwargs.get("password", False) if pw: if kwargs.get("isCrypted", False): password = kwargs["password"] else: password = cryptPassword(kwargs["password"], algo=kwargs.get("algo", None)) self.admin.setpassUser(userEnt, password, True) elif pw == "": # Setup the account with *NO* password self.admin.unlockUser(userEnt) log.info("user account %s setup with no password" % user_name) if kwargs.get("lock", False): self.admin.lockUser(userEnt) log.info("user account %s locked" % user_name) # Add the user to all the groups they should be part of. grpLst.append(self.admin.lookupGroupByName(user_name)) for grp in grpLst: grp.add(libuser.MEMBERNAME, user_name) self.admin.modifyGroup(grp) os._exit(0) except Exception as e: log.critical("Error when creating new user: %s" % str(e)) os._exit(1) try: (pid, status) = os.waitpid(childpid, 0) except OSError as e: log.critical( "exception from waitpid while creating a user: %s %s" % (e.errno, e.strerror)) return False if os.WIFEXITED(status) and (os.WEXITSTATUS(status) == 0): return True else: return False
def createUser (self, user_name, *args, **kwargs): """Create a new user on the system with the given name. Optional kwargs: algo -- The password algorithm to use in case isCrypted=True. If none is given, the cryptPassword default is used. gecos -- The GECOS information (full name, office, phone, etc.). Defaults to "". groups -- A list of existing group names the user should be added to. Defaults to []. homedir -- The home directory for the new user. Defaults to /home/<name>. isCrypted -- Is the password kwargs already encrypted? Defaults to False. lock -- Is the new account locked by default? Defaults to False. password -- The password. See isCrypted for how this is interpreted. root -- The directory of the system to create the new user in. homedir will be interpreted relative to this. Defaults to /mnt/sysimage. shell -- The shell for the new user. If none is given, the libuser default is used. uid -- The UID for the new user. If none is given, the next available one is used. """ childpid = os.fork() root = kwargs.get("root", "/mnt/sysimage") if not childpid: if not root in ["","/"]: os.chroot(root) del(os.environ["LIBUSER_CONF"]) self.admin = libuser.admin() try: if self.admin.lookupUserByName(user_name): os._exit(1) userEnt = self.admin.initUser(user_name) groupEnt = self.admin.initGroup(user_name) grpLst = filter(lambda grp: grp, map(lambda name: self.admin.lookupGroupByName(name), kwargs.get("groups", []))) userEnt.set(libuser.GIDNUMBER, [groupEnt.get(libuser.GIDNUMBER)[0]] + map(lambda grp: grp.get(libuser.GIDNUMBER)[0], grpLst)) if kwargs.get("homedir", False): userEnt.set(libuser.HOMEDIRECTORY, kwargs["homedir"]) else: iutil.mkdirChain(root+'/home') userEnt.set(libuser.HOMEDIRECTORY, "/home/" + user_name) if kwargs.get("shell", False): userEnt.set(libuser.LOGINSHELL, kwargs["shell"]) if kwargs.get("uid", -1) >= 0: userEnt.set(libuser.UIDNUMBER, kwargs["uid"]) if kwargs.get("gecos", False): userEnt.set(libuser.GECOS, kwargs["gecos"]) self.admin.addUser(userEnt, mkmailspool=kwargs.get("mkmailspool", True)) self.admin.addGroup(groupEnt) if kwargs.get("password", False): if kwargs.get("isCrypted", False): password = kwargs["password"] else: password = cryptPassword(kwargs["password"], algo=kwargs.get("algo", None)) self.admin.setpassUser(userEnt, password, True) if kwargs.get("lock", False): self.admin.lockUser(userEnt) # Add the user to all the groups they should be part of. grpLst.append(self.admin.lookupGroupByName(user_name)) for grp in grpLst: grp.add(libuser.MEMBERNAME, user_name) self.admin.modifyGroup(grp) os._exit(0) except Exception as e: log.critical("Error when creating new user: %s" % str(e)) os._exit(1) try: (pid, status) = os.waitpid(childpid, 0) except OSError as e: log.critical("exception from waitpid while creating a user: %s %s" % (e.errno, e.strerror)) return False if os.WIFEXITED(status) and (os.WEXITSTATUS(status) == 0): return True else: return False
def write(self, instPath='', anaconda=None, devices=None): # If the hostname was not looked up, but typed in by the user, # domain might not be computed, so do it now. domainname = None if "." in self.hostname: fqdn = self.hostname else: fqdn = socket.getfqdn(self.hostname) if fqdn in [ "localhost.localdomain", "localhost", "localhost6.localdomain6", "localhost6", self.hostname ] or "." not in fqdn: fqdn = None if fqdn: domainname = fqdn.split('.', 1)[1] if domainname in [ "localdomain", "localdomain6" ]: domainname = None else: domainname = None if self.domains == ["localdomain"] or not self.domains: if domainname: self.domains = [domainname] # /etc/udev/rules.d/70-persistent-net.rules rules = "/etc/udev/rules.d/70-persistent-net.rules" destRules = instPath + rules if (not instPath) or (not os.path.isfile(destRules)) or \ flags.livecdInstall: if not os.path.isdir("%s/etc/udev/rules.d" %(instPath,)): iutil.mkdirChain("%s/etc/udev/rules.d" %(instPath,)) if os.path.isfile(rules) and rules != destRules: shutil.copy(rules, destRules) else: f = open(destRules, "w") f.write(""" # This file was automatically generated by the /lib/udev/write_net_rules # program run by the persistent-net-generator.rules rules file. # # You can modify it, as long as you keep each rule on a single line. """) for dev in self.netdevices.values(): addr = dev.get("HWADDR") if not addr: continue devname = dev.get("DEVICE") basename = devname while basename != "" and basename[-1] in string.digits: basename = basename[:-1] # rules are case senstive for address. Lame. addr = addr.lower() s = "" if len(dev.get("DESC")) > 0: s = "# %s (rule written by anaconda)\n" % (dev.get("DESC"),) else: s = "# %s (rule written by anaconda)\n" % (devname,) s = s + 'SUBSYSTEM==\"net\", ACTION==\"add\", DRIVERS=="?*", ATTR{address}=="%s", ATTR{type}=="1", KERNEL=="%s*", NAME="%s"\n' % (addr, basename, devname,) f.write(s) f.close() net_conf = instPath+"/etc/conf.d/net" net_conf_dir = os.path.dirname(net_conf) if os.path.isfile(net_conf): f = open(net_conf, "aw") else: if not os.path.isdir(net_conf_dir): os.makedirs(net_conf_dir) f = open (net_conf, "w") for dev in self.netdevices.values(): device = dev.get("DEVICE") net_conf = [] ipaddr = dev.get('IPADDR') netmask = dev.get('NETMASK') gateway = dev.get('GATEWAY') is_dhcp_boot = dev.get('BOOTPROTO') == "dhcp" if is_dhcp_boot or (not ipaddr): net_conf.append('dhcp_%s="nosendhost"\n' % (device,)) else: net_conf.append('config_%s="%s netmask %s"\n' % ( device, ipaddr, netmask, ) ) if gateway: net_conf.append('routes_%s="default via %s"\n' % ( device, gateway, ) ) # add new dns_domain_device nis_domain_device management net_conf.append('dns_domain_%s="localdomain"\n' % ( device, ) ) net_conf.append('nis_domain_%s="localdomain"\n' % ( device, ) ) for line in net_conf: f.write(line) f.flush() f.flush() f.close() # hostname f = open(instPath+"/etc/conf.d/hostname","w") if not self.hostname: self.hostname = "sabayon" f.write("hostname=\""+self.hostname + "\"\n") f.flush() f.close() # samba smb_cfg = instPath+"/etc/samba/smb.conf" if os.path.isfile(smb_cfg): g = open(smb_cfg, "r") smb_conf = g.readlines() g = open(smb_cfg, "w") for line in smb_conf: if (line.find("netbios name = ") != -1) and (not line.strip().startswith("#")): line = " netbios name = %s\n" % (self.hostname,) g.write(line) g.flush() g.close() # /etc/hosts host_file = instPath + "/etc/hosts" host_data = [] if os.path.isfile(host_file) and os.access(host_file,os.R_OK): f = open(host_file, "r") host_data = [x.strip() for x in f.readlines()] f.close() f = open(host_file, "w") found = False for line in host_data: if line.startswith("127.0.0.1"): if self.hostname not in line.split(): line += " %s" % (self.hostname,) found = True f.write(line+"\n") if not found: f.write("127.0.0.1\t\t%s\n" % (self.hostname,)) f.flush() f.close() log.info("hostname set to = %s" % (self.hostname,)) domain_conf = instPath+"/etc/conf.d/domainname" if os.path.isfile(domain_conf): f = open(domain_conf,"r") domainname_cont = f.readlines() f.close() f = open(domain_conf, "w") for line in domainname_cont: if line.startswith("DNSDOMAIN="): line = 'DNSDOMAIN="localdomain"\n' elif line.startswith("NISDOMAIN="): line = 'NISDOMAIN="localdomain"\n' f.write(line) f.flush() f.close() # dhclient.conf -> force NetworkManager to not change hostname dh_conf = instPath + "/etc/dhcp/dhclient.conf" if os.path.isfile(dh_conf): f = open(dh_conf, "w") f.write('send host-name "'+self.hostname+'";\n') f.write('supersede host-name "'+self.hostname+'";\n') f.flush() f.close()
def write(self, instPath="", anaconda=None, devices=None): # If the hostname was not looked up, but typed in by the user, # domain might not be computed, so do it now. domainname = None if "." in self.hostname: fqdn = self.hostname else: fqdn = socket.getfqdn(self.hostname) if ( fqdn in ["localhost.localdomain", "localhost", "localhost6.localdomain6", "localhost6", self.hostname] or "." not in fqdn ): fqdn = None if fqdn: domainname = fqdn.split(".", 1)[1] if domainname in ["localdomain", "localdomain6"]: domainname = None else: domainname = None if self.domains == ["localdomain"] or not self.domains: if domainname: self.domains = [domainname] # /etc/udev/rules.d/70-persistent-net.rules rules = "/etc/udev/rules.d/70-persistent-net.rules" destRules = instPath + rules if (not instPath) or (not os.path.isfile(destRules)) or flags.livecdInstall: if not os.path.isdir("%s/etc/udev/rules.d" % (instPath,)): iutil.mkdirChain("%s/etc/udev/rules.d" % (instPath,)) if os.path.isfile(rules) and rules != destRules: shutil.copy(rules, destRules) else: f = open(destRules, "w") f.write( """ # This file was automatically generated by the /lib/udev/write_net_rules # program run by the persistent-net-generator.rules rules file. # # You can modify it, as long as you keep each rule on a single line. """ ) for dev in self.netdevices.values(): addr = dev.get("HWADDR") if not addr: continue devname = dev.get("DEVICE") basename = devname while basename != "" and basename[-1] in string.digits: basename = basename[:-1] # rules are case senstive for address. Lame. addr = addr.lower() s = "" if len(dev.get("DESC")) > 0: s = "# %s (rule written by anaconda)\n" % (dev.get("DESC"),) else: s = "# %s (rule written by anaconda)\n" % (devname,) s = ( s + 'SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="%s", ATTR{type}=="1", KERNEL=="%s*", NAME="%s"\n' % (addr, basename, devname) ) f.write(s) f.close() hostname = self.hostname if not self.hostname: hostname = "kogaion" # systemd uses /etc/hostname with open(instPath + "/etc/hostname", "w") as f: f.write(hostname) f.write("\n") f.flush() # samba smb_cfg = instPath + "/etc/samba/smb.conf" if os.path.isfile(smb_cfg): g = open(smb_cfg, "r") smb_conf = g.readlines() g = open(smb_cfg, "w") for line in smb_conf: if (line.find("netbios name = ") != -1) and (not line.strip().startswith("#")): line = " netbios name = %s\n" % (self.hostname,) g.write(line) g.flush() g.close() # /etc/hosts host_file = instPath + "/etc/hosts" host_data = [] if os.path.isfile(host_file) and os.access(host_file, os.R_OK): f = open(host_file, "r") host_data = [x.strip() for x in f.readlines()] f.close() f = open(host_file, "w") found = False for line in host_data: if line.startswith("127.0.0.1"): if self.hostname not in line.split(): line += " %s" % (self.hostname,) found = True f.write(line + "\n") if not found: f.write("127.0.0.1\t\t%s\n" % (self.hostname,)) f.flush() f.close() log.info("hostname set to = %s" % (self.hostname,)) # dhclient.conf -> force NetworkManager to not change hostname dh_conf = instPath + "/etc/dhcp/dhclient.conf" if os.path.isfile(dh_conf): f = open(dh_conf, "w") f.write('send host-name "' + self.hostname + '";\n') f.write('supersede host-name "' + self.hostname + '";\n') f.flush() f.close()