Python os.getlogin() Examples

The following are code examples for showing how to use os.getlogin(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Python-Scripts-and-Games   Author: aashutoshrathi   File: AddToTaskbar.py    MIT License 7 votes vote down vote up
def addToTaskbar(file_path, dir_path, name):
    you = os.getlogin()
    startup = os.path.join('C:\\Users', you, 'AppData', 'Roaming',
                            'Microsoft', 'Internet Explorer', 'Quick Launch',
                            'User Pinned', 'TaskBar')
    name = name + '.lnk'
    path = os.path.join(startup, name)
    shell = Dispatch('WScript.Shell')
    shortcut = shell.CreateShortCut(path)
    shortcut.Targetpath = file_path
    shortcut.WorkingDirectory = dir_path
    shortcut.IconLocation = file_path
    shortcut.save() 
Example 2
Project: Python-Scripts-and-Games   Author: aashutoshrathi   File: add_to_sendTo.py    MIT License 7 votes vote down vote up
def make_shortcut(file_path, dir_path, name):
    you = os.getlogin()
    startup = os.path.join('C:\\Users', you, 'AppData', 'Roaming',
                            'Microsoft', 'Windows', 'SendTo')
    name = name + '.lnk'
    path = os.path.join(startup, name)
    shell = Dispatch('WScript.Shell')
    shortcut = shell.CreateShortCut(path)
    shortcut.Targetpath = file_path
    shortcut.WorkingDirectory = dir_path
    shortcut.IconLocation = file_path
    shortcut.save() 
Example 3
Project: Python-Scripts-and-Games   Author: aashutoshrathi   File: set_to_startup.py    MIT License 6 votes vote down vote up
def make_shortcut(file_path, dir_path, name):
    you = os.getlogin()
    startup = os.path.join('C:\\Users', you, 'AppData', 'Roaming',
                            'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')
    name = name + '.lnk'
    path = os.path.join(startup, name)
    shell = Dispatch('WScript.Shell')
    shortcut = shell.CreateShortCut(path)
    shortcut.Targetpath = file_path
    shortcut.WorkingDirectory = dir_path
    shortcut.IconLocation = file_path
    shortcut.save() 
Example 4
Project: Spyce   Author: imec-myhdl   File: netlist.py    GNU Lesser General Public License v2.1 6 votes vote down vote up
def fillTemplate(template, blockname, body, include):
    return template.format(body   = body,
                 projectname      = const.projectname,
                 version          = const.version,
                 copyrightText    = const.copyrightText,
                 copyrightPolicy  = const.copyrightPolicy,
                 ticks_per_second = const.ticks_per_second,
                 t_stop           = const.t_stop,
                 blockname        = blockname,
                 user             = os.getlogin(),
                 t_resolution     = timeresolution(),
                 include          = include)
    

#==============================================================================
# main netlist routine
#============================================================================== 
Example 5
Project: omniduct   Author: airbnb   File: duct.py    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
Project: openshift-restclient-python   Author: openshift   File: discovery.py    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 7
Project: dattasa   Author: kartikra   File: kafka_system.py    MIT License 6 votes vote down vote up
def connect(self, group_id="", client_id="",
                auto_offset_reset='earliest', consumer_timeout_ms=1000):

        client_id = socket.gethostname() if client_id == "" else client_id
        group_id = os.getlogin() if group_id == "" else group_id

        exception = ""
        try:
            consumer = KafkaConsumer(bootstrap_servers=self.bootstrap_servers,
                                     auto_offset_reset=auto_offset_reset,
                                     consumer_timeout_ms=consumer_timeout_ms,
                                     value_deserializer=lambda m: json.loads(m.decode('utf-8')),
                                     group_id=group_id,
                                     client_id=client_id,
                                     enable_auto_commit=False
                                     )
            self.consumer = consumer

        except KafkaError as ex:
            print(ex)
            exception = str(ex)
            self.consumer = None

        return exception 
Example 8
Project: YAPI   Author: YetAnotherPackageInstaller   File: config_extractor.py    GNU General Public License v3.0 6 votes vote down vote up
def get_configuration():
    """Get configurations from configuration files."""
    from configparser import ConfigParser
    from configparser import ExtendedInterpolation
    from os import getlogin
    from os import path
    config = ConfigParser(interpolation=ExtendedInterpolation())
    config.read(path.realpath(__file__).rstrip(
        "modules/configuration/config_extractor.py") + "/config/config.ini")
    configuration = dict()
    for key in config.keys():
        configuration[key] = dict()
        for element in config[key]:
            configuration[key][element] = config[key][element].replace(
                "~", "/home/" + getlogin())
    return configuration 
Example 9
Project: pastas   Author: pastas   File: model.py    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": pd.Timestamp.now()}

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

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

        return file_info 
Example 10
Project: psychrometric-chart-makeover   Author: buds-lab   File: ext_daemon.py    MIT License 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 11
Project: mead-baseline   Author: dpressel   File: demolib.py    Apache License 2.0 6 votes vote down vote up
def step(self, metrics, tick, phase, tick_type=None, **kwargs):
        """Write results to `slack` (webhook)

        :param metrics: A map of metrics to scores
        :param tick: The time (resolution defined by `tick_type`)
        :param phase: The phase of training (`Train`, `Valid`, `Test`)
        :param tick_type: The resolution of tick (`STEP`, `EPOCH`)
        :return:
        """
        import requests
        chunks = ''
        if phase in ['Valid', 'Test']:
            chunks += '%s(%d) [Epoch %d] [%s]' % (os.getlogin(), os.getpid(), tick, phase)
            for k, v in metrics.items():
                if k not in ['avg_loss', 'perplexity']:
                    v *= 100.
                chunks += '\t%s=%.3f' % (k, v)
            requests.post(self.webhook, json={"text": chunks}) 
Example 12
Project: wazuh-qa   Author: wazuh   File: fim.py    GNU General Public License v2.0 6 votes vote down vote up
def modify_file_owner(path, name):
    """Change the owner of a file. The new owner will be '1'.

    On Windows, uid will always be 0.

    :param path String Path to the file to be modified
    :param name String Name of the file to be modified
    """
    def modify_file_owner_windows():
        cmd = f"takeown /S 127.0.0.1 /U {os.getlogin()} /F " + path_to_file
        subprocess.call(cmd)

    def modify_file_owner_unix():
        os.chown(path_to_file, 1, -1)

    path_to_file = os.path.join(path, name)

    if sys.platform == 'win32':
        modify_file_owner_windows()
    else:
        modify_file_owner_unix() 
Example 13
Project: power-up   Author: IBM   File: software_hosts.py    Apache License 2.0 6 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 14
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def setup_interactive_mode(histfile='.python_history', interact=False):
    """Setup interactive mode with tab completion, prompt color, and command history."""
    # tab completion
    if 'libedit' in readline.__doc__:   # Mac
        print('Please intall GNU readline by "sudo easy_install readline", '
              'the libedit readline has caveat that cmd history not showing well with color prompt.')
        readline.parse_and_bind("bind '\t' rl_complete")
    else:
        readline.parse_and_bind("C-o: operate-and-get-next")
        readline.parse_and_bind("tab: complete")
        # color prompt
        sys.ps1 = '\x01\x1b[1;34m\x02>>> \x01\x1b[0m\x02'
        sys.ps2 = '\x01\x1b[1;34m\x02... \x01\x1b[0m\x02'
    # command history
    if histfile:
        # with a histfile, cmd history is saved across sessions.
        # Note, the test case execution is also saved in history file.
        histfile = os.path.expanduser("~" + os.getlogin() + os.sep + histfile)
        readline.set_history_length(500)
        try:
            with UserPrivilege():
                readline.read_history_file(histfile)
        except IOError as e:  # [Errno 13] Permission denied
            print_warn(e)

        def write_history_file():
            try:
                with UserPrivilege():
                    readline.write_history_file(histfile)
            except IOError as ex:  # [Errno 13] Permission denied
                print_warn(ex)
        atexit.register(write_history_file)

    if interact:
        try:
            import IPython
            IPython.embed()
        except ImportError:
            print("Python interactive mode. Note, use ipython for more interactive support.\n")
            code.interact(local=locals()) 
Example 15
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def setup_interactive_mode(histfile='.python_history', interact=False):
    """Setup interactive mode with tab completion, prompt color, and command history."""
    # tab completion
    if 'libedit' in readline.__doc__:   # Mac
        print('Please intall GNU readline by "sudo easy_install readline", '
              'the libedit readline has caveat that cmd history not showing well with color prompt.')
        readline.parse_and_bind("bind '\t' rl_complete")
    else:
        readline.parse_and_bind("C-o: operate-and-get-next")
        readline.parse_and_bind("tab: complete")
        # color prompt
        sys.ps1 = '\x01\x1b[1;34m\x02>>> \x01\x1b[0m\x02'
        sys.ps2 = '\x01\x1b[1;34m\x02... \x01\x1b[0m\x02'
    # command history
    if histfile:
        # with a histfile, cmd history is saved across sessions.
        # Note, the test case execution is also saved in history file.
        histfile = os.path.expanduser("~" + os.getlogin() + os.sep + histfile)
        readline.set_history_length(500)
        try:
            with UserPrivilege():
                readline.read_history_file(histfile)
        except IOError as e:  # [Errno 13] Permission denied
            print_warn(e)

        def write_history_file():
            try:
                with UserPrivilege():
                    readline.write_history_file(histfile)
            except IOError as ex:  # [Errno 13] Permission denied
                print_warn(ex)
        atexit.register(write_history_file)

    if interact:
        try:
            import IPython
            IPython.embed()
        except ImportError:
            print("Python interactive mode. Note, use ipython for more interactive support.\n")
            code.interact(local=locals()) 
Example 16
Project: tmanager   Author: ssh3ll   File: commands.py    MIT License 5 votes vote down vote up
def get_user_login() -> str:
    """
    Check user uid and return user name

    :return str: user name
    """
    return "root" if os.getuid() == 0 else os.getlogin() 
Example 17
Project: Old-school-processing   Author: cianfrocco-lab   File: apParam.py    MIT License 5 votes vote down vote up
def getAppionDirectory():
	"""
	Used by appionLoop
	"""
	appiondir = None
	this_file = inspect.currentframe().f_code.co_filename
	libdir = os.path.dirname(this_file)
	libdir = os.path.abspath(libdir)
	trypath = os.path.dirname(libdir)
	if os.path.isdir(trypath):
		appiondir = trypath
		return appiondir

	trypath = os.environ.get('APPIONDIR')
	if trypath and os.path.isdir(trypath):
		appiondir = trypath
		return appiondir

	user = os.getlogin() #os.environ.get('USER')
	trypath = "/home/"+user+"/pyappion"
	if os.path.isdir(trypath):
		appiondir = trypath
		return appiondir

	apDisplay.printError("environmental variable, APPIONDIR, is not defined.\n"+
		"Did you source useappion.sh?")


#===================== 
Example 18
Project: Python-Scripts-and-Games   Author: aashutoshrathi   File: AddToTaskbar.py    MIT License 5 votes vote down vote up
def main():
    print("\n===== Add Your files or Folders to Taskbar in easy way =====")
    you = os.getlogin()
    print('Hey!', you)
    file = input('Path of folder to be added to SendTo : ')
    workingDir = make_working_dir(file)
    file = remove_quotes(file)
    workingDir = remove_quotes(workingDir)
    name = input('File/Folder Name : ')
    addToTaskbar(file, workingDir, name)
    print(name, 'added to SendTo Successfully !!') 
Example 19
Project: Python-Scripts-and-Games   Author: aashutoshrathi   File: add_to_sendTo.py    MIT License 5 votes vote down vote up
def main():
    print("\n===== Add Your files or Folders to SendTo in easy way =====")
    you = os.getlogin()
    print('Hey!', you)
    file = input('Path of folder to be added to SendTo : ')
    workingDir = make_working_dir(file)
    file = remove_quotes(file)
    workingDir = remove_quotes(workingDir)
    name = input('Folder Name : ')
    make_shortcut(file, workingDir, name)
    print(name, 'added to SendTo Successfully !!') 
Example 20
Project: Unique-Python   Author: DipanshKhandelwal   File: GetFiles.py    MIT License 5 votes vote down vote up
def get_files():
	directory = os.path.join('C:\\Users\\%s\\Desktop' %os.getlogin())
	file_list = os.listdir(directory)
	print (file_list) 
Example 21
Project: analyzer-website   Author: santiagolizardo   File: test_proxies.py    GNU Affero 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 22
Project: NiujiaoDebugger   Author: MrSrc   File: test_os.py    GNU General Public License v3.0 5 votes vote down vote up
def test_getlogin(self):
        user_name = os.getlogin()
        self.assertNotEqual(len(user_name), 0) 
Example 23
Project: p4prometheus   Author: rcowham   File: systemctl3.py    MIT License 5 votes vote down vote up
def os_getlogin():
    """ NOT using os.getlogin() """
    import pwd
    return pwd.getpwuid(os.geteuid()).pw_name 
Example 24
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-c', '--consul', default='localhost:8500',
        help='The Consul host to connect to. Defaults to localhost:8500')
    parser.add_argument(
        '-u', '--ssh-user', default=os.getlogin(),
        help='The SSH user to specify for all hosts. Defaults to %s' % os.getlogin())
    parser.add_argument(
        '-m', '--merge', default='*.config',
        help='A glob pattern to specify files to collect and merge into the main config. '
             'Defaults to "*.config"')
    args = parser.parse_args()

    App(args.consul, args.ssh_user, args.merge).run() 
