Exemplo n.º 1
0
    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 == "")
Exemplo n.º 2
0
Arquivo: test.py Projeto: ahhentz/sh
    def test_output_equivalence(self):
        from sh import whoami

        iam1 = whoami()
        iam2 = whoami()

        self.assertEqual(iam1, iam2)
Exemplo n.º 3
0
Arquivo: test.py Projeto: ahhentz/sh
    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 == "")
Exemplo n.º 4
0
    def test_output_equivalence(self):
        from sh import whoami

        iam1 = whoami()
        iam2 = whoami()

        self.assertEqual(iam1, iam2)
Exemplo n.º 5
0
Arquivo: test.py Projeto: swayf/sh
    def test_no_arg(self):
        import pwd
        from sh import whoami

        u1 = whoami().strip()
        u2 = pwd.getpwuid(os.geteuid())[0]
        self.assertEqual(u1, u2)
Exemplo n.º 6
0
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
Exemplo n.º 7
0
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
Exemplo n.º 8
0
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()
Exemplo n.º 9
0
    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)
Exemplo n.º 10
0
Arquivo: test.py Projeto: ahhentz/sh
    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)
Exemplo n.º 11
0
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')
Exemplo n.º 12
0
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()
Exemplo n.º 13
0
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')
Exemplo n.º 15
0
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
Exemplo n.º 16
0
"""
<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:'))
Exemplo n.º 17
0
#!/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!
Exemplo n.º 18
0
 def test_no_arg(self):
     import pwd
     from sh import whoami
     u1 = whoami().strip()
     u2 = pwd.getpwuid(os.geteuid())[0]
     self.assertEqual(u1, u2)
Exemplo n.º 19
0
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!'))
Exemplo n.º 20
0
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
Exemplo n.º 21
0
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)
Exemplo n.º 22
0
Arquivo: tk.py Projeto: tl2a/Tk_app
    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)
Exemplo n.º 23
0
 def username(self) -> str:
     return str(sh.whoami()).strip()
Exemplo n.º 24
0
    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())