def _InitDefaults(self): # Default value; user may unset it. # $ echo -n "$IFS" | python -c 'import sys;print repr(sys.stdin.read())' # ' \t\n' SetGlobalString(self, 'IFS', split.DEFAULT_IFS) SetGlobalString(self, 'PWD', posix.getcwd()) # NOTE: Should we put these in a namespace for Oil? SetGlobalString(self, 'UID', str(posix.getuid())) SetGlobalString(self, 'EUID', str(posix.geteuid())) SetGlobalString(self, 'HOSTNAME', str(libc.gethostname())) # In bash, this looks like 'linux-gnu', 'linux-musl', etc. Scripts test # for 'darwin' and 'freebsd' too. They generally don't like at 'gnu' or # 'musl'. We don't have that info, so just make it 'linux'. SetGlobalString(self, 'OSTYPE', str(posix.uname()[0].lower())) # For getopts builtin SetGlobalString(self, 'OPTIND', '1') # For xtrace SetGlobalString(self, 'PS4', '+ ') # bash-completion uses this. Value copied from bash. It doesn't integrate # with 'readline' yet. SetGlobalString(self, 'COMP_WORDBREAKS', util.READLINE_DELIMS)
def __init__(self, data_dir="/usr/share/command-not-found"): self.sources_list = self._getSourcesList() # a new style DB means we can skip loading the old legacy static DB if os.path.exists(dbpath): self.db = SqliteDatabase(dbpath) elif os.path.exists(legacy_db): self.db = SqliteDatabase(legacy_db) self.user_can_sudo = user_can_sudo() self.euid = posix.geteuid()
def can_systemd(): if not which("systemctl"): LOGGER.warning("Cannot find systemctl to run services") return False if geteuid() != 0: LOGGER.warning( f"Running as non-root (euid {geteuid()}): may not be able to run systemd!" ) return False return True
def main(): if posix.geteuid() != 0: dialog = gtk.MessageDialog( None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, _("You should have root privileges to run this program")) dialog.show_all() dialog.run() else: main_window = Mainwindow() main_window.run()
def download_image (self, iurl): i = iurl.rfind('/') d = iurl.rfind('?') user = pwd.getpwuid(posix.geteuid()) storeroot = os.path.abspath(user[5]) filed = storeroot + '/twitter-icons/' + iurl[i+1:d] if not os.path.isfile(filed): try: f = urllib.urlretrieve(iurl, filed) except Exception, e : self.error("Failed to download picture, %s" % e)
def install_prompt(self, package_name): if not "COMMAND_NOT_FOUND_INSTALL_PROMPT" in os.environ: return if package_name: answer = raw_input(_("Do you want to install it? (N/y)")) if sys.stdin.encoding and isinstance(answer, str): # Decode the answer so that we get an unicode value answer = answer.decode(sys.stdin.encoding) if answer.lower() == _("y"): if posix.geteuid() == 0: command_prefix = "" else: command_prefix = "sudo " install_command = "%sapt-get install %s" % (command_prefix, package_name) print >> sys.stdout, "%s" % install_command subprocess.call(install_command.split(), shell=False)
def Get(self, name): if name in self.cache: return self.cache[name] if name == 'euid': # for \$ and \u value = posix.geteuid() elif name == 'hostname': # for \h and \H value = libc.gethostname() elif name == 'user': # for \u value = _GetUserName( self.Get('euid')) # recursive call for caching else: raise AssertionError(name) self.cache[name] = value return value
def __init__(self,daemon,input,output): self.config = utility.get_config("configuration", { }) self.running = 1 self.daemon = daemon self.open_windows = [ ] self.input = input self.output = output #self.connection = connection # Try to get a sensible default human name. dfl_human_name = '' try: import posix import pwd pw = pwd.getpwuid(posix.geteuid()) if pw: gecos = pw[4] dfl_human_name = string.split(gecos, ',')[0] except: pass # we have two files for the options: # some options belong to the gui, others to the daemon for pair in [('name', os.environ.get('USER','anon')), ('human-name', dfl_human_name), ('description', ''), ('background_color',(65535,65535,65535)), ('text_color',(0,0,0)), ('links_color',(0,0,65535)), ('people_color',(0,0,65535)), ('files_color',(0,0,65535)), ('local_files_color',(41120,8224,61680)), ('quiet_color',(26727, 44310, 14828)), ('beep_on_message', 1), ('show_tips', 1), ('show_gossip', 1), ('auto_list_channels', 1), ('augmented_text', 0)]: if not self.config.has_key(pair[0]): self.config[pair[0]] = pair[1] self.config_dialog_open = 0
def _InitDefaults(self): # Default value; user may unset it. # $ echo -n "$IFS" | python -c 'import sys;print repr(sys.stdin.read())' # ' \t\n' SetGlobalString(self, 'IFS', split.DEFAULT_IFS) SetGlobalString(self, 'PWD', posix.getcwd()) # NOTE: Should we put these in a namespace for Oil? SetGlobalString(self, 'UID', str(posix.getuid())) SetGlobalString(self, 'EUID', str(posix.geteuid())) # For getopts builtin SetGlobalString(self, 'OPTIND', '1') # For xtrace SetGlobalString(self, 'PS4', '+ ') # bash-completion uses this. Value copied from bash. It doesn't integrate # with 'readline' yet. SetGlobalString(self, 'COMP_WORDBREAKS', util.READLINE_DELIMS)
def run(): import os.path import pwd import posix user = pwd.getpwuid(posix.geteuid()) home = os.path.abspath(user[5]) pl = os.path.join(home, "example.png") pw = os.path.join(home, "example-pw.png") sh = os.path.join(home, "example-sh.png") m = draw() # profit m.save(pl) print "wrote combined layers to %s" % pl m.save(pw, "pinwin") print "wrote pinwin layer to %s" % pw m.save(sh, "shadow") print "wrote shadow layer to %s" % sh
def run () : import os.path import pwd import posix user = pwd.getpwuid(posix.geteuid()) home = os.path.abspath(user[5]) pl = os.path.join(home, "example.png") pw = os.path.join(home, "example-pw.png") sh = os.path.join(home, "example-sh.png") m = draw() # profit m.save(pl) print "wrote combined layers to %s" % pl m.save(pw, "pinwin") print "wrote pinwin layer to %s" % pw m.save(sh, "shadow") print "wrote shadow layer to %s" % sh
def advise(self, command, ignore_installed=False): " give advice where to find the given command to stderr " def _in_prefix(prefix, command): " helper that returns if a command is found in the given prefix " return (os.path.exists(os.path.join(prefix, command)) and not os.path.isdir(os.path.join(prefix, command))) if command.startswith("/"): if os.path.exists(command): prefixes = [os.path.dirname(command)] else: prefixes = [] else: prefixes = [prefix for prefix in self.prefixes if _in_prefix(prefix, command)] # check if we have it in a common prefix that may not be in the PATH if prefixes and not ignore_installed: if len(prefixes) == 1: print >> sys.stderr, _("Command '%(command)s' is available in '%(place)s'") % {"command": command, "place": os.path.join(prefixes[0], command)} else: print >> sys.stderr, _("Command '%(command)s' is available in the following places") % {"command": command} for prefix in prefixes: print >> sys.stderr, " * %s" % os.path.join(prefix, command) missing = list(set(prefixes) - set(os.getenv("PATH", "").split(":"))) if len(missing) > 0: print >> sys.stderr, _("The command could not be located because '%s' is not included in the PATH environment variable.") % ":".join(missing) if "sbin" in ":".join(missing): print >> sys.stderr, _("This is most likely caused by the lack of administrative privileges associated with your user account.") return False # do not give advice if we are in a situation where apt-get # or aptitude are not available (LP: #394843) if not (os.path.exists("/usr/bin/apt-get") or os.path.exists("/usr/bin/aptitude")): return False if command in self.getBlacklist(): return False packages = self.getPackages(command) if len(packages) == 0: self.print_spelling_suggestion(command) elif len(packages) == 1: print >> sys.stderr, _("The program '%s' is currently not installed. ") % command, if posix.geteuid() == 0: print >> sys.stderr, _("You can install it by typing:") print >> sys.stderr, "apt-get install %s" % packages[0][0] self.install_prompt(packages[0][0]) elif self.user_can_sudo: print >> sys.stderr, _("You can install it by typing:") print >> sys.stderr, "sudo apt-get install %s" % packages[0][0] self.install_prompt(packages[0][0]) else: print >> sys.stderr, _("To run '%(command)s' please ask your administrator to install the package '%(package)s'") % {'command': command, 'package': packages[0][0]} if not packages[0][1] in self.sources_list: print >> sys.stderr, _("You will have to enable the component called '%s'") % packages[0][1] elif len(packages) > 1: packages.sort(self.sortByComponent) print >> sys.stderr, _("The program '%s' can be found in the following packages:") % command for package in packages: if package[1] in self.sources_list: print >> sys.stderr, " * %s" % package[0] else: print >> sys.stderr, " * %s" % package[0] + " (" + _("You will have to enable component called '%s'") % package[1] + ")" if posix.geteuid() == 0: print >> sys.stderr, _("Try: %s <selected package>") % "apt-get install" elif self.user_can_sudo: print >> sys.stderr, _("Try: %s <selected package>") % "sudo apt-get install" else: print >> sys.stderr, _("Ask your administrator to install one of them") return len(packages) > 0
def advise(self, command, ignore_installed=False): " give advice where to find the given command to stderr " def _in_prefix(prefix, command): " helper that returns if a command is found in the given prefix " return (os.path.exists(os.path.join(prefix, command)) and not os.path.isdir(os.path.join(prefix, command))) if command.startswith("/"): if os.path.exists(command): prefixes = [os.path.dirname(command)] else: prefixes = [] else: prefixes = [ prefix for prefix in self.prefixes if _in_prefix(prefix, command) ] # check if we have it in a common prefix that may not be in the PATH if prefixes and not ignore_installed: if len(prefixes) == 1: print(_("Command '%(command)s' is available in '%(place)s'") % { "command": command, "place": os.path.join(prefixes[0], command) }, file=sys.stderr) else: print(_( "Command '%(command)s' is available in the following places" ) % {"command": command}, file=sys.stderr) for prefix in prefixes: print(" * %s" % os.path.join(prefix, command), file=sys.stderr) missing = list( set(prefixes) - set(os.getenv("PATH", "").split(":"))) if len(missing) > 0: print(_( "The command could not be located because '%s' is not included in the PATH environment variable." ) % ":".join(missing), file=sys.stderr) if "sbin" in ":".join(missing): print(_( "This is most likely caused by the lack of administrative privileges associated with your user account." ), file=sys.stderr) return False # do not give advice if we are in a situation where apt-get # or aptitude are not available (LP: #394843) if not (os.path.exists("/usr/bin/apt-get") or os.path.exists("/usr/bin/aptitude")): return False if command in self.getBlacklist(): return False packages = self.getPackages(command) if len(packages) == 0: self.print_spelling_suggestion(command) elif len(packages) == 1: print(_("The program '%s' is currently not installed. ") % command, end="", file=sys.stderr) if posix.geteuid() == 0: print(_("You can install it by typing:"), file=sys.stderr) print("apt-get install %s" % packages[0][0], file=sys.stderr) self.install_prompt(packages[0][0]) elif self.user_can_sudo: print(_("You can install it by typing:"), file=sys.stderr) print("sudo apt-get install %s" % packages[0][0], file=sys.stderr) self.install_prompt(packages[0][0]) else: print(_( "To run '%(command)s' please ask your administrator to install the package '%(package)s'" ) % { 'command': command, 'package': packages[0][0] }, file=sys.stderr) if not packages[0][1] in self.sources_list: print(_("You will have to enable the component called '%s'") % packages[0][1], file=sys.stderr) elif len(packages) > 1: packages.sort(key=cmp_to_key(self.sortByComponent)) print( _("The program '%s' can be found in the following packages:") % command, file=sys.stderr) for package in packages: if package[1] in self.sources_list: print(" * %s" % package[0], file=sys.stderr) else: print(" * %s" % package[0] + " (" + _("You will have to enable component called '%s'") % package[1] + ")", file=sys.stderr) if posix.geteuid() == 0: print(_("Try: %s <selected package>") % "apt-get install", file=sys.stderr) elif self.user_can_sudo: print(_("Try: %s <selected package>") % "sudo apt-get install", file=sys.stderr) else: print(_("Ask your administrator to install one of them"), file=sys.stderr) return len(packages) > 0
def get_install_msg(cmdname, ignore_installed=True): """ Use CommandNotFound if it is installed, to find any apt packages that may be available. Returns None when no packages are found, and install intructions when there are packages available. """ if CNF is None: # Feature not enabled. return None cmdname = os.path.split(cmdname)[-1] if cmdname in CNF.getBlacklist(): return None packages = CNF.getPackages(cmdname) pkglen = len(packages) colr_args = { 'cmd': {'fore': 'blue'}, 'installcmd': {'fore': 'green'}, 'pkg': {'fore': 'green'}, 'component': {'fore': 'yellow'}, } if pkglen == 0: return None if pkglen == 1: msgfmt = '\n'.join(( 'The program \'{cmd}\' is currently not installed.', ' You can install it by typing: {installcmd}' )) if posix.geteuid() == 0: # User is root. msg = msgfmt.format( cmd=C(cmdname, **colr_args['cmd']), installcmd=C( 'apt install {}'.format(packages[0][0]), **colr_args['installcmd'] ) ) elif CNF.user_can_sudo: msg = msgfmt.format( cmd=C(cmdname, **colr_args['cmd']), installcmd=C( 'sudo apt install {}'.format(packages[0][0]), **colr_args['installcmd'] ) ) else: msg = ' '.join(( 'To run \'{cmd}\' please ask your administrator to install', 'the package \'{pkg}\'' )).format( cmd=C(cmdname, **colr_args['cmd']), pkg=C(packages[0][0], **colr_args['pkg']) ) if not packages[0][1] in CNF.sources_list: msg = '\n'.join(( msg, 'You will have to enable the component called \'{}\''.format( C(packages[0][1], **colr_args['component']) ) )) return msg if pkglen > 1: # Multiple packages available. packages.sort(key=cmp_to_key(CNF.sortByComponent)) msg = [ 'The program \'{cmd}\' can be found in the following packages:' ] for package in packages: if package[1] in CNF.sources_list: msg.append(' * {pkg}'.format( pkg=C(package[0], **colr_args['pkg']) )) else: msg.append( ' * {pkg} ({extramsg} {component})'.format( pkg=C(package[0], **colr_args['pkg']), extramsg='You will have to enable a component called', component=C(package[1], **colr_args['component']) ) ) installmsg = ' Try {{sudo}}{}'.format( C('apt install <selected package>', **colr_args['installcmd']) ) if posix.geteuid() == 0: msg.append(installmsg) return '\n'.join(msg).format( cmd=cmdname, sudo='' ) elif CNF.user_can_sudo: msg.append(installmsg) return '\n'.join(msg).format( cmd=cmdname, sudo=C('sudo ', **colr_args['installcmd']) ) # Multiple packages, user cannot sudo. msg.append(C( ' Ask your administrator to install one of them.', **colr_args['installcmd'] )) return '\n'.join(msg).format(cmd=C(cmdname, **colr_args['cmd']))
self.error("Failed to notify, %s" % e) return False return True # # # if __name__ == "__main__" : retCode = createDaemon() import os.path import pwd import posix user = pwd.getpwuid(posix.geteuid()) storeroot = os.path.abspath(user[5]) storepath = os.path.abspath(os.path.join(storeroot, u".twnotifier")) app = twgrowler(storepath) app.loop() # The code, as is, will create a new file in the root directory, when # executed with superuser privileges. The file will contain the following # daemon related process parameters: return code, process ID, parent # process group ID, session ID, user ID, effective user ID, real group ID, # and the effective group ID. Notice the relationship between the daemon's # process ID, process group ID, and its parent's process ID. procParams = """ return code = %s