Example 25
Project: ai-platform   Author: produvia   File: submit.py    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 26
Project: rpython-lang-scheme   Author: tomoh1r   File: test_ll_os.py    MIT License 5 votes vote down vote up
def test_getlogin():
    if not hasattr(os, 'getlogin'):
        py.test.skip('posix specific function')
    try:
        expected = os.getlogin()
    except OSError, e:
        py.test.skip("the underlying os.getlogin() failed: %s" % e) 
Example 27
Project: rpython-lang-scheme   Author: tomoh1r   File: test_extfunc.py    MIT License 5 votes vote down vote up
def test_os_getlogin():
        def does_stuff():
            return os.getlogin()

        try:
            expected = os.getlogin()
        except OSError, e:
            py.test.skip("the underlying os.getlogin() failed: %s" % e) 
Example 28
Project: open-recipe   Author: dspray95   File: mailmail.py    The Unlicense 5 votes vote down vote up
def getlogin():
    try:
        return os.getlogin()
    except:
        return getpass.getuser() 
Example 29
Project: ZaaS   Author: kakugirai   File: zanryu.py    MIT License 5 votes vote down vote up
def cli(config):
    """ZaaS: Zanryu as a Service"""
    with open(config, "r") as file:
        data = json.load(file)
    weekdays = ["月", "火", "水", "木", "金", "土", "日"]
    i = date.today()
    data["login_name"] = os.getlogin()
    data["year"] = i.year
    data["month"] = i.month
    data["day"] = i.day
    data["weekday"] = weekdays[i.weekday()]
    r = requests.post(URL, json=data)
    return 
