def test_with_context_args(self): from sh import whoami import getpass py = create_tmp_test(""" import sys import os import subprocess from optparse import OptionParser parser = OptionParser() parser.add_option("-o", "--opt", action="store_true", default=False, dest="opt") options, args = parser.parse_args() if options.opt: subprocess.Popen(args[0], shell=False).wait() """) with python(py.name, opt=True, _with=True): out = whoami() self.assertTrue(getpass.getuser() == out.strip()) with python(py.name, _with=True): out = whoami() self.assertTrue(out == "")
def test_output_equivalence(self): from sh import whoami iam1 = whoami() iam2 = whoami() self.assertEqual(iam1, iam2)
def test_no_arg(self): import pwd from sh import whoami u1 = whoami().strip() u2 = pwd.getpwuid(os.geteuid())[0] self.assertEqual(u1, u2)
def extract_config(): def git_sha(base=''): try: return str(sh.git('rev-parse', 'HEAD', _cwd=base)).strip() except Exception: return 'NA' config = c = {} versions = v = {} v['bloscpack'] = bp.__version__ v['blosc'] = blosc.__version__ v['numpy'] = np.__version__ v['joblib'] = jb.__version__ v['tables'] = tables.__version__ v['conda'] = str(sh.conda('--version', _tty_in=True)).strip() v['python'] = str(sh.python('--version', _tty_in=True)).strip() hashes = h = {} h['bloscpack'] = git_sha(os.path.dirname(bp.__file__)) h['joblib'] = git_sha(jb.__path__[0]) h['blosc'] = git_sha(blosc.__path__[0]) h['numpy'] = git_sha(np.__path__[0]) h['tables'] = git_sha(tables.__path__[0]) h['benchmark'] = git_sha() c['uname'] = str(sh.uname('-a')).strip() c['hostname'] = str(sh.hostname()).strip() c['whoami'] = str(sh.whoami()).strip() c['date'] = str(sh.date()).strip() c['versions'] = versions c['hashes'] = hashes return config
def extract_config(): def git_sha(base=''): try: return str(sh.git('rev-parse', 'HEAD', _cwd=base)).strip() except Exception: return 'NA' config = c = {} versions = v = {} v['bloscpack'] = bp.__version__ v['numpy'] = np.__version__ v['joblib'] = jb.__version__ v['conda'] = str(sh.conda('--version', _tty_in=True)).strip() v['python'] = str(sh.python('--version', _tty_in=True)).strip() hashes = h = {} h['bloscpack'] = git_sha(os.path.dirname(bp.__file__)) h['joblib'] = git_sha(jb.__path__[0]) h['numpy'] = git_sha(np.__path__[0]) h['benchmark'] = git_sha() c['uname'] = str(sh.uname('-a')).strip() c['hostname'] = str(sh.hostname()).strip() c['whoami'] = str(sh.whoami()).strip() c['date'] = str(sh.date()).strip() c['versions'] = versions c['hashes'] = hashes return config
def default_shell(name): """ Sets default shell for the current user. """ spinner = Halo(text="Default shell `{}`".format(name), spinner="dots", placement="right") spinner.start() try: path = sh.which(name).strip() user = sh.whoami().strip() with Authentication(): sh.chsh("-s", path, user) spinner.succeed() except sh.ErrorReturnCode as err: err_message = "\n\t" + err.stderr.replace("\n", "\n\t") logging.error("Error changing default shell to %s: %s", name, err_message) spinner.fail()
def test_with_context(self): from sh import whoami import getpass py = create_tmp_test(""" import sys import os import subprocess print("with_context") subprocess.Popen(sys.argv[1:], shell=False).wait() """) cmd1 = python.bake(py.name, _with=True) with cmd1: out = whoami() self.assertTrue("with_context" in out) self.assertTrue(getpass.getuser() in out)
def main(private_server_ip): ''' If the user agrees, configure postfix on this computer to work with their GoodCrypto server. ''' if sh.whoami().strip() != 'root': print('') print('ERROR: You must be root to run this program.') exit() print('') print('GoodCrypto.com') response = input('Integrate postfix with your GoodCrypto private server (y/N)? ') if response.lower().startswith('y'): configure(private_server_ip) else: print('Canceled integration')
def default_shell(name): """ Sets default shell for the current user. """ spinner = Halo( text="Default shell `{}`".format(name), spinner="dots", placement="right" ) spinner.start() try: path = sh.which(name).strip() user = sh.whoami().strip() with Authentication(): sh.chsh("-s", path, user) spinner.succeed() except sh.ErrorReturnCode as err: err_message = "\n\t" + err.stderr.replace("\n", "\n\t") logging.error( "Error changing default shell to %s: %s", name, err_message ) spinner.fail()
def read_user_email(): """ Reads user's email from system config files. Returns: str: The user's email, or None if not found. """ email = None try: username = whoami().stdout.strip() email = sed( grep( dscl(".", "-read", "/Users/" + username), "EMailAddress" ), "s/EMailAddress: //" ) except ErrorReturnCode: pass return email
def main(private_server_ip): ''' If the user agrees, configure postfix on this computer to work with their GoodCrypto server. ''' if sh.whoami().strip() != 'root': print('') print('ERROR: You must be root to run this program.') exit() print('') print('GoodCrypto.com') response = input( 'Integrate postfix with your GoodCrypto private server (y/N)? ') if response.lower().startswith('y'): configure(private_server_ip) else: print('Canceled integration')
def read_user_fullname(): """ Reads user's full name from system config files. This function attempts to determine the current user's full name by reading system configuration files. If that is unsuccesful, None is returned. Returns: str: The user's full name, or None if not found. """ try: fullname = osascript( "-e" "long user name of (system info)" ).stdout.strip() except ErrorReturnCode: fullname = None if not fullname: try: username = whoami().stdout.strip() firstname = sed( grep( dscl(".", "-read", "/Users" + username), "FirstName" ), "s/FirstName: //" ) lastname = sed( grep( dscl(".", "-read", "/Users" + username), "LastName" ), "s/LastName: //" ) fullname = firstname + " " + lastname except ErrorReturnCode: fullname = None return fullname
""" <Python 2.7> """ """ sh < sudo pip install --user sh > Python makes a great scripting language. Sometimes using the standard os and subprocess libraries can be a bit of a headache. """ import sh print(sh.pwd()) print(sh.whoami()) #sh.mkdir('new_folder') #sh.touch('new_file.txt') print('-------------------------------------------------------------------') """ emoji :: https://pypi.org/project/emoji/ pip install emoji """ import emoji print(emoji.emojize('Python is :thumbs_up:'))
#!/usr/bin/env python3 # pip3 install sh import sh sh.pwd() #* current directory sh.mkdir('new-folder') sh.touch('new-file.txt') sh.whoami() #* username sh.echo('Hi!') #* Hi!
something = Thing(100) nothing = Thing(0) # True print(something > nothing) # False print(something < nothing) # Error #something + nothing # pprint import requests import pprint url = 'https://randomuser.me/api/?results=1' users = requests.get(url).json() pprint.pprint(users) # sh library import sh print(sh.pwd()) #sh.mkdir('new_folder') #sh.touch('new_file.txt') print(sh.whoami()) print(sh.echo('This is great!'))
find_list = args.search_string[0] for s in find_list: s = s.lower() user=None try: user = args.user except IndexError: pass signal = args.signal ps = sh.ps if user == "": user = str(sh.whoami()).strip() print "user:'******'" ps = ps.bake(["-U", user]) ps = ps.bake(["-o", "pid,%cpu,%mem,command"]) lines = str(ps()).lower().splitlines() head = lines[0] out = [] if len(lines) > 1 : out = lines[1:] out = filter( lambda x: len(x) > 0, out) out=out[:] print head
import requests import sh import datetime import logging, logging.handlers logger = logging.getLogger("agent") logger.setLevel(logging.DEBUG) logger.addHandler(logging.handlers.RotatingFileHandler("agent.log")) FORMAT = "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s" logging.basicConfig(format=FORMAT) data = { "hostname": sh.cat("/etc/hostname").stdout.decode().strip(), "username": sh.whoami().stdout.decode().strip(), "time": datetime.datetime.now().isoformat(), "stats": {} } logger.debug(str(data), extra={}) response = requests.post("http://127.0.0.1:8080/", json=data) logger.debug(response.text) logger.info(response.status_code)
app.maxsize(x + 100, y + 100) app.title("My APP") app.geometry("400x500") app.update() fix_w(app.winfo_width(), app.winfo_height()) app.configure(background='#546e7a') # app.wm_attributes('-type', 'splash') app.wm_attributes('-alpha', '.95') # Label label1 = Label(text="", fg="#e84118", bg="#546e7a", font=('FontAwesome', 30)) label1.place(relx=0.5, rely=0.3, anchor='center') ur = str(sh.whoami()).strip('\n') # str(ur) label2 = Label(text="hi " + ur + " !!", fg="#ffffff", bg="#546e7a", font=('Lobster 1.4', 30)) label2.place(relx=0.5, rely=0.4, anchor='center') label3 = Label(fg="#ffffff", bg="#546e7a", font=('Raleway', 22)) label3.place(relx=0.5, rely=0.5, anchor='center') def tim(): tm = time.strftime('%l : %M : %S') label3.config(text=tm) label3.after(200, tim)
def username(self) -> str: return str(sh.whoami()).strip()
except ErrorReturnCode: pass return email def get_email(): email = read_user_email() if not email: response = "n" else: # TODO (plemons): Add color to this and the get_fullname() prompt print( "The best I can make out, your email address is " + Fore.YELLOW + str(email) + Fore.RESET ) response = user_input("Is that correct? [Y/n]") if response.lower().startswith("n"): email = user_input("What is your email? ") return email if __name__ == "__main__": print(get_full_name()) print(get_email()) with sudo: print(whoami().stdout.strip()) print(whoami().stdout.strip())