Example 30
Project: update_firefox   Author: tuxlover   File: update_firefox.py    GNU General Public License v3.0 5 votes vote down vote up
def unpack_firefox(archfile,pathuri):
	new_file = tarfile.open(archfile)
	if os.getlogin() == "root": 
		new_file.extractall(path=install_path)
		new_file.close()
	else:
		new_file.extractall(path=tar_url)
		new_file.close() 
Example 31
Project: mlab-ns   Author: m-lab   File: test_proxies.py    Apache License 2.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 32
Project: pyethapp   Author: heikoheiko   File: app.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(ctx, dev):
    """Start the client ( --dev to stop on error)"""
    # create app
    app = EthApp(ctx.obj['config'])

    # development mode
    if dev:
        gevent.get_hub().SYSTEM_ERROR = BaseException
        try:
            ctx.obj['config']['client_version'] += '/' + os.getlogin()
        except:
            log.warn("can't get and add login name to client_version")
            pass

    # dump config
    konfig.dump_config(ctx.obj['config'])

    # register services
    for service in services:
        assert issubclass(service, BaseService)
        if service.name not in app.config['deactivated_services']:
            assert service.name not in app.services
            service.register_with_app(app)
            assert hasattr(app.services, service.name)

    # start app
    app.start()

    # wait for interrupt
    evt = Event()
    gevent.signal(signal.SIGQUIT, evt.set)
    gevent.signal(signal.SIGTERM, evt.set)
    gevent.signal(signal.SIGINT, evt.set)
    evt.wait()

    # finally stop
    app.stop() 
Example 33
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_os.py    GNU General Public License v2.0 5 votes vote down vote up
def test_getlogin(self):
        user_name = os.getlogin()
        self.assertNotEqual(len(user_name), 0) 
Example 34
Project: mekong-ssc-gae   Author: KMarkert   File: test_proxies.py    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 35
Project: StockRecommendSystem   Author: doncat99   File: _file_cache.py    MIT License 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 (AttributeError, IOError, OSError):
            return 'nobody' 
Example 36
Project: utilities   Author: farisachugthai   File: env_checks.py    MIT License 5 votes vote down vote up
def get_username():
    """More cross-platform implementation of retrieving a username.


   This function checks the environment variables :envvar:`LOGNAME`,
   :envvar:`USER`, :envvar:`LNAME` and :envvar:`USERNAME`, in order, and
   returns the value of the first one which is set to a non-empty string.  If
   none are set, the login name from the password database is returned on
   systems which support the :mod:`pwd` module, otherwise, an exception is
   raised.

    In general, this function should be preferred over :func:`os.getlogin()`.
    """
    return getpass.getuser() 
Example 37
Project: tir   Author: totvs   File: base.py    MIT License 5 votes vote down vote up
def __init__(self, config_path="", autostart=True):
        """
        Definition of each global variable:

        base_container: A variable to contain the layer element to be used on all methods.

        errors: A list that contains every error that should be sent to log at the end of the execution.

        language: Contains the terms defined in the language defined in config or found in the page.

        log: Object that controls the logs of the entire application.

        log.station: Property of the log that contains the machine's hostname.

        log_file: A variable to control when to generate a log file of each execution of web_scrap. (Debug purposes)

        wait: The global Selenium Wait defined to be used in the entire application.
        """
        #Global Variables:

        if config_path == "":
            config_path = os.path.join(sys.path[0], r"config.json")
        self.config = ConfigLoader(config_path)
        self.config.autostart = autostart

        self.language = LanguagePack(self.config.language) if self.config.language else ""
        self.log = Log(folder=self.config.log_folder)
        self.log.station = socket.gethostname()
        self.log.user = os.getlogin()

        self.base_container = "body"
        self.errors = []
        self.config.log_file = False

        if autostart:
            self.Start()

# Internal Methods 
Example 38
Project: Safejumper-for-Desktop   Author: proxysh   File: mailmail.py    GNU General Public License v2.0 5 votes vote down vote up
def getlogin():
    try:
        return os.getlogin()
    except:
        return getpass.getuser() 
Example 39
Project: attack_monitor   Author: yarox24   File: madvr.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_env_variables(REPLACE_VARIABLES_PATH):
    REPLACE_VARIABLES = {"%%%USERNAME%%%" : os.getlogin(),
                        "%%%HOSTNAME%%%": platform.node(),
                        }

    if not os.path.exists(REPLACE_VARIABLES_PATH):
        with open(REPLACE_VARIABLES_PATH, 'w', encoding='utf8') as outfile:
            str_ = json.dumps(REPLACE_VARIABLES, indent=4, separators=(',', ': '), ensure_ascii=False)
            outfile.write(str_) 
Example 40
Project: syntribos   Author: openstack   File: env.py    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 41
Project: conf   Author: XonqNopp   File: shellutils.py    GNU General Public License v3.0 5 votes vote down vote up
def getlogin():
    """avoid using os.getlogin() because of strange tty / stdin problems
    (man 3 getlogin)
    Another solution would be to use $LOGNAME, $USER or $USERNAME
    """
    if sys.platform != 'win32':
        import pwd # Platforms: Unix
        return pwd.getpwuid(os.getuid())[0]
    else:
        return os.environ['USERNAME'] 
Example 42
Project: conf   Author: XonqNopp   File: shellutils.py    GNU General Public License v3.0 5 votes vote down vote up
def getlogin():
    """avoid using os.getlogin() because of strange tty / stdin problems
    (man 3 getlogin)
    Another solution would be to use $LOGNAME, $USER or $USERNAME
    """
    if sys.platform != 'win32':
        import pwd # Platforms: Unix
        return pwd.getpwuid(os.getuid())[0]
    else:
        return os.environ['USERNAME'] 
Example 43
Project: discord-voice-assistant-bot   Author: pg8wood   File: bot_service.py    MIT License 5 votes vote down vote up
def main():
	
	system = str(platform.system())
	release = str(platform.release())
	print("OS info:", system, release)
	
	if(system == "Windows"):
		venv_directory = "C:\\Users\\" + str(os.getlogin()) + "\\AppData\\Local\\Programs\\Python\\Python" + str(sys.version_info[0]) + str(sys.version_info[1]) + "\\Lib\\venv\\scripts\\nt\\activate.bat"
			
		print("Activating venv...")
		os.startfile(venv_directory)
		
	elif(system == "Linux"):
		venv_directory = "/usr/lib/python" + str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "/venv/scripts/common/activate"
		
		print("Activating venv...")
		os.system(venv_directory)
	
	else:  ##Not Windows or Linux, must be a Mac
		##TODO: implement MacOS startup!
		print("MacOS not yet supported! Oops...")
	
	while(True):
		exit_code = subprocess.call([sys.executable, "index.py"])
		
		print("Exit code: ", exit_code)
		
		if(exit_code != 0 and exit_code != 1):
			print("The bot crashed with exit code %d. Restarting...\n" % exit_code)
			time.sleep(1)
		else:
			print("The bot exited gracefully. Bye!\n")
			exit(0) 
Example 44
Project: liquimigrate   Author: onjin   File: base.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_arguments(self, parser):
        parser.add_argument(
            'app_label', nargs='*',
            help='App labels of applications to limit the output to.',
        )
        parser.add_argument(
            '--author', action='store', default=os.getlogin(),
            help='Migrations author (defaults to username)',
        )
        parser.add_argument(
            '--fake', action='store_true', default=False,
            help='Create fake changesets (mark migrations ran)',
        )
        parser.add_argument(
            '--skip-errors', action='store_true', default=False,
            help='Skip SQL creation erros',
        )
        parser.add_argument(
            '--database', action='store', dest='database',
            default=DEFAULT_DB_ALIAS,
            help='Nominates a database to synchronize. '
                 'Defaults to the "default" database.',
        )
        parser.add_argument(
            '--indent', action='store', default='    ',
            help='Indentation characters (defaults to four spaces)',
        ) 
Example 45
Project: BomberCrewBot   Author: ajchili   File: crewmembers.py    GNU General Public License v3.0 5 votes vote down vote up
def get_active_crew_members():
    # TODO: Support Multiple Save Files
    with open("C:\\Users\\" + os.getlogin() + "\\AppData\\LocalLow\\Runner Duck\\Bomber Crew\\BC_SaveSlotV2_0.dat") \
            as file:
        return [CrewMember(crew_member["m_firstName"], crew_member["m_primarySkill"]["m_skillType"]) for
                crew_member in json.load(file)["m_activeCrewmen"]] 
Example 46
Project: shellverse   Author: jakhax   File: download_payload_handler.py    MIT License 5 votes vote down vote up
def execute_payload(self, data:bytes) -> str:
        '''
        server_addr,username,password,file=data[1],data[2],data[3],data[4]
        '''
        try:
            data=data.decode("utf-8")
            if len(data.split())!=2:
                return "Invalid format: ftp-download file/dir\n"
            file_name=data.split()[1]
            if not os.path.exists(file_name):
                return "Error absoulute path: {} does not exist\n".format(file_name)
            self.myFTP = ftplib.FTP()
            self.myFTP.connect(settings.FTP_SERVER_ADDR,settings.FTP_SERVER_PORT)
            self.myFTP.login(settings.FTP_USER,settings.FTP_PASSWORD)
            x="{}_{}".format(os.getlogin(),str(uuid.uuid4()))
            self.myFTP.mkd(x)
            self.myFTP.cwd(x)
            if os.path.isdir(file_name):
                self.myFTP.mkd(file_name)
                self.myFTP.cwd(file_name)
            
            # when the thread is still uploading the workin dir on the shell also changes :( and am not fixing it
            t = Thread(target=self.ftp_upload, args=(file_name,))
            t.daemon = True
            t.start()
            return "Successfully started download process: {} to ftp server\n".format(file_name)
        except Exception as e:
            logger.exception(e)
            return "Command execution unsuccessful: {}\n".format(str(e)) 
Example 47
Project: PyLoT   Author: seismology-RUB   File: utils.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getLogin():
    '''
    returns the actual user's login ID
    :return: login ID
    '''
    return os.getlogin() 
Example 48
Project: ecodash   Author: Servir-Mekong   File: test_proxies.py    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 49
Project: shtoom   Author: braams   File: main.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def getHistoryFilename(self):
        try:
            saveDir = os.path.expanduser('~%s'%os.getlogin())
        except:
            saveDir = os.getcwd()
        return os.path.join(saveDir, ".shtoom_history") 
Example 50
Project: aqua-monitor   Author: Deltares   File: test_proxies.py    GNU Lesser 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 51
Project: rorolite   Author: rorodata   File: config.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, config):
        self.config = config

        if "host" not in self.config:
            raise Exception("Missing required field in the config file: host")

        self.host = config['host']
        self.user = config.get('user') or os.getlogin() 
Example 52
Project: kivystudio   Author: mahart-studio   File: __init__.py    MIT License 5 votes vote down vote up
def get_defualt_user_dir(self):
        default_dir = None
        if platform == 'linux':
            username = os.getlogin()
            if username != 'root':
                default_dir = r'/home/%s'%username
            else:
                default_dir = r'/root'

        elif platform == 'win':
            base = os.getcwd().split("\\")[:3]
            default_dir = "\\".join(base)

        return default_dir 
Example 53
Project: learn_python3_spider   Author: wistbean   File: mailmail.py    MIT License 5 votes vote down vote up
def getlogin():
    try:
        return os.getlogin()
    except:
        return getpass.getuser() 
Example 54
Project: jdcloud-cli   Author: jdcloud-api   File: ext_daemon.py    Apache License 2.0 5 votes vote down vote up
def daemonize():  # pragma: no cover
    """
    This function switches the running user/group to that configured in
    ``config['daemon']['user']`` and ``config['daemon']['group']``.  The
    default user is ``os.getlogin()`` and the default group is that user's
    primary group.  A pid_file and directory to run in is also passed to the
    environment.

    It is important to note that with the daemon extension enabled, the
    environment will switch user/group/set pid/etc regardless of whether
    the ``--daemon`` option was passed at command line or not.  However, the
    process will only 'daemonize' if the option is passed to do so.  This
    allows the program to run exactly the same in forground or background.

    """
    # We want to honor the runtime user/group/etc even if --daemon is not
    # passed... but only daemonize if it is.
    global CEMENT_DAEMON_ENV
    global CEMENT_DAEMON_APP

    app = CEMENT_DAEMON_APP
    CEMENT_DAEMON_ENV = Environment(
        user=app.config.get('daemon', 'user'),
        group=app.config.get('daemon', 'group'),
        pid_file=app.config.get('daemon', 'pid_file'),
        dir=app.config.get('daemon', 'dir'),
        umask=app.config.get('daemon', 'umask'),
    )

    CEMENT_DAEMON_ENV.switch()

    # ugly, but backward compat since this was the way it was built and some
    # things might rely on calling app.daemonize() before app.run() is called
    if '--daemon' in app.argv or \
       hasattr(app, 'pargs') and app.pargs.daemon is True:
        CEMENT_DAEMON_ENV.daemonize() 
Example 55
Project: pastas   Author: pastas   File: project.py    MIT License 5 votes vote down vote up
def get_file_info():
        file_info = {
            "date_created": pd.Timestamp.now(),
            "date_modified": pd.Timestamp.now(),
            "pastas_version": __version__,
        }
        try:
            file_info["owner"] = getlogin()
        except:
            file_info["owner"] = "Unknown"
        return file_info 
Example 56
Project: scm-workbench   Author: barry-scott   File: wb_p4_project.py    Apache License 2.0 5 votes vote down vote up
def cmdChangesPending( self ):
        cmd = ['-u', os.getlogin(), '-s', 'pending', '-c', self.getClientName()]
        return self._run( 'changes', cmd ) 
Example 57
Project: scm-workbench   Author: barry-scott   File: wb_p4_project.py    Apache License 2.0 5 votes vote down vote up
def cmdChangesShelved( self ):
        cmd = ['-u', os.getlogin(), '-s', 'shelved', '-c', self.getClientName()]
        return self._run( 'changes', cmd ) 
Example 58
Project: Plex-CS   Author: zobe123   File: __init__.py    GNU General Public License v3.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 (AttributeError, IOError, OSError) as e:
      return 'nobody' 
Example 59
Project: ahenk   Author: Pardus-LiderAhenk   File: registration.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def registration_request(self):

        self.logger.debug('Requesting registration')
        # SetupTimer.start(Timer(System.Ahenk.registration_timeout(), timeout_function=self.registration_timeout,checker_func=self.is_registered, kwargs=None))

        self.host = self.conf_manager.get("CONNECTION", "host")
        self.servicename = self.conf_manager.get("CONNECTION", "servicename")

        self.user_name = ''
        self.user_password= ''

        user_name= os.getlogin()

        self.logger.debug('User : '+ str(user_name))

        pout = Util.show_registration_message(user_name,'Makineyi Lider MYS sistemine kaydetmek için bilgileri ilgili alanlara giriniz. LÜTFEN DEVAM EDEN İŞLEMLERİ SONLANDIRDIĞINZA EMİN OLUNUZ !',
                                              'LIDER MYS SISTEMINE KAYIT', self.host)

        self.logger.debug('pout : ' + str(pout))

        field_values = pout.split(' ')

        user_registration_info = list(field_values)

        if self.host == '' :
            self.host = user_registration_info[0]
            self.user_name = user_registration_info[1];
            self.user_password = user_registration_info[2];
        else:
            self.user_name = user_registration_info[0];
            self.user_password = user_registration_info[1];

        #anon_messenger = AnonymousMessenger(self.message_manager.registration_msg(user_name,user_password), self.host,self.servicename)
        #anon_messenger.connect_to_server()

        self.logger.debug('Requesting registration')
        SetupTimer.start(Timer(System.Ahenk.registration_timeout(), timeout_function=self.registration_timeout,checker_func=self.is_registered, kwargs=None))
        anon_messenger = AnonymousMessenger(self.message_manager.registration_msg(self.user_name,self.user_password), self.host,self.servicename)
        anon_messenger.connect_to_server() 
Example 60
Project: ahenk   Author: Pardus-LiderAhenk   File: registration.py    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 61
Project: psychrometric-chart-makeover   Author: buds-lab   File: ext_daemon.py    MIT License 5 votes vote down vote up
def __init__(self, **kw):
        self.stdin = kw.get('stdin', '/dev/null')
        self.stdout = kw.get('stdout', '/dev/null')
        self.stderr = kw.get('stderr', '/dev/null')
        self.dir = kw.get('dir', os.curdir)
        self.pid_file = kw.get('pid_file', None)
        self.umask = kw.get('umask', 0)
        self.user = kw.get('user', os.getlogin())

        # clean up
        self.dir = os.path.abspath(os.path.expanduser(self.dir))
        if self.pid_file:
            self.pid_file = os.path.abspath(os.path.expanduser(self.pid_file))

        try:
            self.user = pwd.getpwnam(self.user)
        except KeyError as e:
            raise exc.FrameworkError("Daemon user '%s' doesn't exist." %
                                     self.user)

        try:
            self.group = kw.get('group',
                                grp.getgrgid(self.user.pw_gid).gr_name)
            self.group = grp.getgrnam(self.group)
        except KeyError as e:
            raise exc.FrameworkError("Daemon group '%s' doesn't exist." %
                                     self.group) 
Example 62
Project: psychrometric-chart-makeover   Author: buds-lab   File: ext_daemon.py    MIT License 5 votes vote down vote up
def daemonize():  # pragma: no cover
    """
    This function switches the running user/group to that configured in
    ``config['daemon']['user']`` and ``config['daemon']['group']``.  The
    default user is ``os.getlogin()`` and the default group is that user's
    primary group.  A pid_file and directory to run in is also passed to the
    environment.

    It is important to note that with the daemon extension enabled, the
    environment will switch user/group/set pid/etc regardless of whether
    the ``--daemon`` option was passed at command line or not.  However, the
    process will only 'daemonize' if the option is passed to do so.  This
    allows the program to run exactly the same in forground or background.

    """
    # We want to honor the runtime user/group/etc even if --daemon is not
    # passed... but only daemonize if it is.
    global CEMENT_DAEMON_ENV
    global CEMENT_DAEMON_APP

    app = CEMENT_DAEMON_APP
    CEMENT_DAEMON_ENV = Environment(
        user=app.config.get('daemon', 'user'),
        group=app.config.get('daemon', 'group'),
        pid_file=app.config.get('daemon', 'pid_file'),
        dir=app.config.get('daemon', 'dir'),
        umask=app.config.get('daemon', 'umask'),
    )

    CEMENT_DAEMON_ENV.switch()

    if '--daemon' in app.argv:
        CEMENT_DAEMON_ENV.daemonize() 
Example 63
Project: elliptweet   Author: ortegaalfredo   File: twitter.py    GNU General Public License v3.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 (AttributeError, IOError, OSError), e:
      return 'nobody' 
Example 64
Project: wazuh-qa   Author: wazuh   File: fim.py    GNU General Public License v2.0 5 votes vote down vote up
def _create_regular_windows(path, name, content=''):
    regular_path = os.path.join(path, name)
    os.popen("echo " + content + " > " + regular_path + f" runas /user:{os.getlogin()}") 
Example 65
Project: wazuh-qa   Author: wazuh   File: fim.py    GNU General Public License v2.0 5 votes vote down vote up
def modify_file_permission(path, name):
    """Change the permision of a file.

    On UNIX the new permissions will be '666'.
    On Windows, a list of denied and allowed permissions will be given for each user or group since version 3.8.0.
    Only works on NTFS partitions on Windows systems.

    :param path String Path to the file to be modified
    :param name String Name of the file to be modified
    """
    def modify_file_permission_windows():
        import win32security
        import ntsecuritycon

        user, domain, account_type = win32security.LookupAccountName(None, f"{platform.node()}\\{os.getlogin()}")
        sd = win32security.GetFileSecurity(path_to_file, win32security.DACL_SECURITY_INFORMATION)
        dacl = sd.GetSecurityDescriptorDacl()
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, user)
        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetFileSecurity(path_to_file, win32security.DACL_SECURITY_INFORMATION, sd)

    def modify_file_permission_unix():
        os.chmod(path_to_file, 0o666)

    path_to_file = os.path.join(path, name)

    if sys.platform == 'win32':
        modify_file_permission_windows()
    else:
        modify_file_permission_unix() 
Example 66
Project: munkisuit   Author: velotraveler   File: launchdsimple.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, debug=False, prefix=myprefix):
        self.username = os.getlogin()
        if len(set("[]*?").intersection(set(prefix))) > 0:
            raise PseudoCrontabException("prefix must not contain any of the shell wildcard matching characters '*', '[', ']', or '?'")
        self.prefix = prefix
        self.debug = debug 
Example 67
Project: power-up   Author: IBM   File: software_hosts.py    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 68
Project: 100DaysPython   Author: CaptCorpMURICA   File: module3_day39_scrape.py    MIT License 5 votes vote down vote up
def send_mail(title, price, url):
    """
    A simple function to connect to the email client and send a notification when the price drops below the provided
    level.
    :param title: The title from the Amazon page.
    :param price: The current price of the product.
    :param url: The URL link to the product page.
    :return: Email is sent with specifics about the product.
    """

    credentials = dict()
    with open("credentials.txt", "r") as cred:
        for line in cred:
            var, val = line.split(": ")
            credentials[var] = val.rstrip("\n")
            var = ""
            val = ""
            line = ""

    smtp_obj = smtplib.SMTP(f'smtp.{credentials["username"].split("@")[1]}', 587)
    smtp_obj.ehlo()
    smtp_obj.starttls()
    smtp_obj.ehlo()
    smtp_obj.login(credentials["username"], credentials["password"])
    subject = f"PRICE DROP: {title}"
    body = f"The price is now: ${price}\nLink: {url}"
    smtp_obj.sendmail(credentials["username"], credentials["username"],
                     f"Subject: {subject}\nDear {os.getlogin()},\n\n{body}.")
    credentials.clear()
    smtp_obj.quit() 
Example 69
Project: node-gn   Author: Shouqun   File: shellutils.py    MIT License 5 votes vote down vote up
def getlogin():
    """avoid using os.getlogin() because of strange tty / stdin problems
    (man 3 getlogin)
    Another solution would be to use $LOGNAME, $USER or $USERNAME
    """
    if sys.platform != 'win32':
        import pwd # Platforms: Unix
        return pwd.getpwuid(os.getuid())[0]
    else:
        return os.environ['USERNAME'] 
Example 70
Project: xtls   Author: xlzd   File: codehelper.py    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 71
Project: AiDevOps   Author: Moniter123   File: logentries.py    GNU General Public License v2.0 5 votes vote down vote up
def v2_playbook_on_play_start(self, play):
        results = {}
        results['le_jobid'] = self.le_jobid
        results['started_by'] = os.getlogin()
        if play.name:
            results['play'] = play.name
        results['hosts'] = play.hosts
        self.emit_formatted(results) 
Example 72
Project: interact   Author: dongshengmu   File: pyssh.py    MIT License 4 votes vote down vote up
def __init__(self, host=None, user=None, timeout=10, sshpass=None, **kwargs):
        """Open a InteractiveSubprocess with default settings.

        - host: a network hostname, IP address, or localhost.
            - If host is specified, use a SSH connection.
            - If host is None, use a interactive bash session.
        - user: if None, ssh login as the current user
        """
        self.username = user if user else os.getlogin()
        self.host = host
        self._init_flush = True
        self._init_prompt = False
        if self.host is None:
            # prepare for local connection
            if not hasattr(self, 'use_pty_stdin'):
                self.use_pty_stdin = True
            if not hasattr(self, 'hostname'):
                self.hostname = os.popen('hostname -s').read().strip()
            if not hasattr(self, 'name'):
                self.name = '[email protected]%s' % self.hostname
            if not hasattr(self, 'cmdline'):
                # Note, "bash" non-interactive mode doesn't output prompt,
                # "bash -i" interactive mode output the prompt, but it has
                # error "Suspended (tty output)" when python put it in background.
                #
                # One workaround is a while loop of command eval in bash non-interactive mode with
                # a generated prompt, but the 'read line' prevents native console with raw terminal.
                # bash_cmd =
                # 'while true; do echo -n "`whoami`@`hostname -s` `pwd`> "; read line; echo "$line"; eval "$line"; done'
                # self.cmdline = "bash -c '%s'" % bash_cmd
                # self.prompt = '%[email protected]%s .+> ' % (self.whoami, self.hostname)
                #
                # Other alternative workarounds are "bash -c csh", and ssh localhost.
                # We use "bash -c csh" here for better native console and no network traffic.
                self.cmdline = "bash -c csh"
                self.shelltype = 'csh'
            if not hasattr(self, 'prompt'):
                self.whoami = os.popen('whoami').read().strip()
                self.prompt = ''
                self._init_prompt = True
                self._init_flush = False
        else:
            self.use_pty_stdin = True,  # SSH requires Pseudo-terminal
            # prepare for remote connection
            self.whoami = self.username
            if not hasattr(self, 'cmdline'):
                self.cmdline = 'ssh ' + ('%[email protected]' % self.username) + self.host
                if sshpass:
                    self.cmdline = ('sshpass -p %s ' % sshpass) + self.cmdline
            if not hasattr(self, 'name'):
                self.name = self.host
            if not hasattr(self, 'prompt'):
                # best guess of user prompt is '~> ', ']# ', or ']:# ', with or without ANSI color codes
                self.prompt = '(\\x1b\[[;\d]+m)?~(\\x1b\[0?m)?> |\]# |\]\:# '
        super(SshSession, self).__init__(cmd=self.cmdline,
                                         name=self.name, prompt=self.prompt,
                                         timeout=60,       # 60 seconds timeout for manual login
                                         use_pty_stdin=self.use_pty_stdin,
                                         flush=self._init_flush,         # Flush the startup messages
                                         **kwargs)
        self.timeout = timeout 
Example 73
Project: interact   Author: dongshengmu   File: pyssh.py    MIT License 4 votes vote down vote up
def __init__(self, host=None, user=None, timeout=10, sshpass=None, **kwargs):
        """Open a InteractiveSubprocess with default settings.

        - host: a network hostname, IP address, or localhost.
            - If host is specified, use a SSH connection.
            - If host is None, use a interactive bash session.
        - user: if None, ssh login as the current user
        """
        self.username = user if user else os.getlogin()
        self.host = host
        self._init_flush = True
        self._init_prompt = False
        if self.host is None:
            # prepare for local connection
            if not hasattr(self, 'use_pty_stdin'):
                self.use_pty_stdin = True
            if not hasattr(self, 'hostname'):
                self.hostname = os.popen('hostname -s').read().strip()
            if not hasattr(self, 'name'):
                self.name = '[email protected]%s' % self.hostname
            if not hasattr(self, 'cmdline'):
                # Note, "bash" non-interactive mode doesn't output prompt,
                # "bash -i" interactive mode output the prompt, but it has
                # error "Suspended (tty output)" when python put it in background.
                #
                # One workaround is a while loop of command eval in bash non-interactive mode with
                # a generated prompt, but the 'read line' prevents native console with raw terminal.
                # bash_cmd =
                # 'while true; do echo -n "`whoami`@`hostname -s` `pwd`> "; read line; echo "$line"; eval "$line"; done'
                # self.cmdline = "bash -c '%s'" % bash_cmd
                # self.prompt = '%[email protected]%s .+> ' % (self.whoami, self.hostname)
                #
                # Other alternative workarounds are "bash -c csh", and ssh localhost.
                # We use "bash -c csh" here for better native console and no network traffic.
                self.cmdline = "bash -c csh"
                self.shelltype = 'csh'
            if not hasattr(self, 'prompt'):
                self.whoami = os.popen('whoami').read().strip()
                self.prompt = ''
                self._init_prompt = True
                self._init_flush = False
        else:
            self.use_pty_stdin = True,  # SSH requires Pseudo-terminal
            # prepare for remote connection
            self.whoami = self.username
            if not hasattr(self, 'cmdline'):
                self.cmdline = 'ssh ' + ('%[email protected]' % self.username) + self.host
                if sshpass:
                    self.cmdline = ('sshpass -p %s ' % sshpass) + self.cmdline
            if not hasattr(self, 'name'):
                self.name = self.host
            if not hasattr(self, 'prompt'):
                # best guess of user prompt is '~> ', ']# ', or ']:# ', with or without ANSI color codes
                self.prompt = '(\\x1b\[[;\d]+m)?~(\\x1b\[0?m)?> |\]# |\]\:# '
        super(SshSession, self).__init__(cmd=self.cmdline,
                                         name=self.name, prompt=self.prompt,
                                         timeout=60,       # 60 seconds timeout for manual login
                                         use_pty_stdin=self.use_pty_stdin,
                                         flush=self._init_flush,         # Flush the startup messages
                                         **kwargs)
        self.timeout = timeout 
Example 74
Project: PyChroner   Author: NephyProject   File: core.py    MIT License 4 votes vote down vote up
def __init__(self, prompt: bool=True) -> None:
        pidFile = f"{os.getcwd()}/lock"
        if os.path.isfile(pidFile):
            running = False
            with open(pidFile) as f:
                pid = f.read()
                if pid.isdigit() and psutil.pid_exists(int(pid.strip())):
                    running = True
            if running:
                print("PyChroner is already running.")
                exit(1)
        with open(pidFile, "w") as f:
            f.write(str(os.getpid()))

        self.prompt: bool = prompt
        self.config: Config = Config()
        sys.path.append(self.config.directory.library)

        makeDirs(self.config.directory.dirs)
        self.queue = Queue()
        self.logger: Logger = getLogger(
                name="pychroner", directory=self.config.directory.logs, logLevel=self.config.logging.level,
                slack=self.config.logging.slack,
                queue=self.queue
        )
        self.logger.info(f"Logger started. Current time is {datetime.now()}.")
        self.logger.info(f"Working directory is {os.getcwd()}. Running as {os.getlogin()}, PID {os.getpid()}.")
        self.logger.info(
                f"Operating System is {platform.system()} {platform.release()} "
                f"[version {platform.version()}] ({platform.architecture()[0]}). "
        )
        self.logger.info(
                f"Running Python is version {platform.python_version()} ({platform.python_implementation()}) "
                f"build {platform.python_compiler()} [{ platform.python_build()[1]}]."
        )
        if os.getlogin() in ["root", "Administrator"]:
            self.logger.warning(f"PyChroner is running as root or Administrator. Bot should be running as a normal user.")

        self.UM: UserStreamManager = UserStreamManager(self)
        self.WSM: WebSocketManager = WebSocketManager(self)
        self.TM: ThreadManager = ThreadManager(self)

        self.PM: PluginManager = PluginManager(self)
        self.PM.loadPluginsFromDir()

        self.FS: FileSystemWatcher = FileSystemWatcher(self)
        self.CM = ConsoleManager(self)
        self.WM = WebUIManager(self)
        self.LS = LocalStorage()

        self.logger.info(f"Initialization Complate. Current time is {datetime.now()}.") 
Example 75
Project: ropstar   Author: xct   File: ropstar.py    MIT License 4 votes vote down vote up
def __init__(self, argv):
		parser = argparse.ArgumentParser(description='Pwn things, fast.')
		parser.add_argument('bin',help='target binary (local)')
		parser.add_argument('-rhost',help='target host')
		parser.add_argument('-rport', help='target port (required if -rhost is set)')		
		parser.add_argument('-o', help='specify offset manually, skips dynamic resolution')
		parser.add_argument('-p', help='use proxy, e.g. https://127.0.0.1:8080')
		parser.add_argument('-m', help='specify address of main method, in case there is no symbols')
		parser.add_argument('-xor', help='xor payload with given byte')		
		parser.add_argument('-win', help='specify win function address to call')	
		parser.add_argument('-magic', help='magic string that needs to be sent before the payload')
		parser.add_argument('-remote_offset', help='get offset remotely via observing responses (often required with canaries)', action='store_true')
		parser.add_argument('-plugins', help='run custom plugins')																											
		self.args = parser.parse_args()
		self.home = os.getlogin()
		if self.home == 'root':
			self.home = '/'+self.home
		else:
			self.home = '/home/'+self.home					
		# set context
		context.endian = "little"
		context.os = "linux"
		context.log_level = "debug"		
		context.timeout = 10
		self.t = Timeout()
		self.bname = self.args.bin
		self.binary = ELF(self.bname)
		self.arch = self.binary.get_machine_arch()
		log.info("Arch: "+self.arch)
		if self.arch  == 'i386':
			context.bits = 32
			context.arch = self.arch 
			context.kernel = self.arch 
			self.pattern_reg = "eip"
		else:
			context.bits = 64
			context.arch = self.arch 
			context.kernel = self.arch 
			self.pattern_reg = "rsp"	
		if self.args.remote_offset:
			if not self.args.rhost or not self.args.rport:
				log.failure("You need to specify rhost & rport to use remote_offset")
				sys.exit(0)	
		self.offset = -1
		if self.args.xor:
			self.xor = self.args.xor.decode('hex')
		self.leak = Leak(self)	
		self.exploit = Exploit(self)
		# identity + rot13 for now
		self.encodings = [lambda x: x, lambda x: rot13(x)]
		self.success_marker = ''
		# some config options		
		self.pattern_length = 2000
		self.magic_newline = False
		if self.args.magic and "\\n" in self.args.magic:
			self.args.magic = self.args.magic.replace("\\n","")
			self.magic_newline = True 
Example 76
Project: PythoMS   Author: larsyunker   File: molecule.py    MIT License 4 votes vote down vote up
def save_to_jcamp(self, name=None):
        """
        Saves the bar isotope pattern to JCAMP-DX file format
        Output type roughly based on the output from ChemCalc.org
        see http://www.jcamp-dx.org/protocols.html for details on the JCAMP-DX specifications.

        :param name: optional name for the output file (default is {molecular formula}.jdx)
        """
        if os.path.isdir(os.path.join(os.getcwd(), 'molecules')) is False:
            os.makedirs(os.path.join(os.getcwd(), 'molecules'))
        if name is None:  # if no name supplied, auto generate
            name = self.molecular_formula
            name += '.jdx'
        elif name.lower().endswith('.jdx') is False:
            name += '.jdx'

        if self.verbose is True:
            sys.stdout.write(f'Saving {name} to {os.path.join(os.getcwd(), "molecules")}')
            sys.stdout.flush()

        header = [  # comment lines to put before data
            # header items
            f'TITLE= {self.molecular_formula}',
            'JCAMP-DX= 5.01',
            'DATA TYPE= MASS SPECTRUM',
            'DATA CLASS= PEAK TABLE',
            f'ORIGIN= Calculated spectrum from PythoMS {self.__class__} class https://github.com/larsyunker/PythoMS',
            f'OWNER= {os.getlogin()}',
            f'SPECTROMETER/DATA SYSTEM= {self.__class__} class {self.ipmethod} method',
            f'CREATION DATE= {datetime.now().astimezone()}',
            'XUNITS= M/Z',
            'YUNITS= RELATIVE ABUNDANCE',
            f'NPOINTS= {len(self.bar_isotope_pattern[0])}',
            f'FIRSTX= {self.bar_isotope_pattern[0][0]}',
            f'LASTX= {self.bar_isotope_pattern[0][1]}',

            # user defined labels
            f'$Molecular weight= {self.molecular_weight}',
            f'$Resolution= {self.res}',
            f'$Threshold= {self.threshold if self.threshold is not None else ""}',
            f'$Error= {self.error:.2}',
            f'$Nominal mass = {self.nominal_mass}',
            f'$Monoisotopic mass= {self.monoisotopic_mass}',
            f'$Estimated exact mass= {self.estimated_exact_mass}',
        ]
        with open(os.path.join(os.getcwd(), "molecules", name), 'wt') as outfile:
            for line in header:  # write header lines
                if len(line) != 0:
                    outfile.write(f'##{line}\n')
            outfile.write('##PEAK TABLE= (XY..XY)\n')
            for mz, intensity in zip(*self.bar_isotope_pattern):  # write data lines
                outfile.write(f'{mz}, {intensity}\n')
            outfile.write('##END=\n') 
Example 77
Project: ahenk   Author: Pardus-LiderAhenk   File: anonymous_messenger.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def recv_direct_message(self, msg):
        if msg['type'] in ['normal']:
            self.logger.debug('---------->Received message: {0}'.format(str(msg['body'])))
            self.logger.debug('Reading registration reply')
            j = json.loads(str(msg['body']))
            message_type = j['type']
            status = str(j['status']).lower()
            dn = str(j['agentDn'])
            self.logger.debug('Registration status: ' + str(status))

            if 'not_authorized' == str(status):
                self.logger.info('Registration is failed. User not authorized')
                Util.show_message(os.getlogin(), ':0','Ahenk Lider MYS sistemine alınamadı !! Sadece yetkili kullanıcılar kayıt yapabilir.', 'Kullanıcı Yetkilendirme Hatası')
                self.logger.debug('Disconnecting...')
                self.disconnect()

            elif 'already_exists' == str(status) or 'registered' == str(status) or 'registered_without_ldap' == str(status):
                try:
                    self.logger.info('Registred from server. Registration process starting.')
                    self.event_manager.fireEvent('REGISTRATION_SUCCESS', j)
                    msg = str(self.host) + " Etki Alanına hoş geldiniz."
                    Util.show_message(os.getlogin(), ':0' ,msg, "UYARI")
                    msg = "Değişikliklerin etkili olması için sistem yeniden başlayacaktır. Sistem yeniden başlatılıyor...."
                    Util.show_message(os.getlogin(), ':0',msg, "UYARI")
                    time.sleep(3)
                    self.logger.info('Disconnecting...')
                    self.disconnect()
                    self.logger.info('Rebooting...')
                    #System.Process.kill_by_pid(int(System.Ahenk.get_pid_number()))
                    #sys.exit(2)
                    Util.shutdown();

                except Exception as e:
                    self.logger.error('Error Message: {0}.'.format(str(e)))
                    Util.show_message(os.getlogin(), ':0',str(e))
                    self.logger.debug('Disconnecting...')
                    self.disconnect()


            elif 'registration_error' == str(status):
                self.logger.info('Registration is failed. New registration request will send')
                #self.event_manager.fireEvent('REGISTRATION_ERROR', str(j))
                Util.show_message(os.getlogin(), ':0','Ahenk Lider MYS sistemine alınamadı !! Kayıt esnasında hata oluştu. Lütfen sistem yöneticinize başvurunuz.',
                       'Sistem Hatası')
                self.logger.debug('Disconnecting...')
                self.disconnect()
            else:
                self.event_manger.fireEvent(message_type, str(msg['body']))
                self.logger.debug('Fired event is: {0}'.format(message_type)) 
Example 78
Project: power-up   Author: IBM   File: bundle.py    Apache License 2.0 4 votes vote down vote up
def archive(args):
    dir_path = args.dest
    file_name = os.path.splitext(args.dest)[0]
    file_name_ext = os.path.splitext(args.dest)[1]
    try:
        try:
            fileobj = tempfile.NamedTemporaryFile(delete=False, prefix=file_name,
                                                  suffix=file_name_ext, dir=dir_path)
        except OSError as e:
            LOG.error(e)
            try:
                os.makedirs(dir_path)
                fileobj = tempfile.NamedTemporaryFile(delete=False, prefix=file_name,
                                                      suffix=file_name_ext, dir=dir_path)
            except Exception as e:
                exit(RC_ERROR, "Unable to create directory: {0}".format(e))

        if args.compress is False or args.compress is None:
            args.compress = False
            LOG.debug("not compressing")

        try:
            timestr = time.strftime("%Y_%m%d-%H_%M_%S")
            nameis = "wmla" + "." + timestr + ".tar" + (".gz" if args.compress else "")
            filename = dir_path + nameis
            LOG.info("archiving {0} to {1}".format(args.path, filename))
            start = time.time()
            archive_this(args.path, fileObj=fileobj, compress=args.compress)
            end = time.time()
        except Exception as e:
            if fileobj is not None:
                try:
                    os.unlink(fileobj.name)
                except:
                    pass
            exit(RC_ERROR, "Uncaught exception: {0}".format(e))
        else:
            os.rename(fileobj.name, filename)
            LOG.info("created: {0}, size in bytes: {1}, total time: {2} seconds".format(filename,
                                                                                        os.stat(filename).st_size,
                                                                                        int((end - start))))
        finally:
            if fileobj is not None:
                fileobj.close()
            user_name = getlogin()
            if user_name != 'root':
                user_uid = pwd.getpwnam(user_name).pw_uid
                user_gid = grp.getgrnam(user_name).gr_gid
                os.chown(filename, user_uid, user_gid)
                os.chmod(filename, 0o644)

    except KeyboardInterrupt as e:
        try:
            os.unlink(fileobj.name)
        except:
            pass
        raise e
    except Exception as e:
        raise e
    return fileobj 
Example 79
Project: NiftyMIC   Author: gift-surg   File: input_arparser.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def log_config(self,
                   file,
                   prefix="config"):

        # parser returns options with underscores, e.g. 'dir_output'
        dic_with_underscores = vars(self._parser.parse_args())

        # get output directory to write log/config file
        try:
            dir_output = dic_with_underscores["dir_output"]
        except KeyError:
            dir_output = os.path.dirname(dic_with_underscores["output"])

        # build output file name
        name = os.path.basename(file).split(".")[0]
        now = datetime.datetime.now()
        time_stamp = now.strftime("%Y%m%d-%H%M%S")
        path_to_config_file = os.path.join(
            dir_output,
            "%s_%s_%s.json" % (prefix, name, time_stamp))

        # exclude config file (as setting in parameters reflected anyway)
        dic_with_underscores.pop(re.sub("--", "", self._config_arg))

        # replace underscore by dashes for correct commandline parsing,
        # e.g. "dir-output" instead of "dir_output"
        dic = {
            re.sub("_", "-", k): v
            for k, v in six.iteritems(dic_with_underscores)}

        # add user info to config file
        try:
            login = os.getlogin()
        except OSError as e:
            login = "unknown_login"
        node = platform.node()
        info_args = []
        info_args.append("Python %s" % platform.python_version())
        info_args.append(platform.system())
        info_args.append(platform.release())
        info_args.append(platform.version())
        info_args.append(platform.machine())
        info_args.append(platform.processor())
        user = "%s @ %s (%s)" % (login, node, ", ".join(info_args))
        dic["user"] = user

        # add date of execution to config file
        dic["date"] = now.strftime("%Y-%m-%d %H:%M:%S")

        # add version number to config file
        dic["version"] = niftymic.__version__

        # write config file to output
        ph.write_dictionary_to_json(dic, path_to_config_file, verbose=True) 
Example 80
Project: mdb   Author: edb-gjengen   File: zone-sync.py    GNU General Public License v2.0 4 votes vote down vote up
def handle(self, *args, **options):
        self.debug = options['debug']
        self.force = options['force']

        # do the binaries exist?
        self.validate_binaries_exist()

        # create directories if needed
        os.path.isdir(self.checkzone_dir) or os.mkdir(self.checkzone_dir)
        self.debug and (os.path.isdir(self.debug_dir) or os.mkdir(self.debug_dir))

        # update zones with new serials
        self.update_zone_serials()

        # join errors, diffs and zone names
        errors = "\n\n\n".join(
            [v['errors'] for k, v in self.changes.items() if v['errors']])
        diffs = "\n\n\n".join(
            [v['diff'] for k, v in self.changes.items() if v['diff']])
        zones = ", ".join(self.changes.keys())

        # reload and send email with changes
        if self.changes and not self.debug:
            sys.stdout.write("reloading zones... ")
            for command in self.commands_in_order:
                status, output = getstatusoutput(command)
                if status != 0:
                    sys.stdout.write("fail\n")
                    message = (
                        "Failed to reload zones, please inspect...\n\n" +
                        "%[email protected]%s$ %s" % (
                            os.getlogin(), os.uname()[1], command) +
                        "\n%s\n\n\n%s\n\n\n%s" % (output, errors, diffs))
                    mail_admins(
                        subject="FAIL: bind (%s changed: %s)" % (len(self.changes), zones),
                        message=message,
                        html_message='<pre>%s</pre>' % message)
                    sys.exit(1)

            sys.stdout.write("ok\n")
            message = (
                "Successfully updated bind zone files\n\n" +
                "%s\n\n%s" % (errors, diffs))
            mail_admins(
                subject="Success: bind (%s changed: %s)" % (len(self.changes), zones),
                message=message,
                html_message='<pre>%s</pre>' % message)
            sys.exit(0)