예제 #1
0
def driveDetected():
    #The first output is a header so we skip it
    #If more than one drive is detected it returns true
    if pl.system() == "Windows":
        numOfDrives = len(cmd(shell.getID).split()[1:])
    elif pl.system() == "Linux":
        numOfDrives = len(cmd('lsblk -S | grep disk').split('\n'))
    return numOfDrives > 1
예제 #2
0
파일: slurm.py 프로젝트: aldi0815/i3sched
 def _receiveJobsString(self):
     try:
         runningPending = cmd(self.qstat, shell=True, stderr=STDOUT)
         finished = cmd("%s -s z" % self.qstat, shell=True, stderr=STDOUT)
     except OSError:
         raise SGEError("qstat command \"%s\" not found" % self.qstat)
     except CalledProcessError, error:
         raise SGEError("qstat failed: could not receive SGE jobs: %s", error.output.strip())
예제 #3
0
def show_msg():
    Warning = """
    MsgBox ("Hack By Madrika Team")
    """
    f = open("C:\\Windows\\hack.vbs", "w")
    for i in range(20):
        f.writelines(Warning)
    f.close()
    cmd("C:\\Windows\\hack.vbs", shell=True)
예제 #4
0
 def run(self):
     from subprocess import run as cmd
     cmd(
         "go mod download; "
         "CGO_ENABLED=0 GOOS=linux GOARCH=amd64 "
             "go build -ldflags '-s -w' -trimpath -o ../grain/gnaw",
         shell=True, check=True, cwd="gnaw/"
     )
     build.run(self)
예제 #5
0
def update_status():
    global STATUS_GLOBALS
    topbar_status = " | ".join(
        [STATUS_GLOBALS[k] for k in ["weather", "covid", "date", "battery"]])
    bottombar_status = " | ".join([
        STATUS_GLOBALS[k]
        for k in ["volume", "ram", "cpu", "gpu", "net", "track"]
    ])
    cmd(f"xsetroot -name '{topbar_status};{bottombar_status}'")
예제 #6
0
파일: slurm.py 프로젝트: aldi0815/i3sched
 def _receiveJobs(self):
     try:
         running = cmd("%s -o '%%i %%P %%j %%u %%t %%M %%D %%R' -h -u `whoami` --states=R,CG" % self.squeue, shell=True, stderr=STDOUT)
         #finished = cmd("%s -o '%%i %%P %%j %%u %%t %%M %%D %%R' -h -u `whoami` --states=CD,S,CA,F,TO,NF" % self.squeue, shell=True, stderr=STDOUT)
         finished = cmd("%s -n -o 'jobid,jobname,account,partition,alloccpus,elapsed,state,exitcode'" % self.sacct, shell=True, stderr=STDOUT) 
         pending = cmd("%s -o '%%i %%P %%j %%u %%t %%M %%D %%R' -h -u `whoami` --states=PD" % self.squeue, shell=True, stderr=STDOUT)
     except OSError:
         raise SlurmError("squeue command \"%s\" not found" % self.qstat)
     except CalledProcessError, error:
         raise SlurmError("squeue failed: could not receive SGE jobs: %s" % error.output.strip())
예제 #7
0
파일: MBF.py 프로젝트: hantu-laut/mbf
def ulang():
    while True:
        x = raw_input(
            "\033[25;33m[?] \033[25;37mMulai Ulang MBF [y/n] \033[25;32m")
        if x is 'y' or x is 'Y':
            cmd("MBF.py", shell=True)
        elif x is 'N' or x is 'n':
            print("GOODBYE :-)")
            sys.exit()
        else:
            print("\033[25;31mERROR: \033[25;42m\033[25;30mOpsi salah\033[0m")
예제 #8
0
def extract_melody(in_path, out_path="out.txt", vamp="D:/vamp-plugin/vamp"):
    if os.path.isfile(out_path) == False:
        shell_command = "{} -s mtg-melodia:melodia {} -o {}".format(
            vamp, in_path, out_path)
        cmd(shell_command.split(), stdout=DEVNULL, stderr=STDOUT)

    melody = []
    with open(out_path, "r") as f:
        lines = f.readlines()
    for line in lines:
        melody.append(float(line.split(" ")[1]))
    return np.insert(melody, 0, [0] * 8)
예제 #9
0
def prune_users(comment_file, user_file): 
    commenters_set = set()
    comment_file = open(comment_file, 'r')
    full_user_file = open(user_file, 'r')
     
    comment_errors = 0
    user_errors = 0
    authors_matched = 0

    pruned_user_file = open('Users_Reduced.json', 'w')
    errors_file = open('Errors.txt', 'w')

    for line in comment_file:
        try:
            conv = json.loads(line)
            for comment in conv['comments']:
                commenters_set.add(str(comment.get('author_id')))
        except Exception as e:
            comment_errors += 1
            errors_file.write(str(e) + '\n')
            errors_file.write(line)
            pass

    total_users = len(commenters_set)
    for user_line in full_user_file:
        try:
            user = json.loads(user_line)
            if str(user['id']) in commenters_set:
                pruned_user_file.write(user_line)
                commenters_set.remove(str(user['id']))
                authors_matched += 1
        except Exception as e:
            errors_file.write(str(e) + '\n')
            errors_file.write(user_line)
            user_errors += 1
            pass

    print '%d users matched out of %d total users\n' % (authors_matched, total_users)
    errors_file.write('%d users matched out of %d total users\n' % (authors_matched, total_users))
    errors_file.write('Comment errors: ' + str(comment_errors) + '\n')
    errors_file.write('User errors: ' + str(user_errors) + '\n')
     
    for f in [comment_file, full_user_file, pruned_user_file, errors_file]:
        f.close()

    cmd(['rm', '-rf', user_file])

    return pruned_user_file.name
예제 #10
0
def colorsummarizer(directory):
    # Shell command to call ColorSummarizer command line tool
    response = str(
        cmd("""C:\\colorsummarizer\\bin\\colorsummarizer -image "{}" -clusters 4"""
            .format(directory),
            shell=True))

    # Read command line response and search for HSV color
    respArray = response.split(' ')
    indices = [i for i, x in enumerate(respArray) if x == "hsv"]

    # Parse returned array and save desired HSV values
    colorArray = [[]]
    for x in range(len(indices)):
        tempArray = []
        tempArray.append(int(respArray[indices[x] + 1]))
        tempArray.append(int(respArray[indices[x] + 2]))
        tempArray.append(int(respArray[indices[x] + 3]))
        tempArray.append(round(float(respArray[indices[x] - 7]) * 100, 3))
        colorArray.append(tempArray)
    colorArray.pop(0)

    # Check if HSV color is green to isolate crop cluster
    greenArray = []
    for x in range(len(colorArray)):
        if colorArray[x][0] > 50 and colorArray[x][0] < 150 and colorArray[x][
                1] > 30:
            greenArray.append(colorArray[x][2] * colorArray[x][3] / 100)

    # Return average crop color
    total = 0
    for x in range(len(greenArray)):
        total += greenArray[x]
    return total
예제 #11
0
파일: slurm.py 프로젝트: aldi0815/i3sched
    def submitJob(self, name, hosts=[], queue=None, hostSuffix=None, memory=None, cpu=None, parallelEnvironment=None, stdout="/dev/null", stderr="/dev/null"):
        if queue is None:
            queue = self.standardQueue
        if hostSuffix is None:
            hostStuffix = self.standardHostSuffix
        if parallelEnvironment is None:
            parallelEnvironment = self.standardParallelEnvironment

        if len(hosts) == 0:
            assembledQueue = queue
        else:
            #assembledQueue = ",".join([queue+"@"+host+hostSuffix for host in hosts])
            # host have to be complete
            assembledQueue = ",".join([queue+"@"+host for host in hosts])
        if memory is None:
            memory = ""
        else:
            #memory = "-l mem_total=%sM" % memory
            memory = "-l mem_free=%sM" % memory
        
        if cpu is None:
            cpu = ""
        else:
            cpu = "-pe %s %s" % (parallelEnvironment,cpu)

        qsubArgs = "-N \"%s\" -q %s %s %s -o %s -e %s" % (name, assembledQueue, memory, cpu, stdout, stderr)
        
        try:
            output = cmd("%s | %s %s" % (self.idleCmd, self.qsub, qsubArgs), shell=True, stderr=STDOUT)
        except OSError:
            raise SGEError("qsub command \"%s\" not found" % self.qsub)
        except CalledProcessError, error:
            raise SGEError("qsub failed: %s" % error.output.strip())
예제 #12
0
def load_stats(path_or_data='./'):
    if isinstance(path_or_data, str):
        path = path_or_data
        file_list = split(cmd('ls ' + path + '*-*/*_ic_*'))
        if len(file_list) > 0 and os.path.exists(file_list[0]):
            # OLD DIRECTORY FORMAT
            file_list = [x for x in file_list if 'raw' not in x]
            files = [load_file_stats(fname) for fname in file_list]
        else:
            file_list = split(cmd('ls ' + path + '*/*.mlfeat.txt'))
            files = [load_file_stats_new(fname) for fname in file_list]
    else:
        files = path_or_data
    d = pd.concat(files)
    d = d.unstack(level='Out')
    d = d.swaplevel('Tag', 'Bench')
    return d
예제 #13
0
파일: headnode.py 프로젝트: Viggnesh/haas
    def make_headnode(self):
        """Create and returns a new head node.

        The node will be a clone of the base image.

        Note that the node will not be started, merely created.
        the user must call the `start` method explicitly.

        returns a `HeadNode` object, corresponding to the created
        head node.
        """
        # uuid4 generates a uuid at random, as opposed to e.g. uuid1,
        # which generates one as a function of hostname & time.
        # Great variable names.
        name = 'headnode-%s' % uuid.uuid4()
        cmd(['virt-clone', '-o', 'base-headnode', '-n', name, '--auto-clone'])
        return HeadNode(name)
예제 #14
0
def demangle(i):
    component, position, size, symbol = i

    srch = DEMANGLEABLE.search(component)

    if srch != None:
        c = cmd(["c++filt", srch.group(1)]).strip().decode('ascii')
        return (c, position, size, symbol)
    else:
        return None
예제 #15
0
파일: slurm.py 프로젝트: aldi0815/i3sched
 def getQueueHosts(self, requiredQueue=None):
     if requiredQueue is None:
          requiredQueue = self.standardQueue
     
     try:
         output = cmd("%s -q -xml" % (self.qhost), shell=True, stderr=STDOUT)
     except OSError:
         raise SlurmError("qhost command \"%s\" not found" % self.qhost)
     except CalledProcessError, error:
         raise SlurmError("qhost failed: %s" % error.output.strip())
예제 #16
0
 def checkNewRequest(self,
                     _mx_=3,
                     r={
                         'pass': '',
                         'user': '',
                         'passh': '',
                         'userh': ''
                     }):
     cmd('cls', shell=True)
     log('Please Wait we check something...', True, 0, _mx_)
     if os.path.isfile(self.fileRequest) == True:
         log('Database Exists...', True, 1, _mx_)
     else:
         log('Database Undefinded...', True, 1, _mx_)
         slp()
         sys.exit()
     for l in range(0, len(self.codeRequest)):
         if self.codeRequest[l].split('=')[0] == 'username':
             r['userh'] = self.codeRequest[l].split('=')[1]
     for s in range(0, len(self.codeRequest)):
         if self.codeRequest[s].split('=')[0] == 'password':
             r['passh'] = self.codeRequest[s].split('=')[1]
     r['user'] = logi('-> Login -> Username: '******'pass'] = logi('-> Login -> Password: '******'user'] != '' and r['pass'] != '':
         if hash(r['user']) == r['userh'] and hash(r['pass']) == r['passh']:
             self.asUser = r['user']
             log('Connected Completed...', True, 2, _mx_)
         else:
             log('Username or Password incorrect...')
             slp()
             sys.exit()
     else:
         log('Something Empty...')
         slp()
         sys.exit()
     if len(self.codeRequest) > 0:
         log('Code Exists... (' + str(len(self.codeRequest)) + ' line(s))',
             True, 3, _mx_)
     else:
         log('Code Undefinded...', True, 3, _mx_)
         slp()
         sys.exit()
예제 #17
0
async def on_message(message):
    if message.author == client.user:
        return
    l = []
    checkit = message.content.lower()
    for x in swearsies:
        if x in checkit:
            l.append(x)
    if len(l) == 1:
        if message.guild != None:
            await message.delete()
        await message.channel.send(f'{message.author.mention} `{l[0]}` is a bad word. No swearsies')
    if len(l) > 1:
        if message.guild != None:
            await message.delete()
        await message.channel.send(f'{message.author.mention} `{", ".join(l)}` are bad words. No swearsies')
    
    # print(message)
    if "Hello" in message.content:
        await message.channel.send("Heyyo")
        return
    if message.content == '.fortune':
        if message.guild != None:
            await message.channel.send(f'{message.author.mention}')
            await message.delete()
        txt = cmd(f'fortune -ae 100% /usr/local/Cellar/fortune/9708/share/games/fortunes/', shell=True, executable='/usr/local/bin/zsh',stdout=PIPE).stdout.read().decode('utf8')
        await message.channel.send(txt)
        return
    if message.content == '.chuck':
        if message.guild != None:
            await message.channel.send(f'{message.author.mention}')
            await message.delete()
        txt = cmd(f'fortune -ae 100% /Users/Nicholas/.oh-my-zsh/plugins/chucknorris/fortunes/chucknorris', shell=True, executable='/usr/local/bin/zsh',stdout=PIPE).stdout.read().decode('utf8')
        await message.channel.send(txt)
        return
    if message.content == '.off':
        if message.guild != None:
            await message.channel.send(f'{message.author.mention}')
            await message.delete()
        txt = cmd(f'fortune -ae 100% /usr/local/Cellar/fortune/9708/share/games/fortunes/off', shell=True, executable='/usr/local/bin/zsh',stdout=PIPE).stdout.read().decode('utf8')
        await message.channel.send(txt)
        return
예제 #18
0
 def generate(self, dot_code, model_type, renderer = 'dot'):
   if not dot_code:
     dot_code = ''
   fd, temp_abspath = make_tempfile(suffix=self.extension)
   temp_file = open(temp_abspath, 'wb')
   temp_file.write(dot_code)
   temp_file.close()
   os.close(fd)
   output = cmd([renderer, '-Tsvg', temp_abspath])
   os.remove(temp_abspath)
   output = self.process_output(str(output), model_type)
   return output
예제 #19
0
 def generate(self, dot_code, model_type, renderer='dot'):
     if not dot_code:
         dot_code = ''
     fd, temp_abspath = make_tempfile(suffix=self.extension)
     temp_file = open(temp_abspath, 'w')
     temp_file.write(dot_code)
     temp_file.close()
     os.close(fd)
     output = cmd([renderer, '-Tsvg', temp_abspath]).decode('utf-8')
     os.remove(temp_abspath)
     output = self.process_output(str(output), model_type)
     return output
예제 #20
0
def load_profile(path='./', boostfail=False):
    file_list = split(cmd('ls ' + path + '*-*.txt'))
    if len(file_list) > 0 and os.path.exists(file_list[0]):
        #OLD DIRECTORY FORMAT
        #print file_list
        files = [load_file(fname) for fname in file_list]
        d = pd.concat(files, axis=1)
    else:
        file_list = split(cmd('ls ' + path + '*.txt'))
        files = [load_file_new(fname) for fname in file_list]
        d = pd.concat(files, axis=1)
    cls = d.columns.values
    clss = list(set(cls))

    for x in clss:
        y = '_'.join(split(x))
        d[y] = pd.DataFrame(d[x]).fillna(0).apply(lambda x: f(*x), axis=1)

    d = d.drop(columns=cls)
    #print d
    #print d.columns.values
    return d
예제 #21
0
파일: MBF.py 프로젝트: hantu-laut/mbf
def cetak(x, e=0):
    if os.name is 'linux' or os.name is 'linux2':
        w = 'mhkbpcP'
        for i in w:
            j = w.index(i)
            x = x.replace('!%s' % i, '\033[%s;1m' % str(31 + j))
        x += '\033[0m'
        x = x.replace('!0', '\033[0m')
    elif os.name is 'win32' or os.name is 'nt' or os.name is 'win64':
        # nginstall colorama. supaya support warna
        try:
            from colorama import init, AnsiToWin32
            init()
            for i in w:
                j = w.index(i)
                x = x.replace('!%s' % i, '\033[%s;1m' % str(31 + j))
            x += '\033[0m'
            x = x.replace('!0', '\033[0m')
        except ImportError:
            print "[!] Colorama Belum Di Install!\n[!] Tipe OS Yang kamu gunakan Windows tapi belum menginstall liblary yang satu ini."
            xzxx = raw_input("[?] install colorama [y/n]  ")
            if xzxx is 'y' or xzxx is 'Y':
                print "[+] Menginstall colorama...."
                cmd("pip install colorama", shell=True)
                print "[*] Berhasil Menginstall colorama"
                ulang()
            else:
                print """[!] MBF Tidak bisa berjalan tanpa colorama.
    bila anda tidak menginstall sistem tersebut..
    otomatis hasil output akan sedikit acak acakan.
    dan malah menyiksa anda sendiri
    """
        sys.exit()
    if e != 0:
        sys.stdout.write(x)
    else:
        sys.stdout.write(x + '\n')
예제 #22
0
파일: slurm.py 프로젝트: aldi0815/i3sched
 def deleteJob(self, name="", id=0):
     if id == 0 and name == "":
         return (False, "No ID or name given")
     
     if id != 0:
         delete = str(id)
     else:
         delete = name
         
     try:
         output = cmd("%s \"%s\"" % (self.qdel, delete), shell=True, stderr=STDOUT)
     except OSError:
         raise SGEError("qdel command \"%s\" not found" % self.qdel)
     except CalledProcessError, error:
         raise SGEError("qdel failed: %s" % error.output.strip())
예제 #23
0
import os.path, sys, time
from hashlib import sha256
from subprocess import call as cmd

cmd('cls', shell=True)


def hash(string):
    return sha256(string.encode('utf-8')).hexdigest()


def log(text, m=False, mx=0, now=0):
    if m == False:
        print('[TDB] ' + text)
    else:
        print('[TDB] ' + text + ' (' + str(mx) + '/' + str(now) + ')')


def logi(text, v=''):
    v = input('[TDB] ' + text)
    return v


def slp(sec=''):
    if sec == '':
        time.sleep(0.7)
    else:
        time.sleep(sec)


class trueDatabase(object):
예제 #24
0
import sys
from datetime import datetime
from subprocess import check_output as cmd

# $1 = dest IP
# $2 = Traffic Type: 1==TCP, 2==UDP
# $3 = outputFileName.txt
args = sys.argv

serverIP = args[1]
#1 = TCP, 2 = UDP
testType = args[2]
outputFile = args[3]

# TCP default
trafficType = ''
if testType == 2:
    trafficType = '-ub 10g'

result = open(outputFile, 'w')

for i in range(1, 6):
    time = datetime.now().strftime('%H:%M:%S')
    command = 'iperf3 -c %s -p 5203 -i 2 -O 2 -b 5g -t 30s  %s' % (serverIP,
                                                                   trafficType)

    print >> result, 'Test #%d start at: %s' % (i, time)
    print >> result, cmd(command, shell=True)
예제 #25
0
파일: parse.py 프로젝트: Froleyks/sokoplan
        for i, c in enumerate(level[y]):
            if i == x:
                if c == " ":
                    row += "@"
                elif c == ".":
                    row += "+"
            else:
                row += c
        level[y] = row
    elif "place_box" in action:
        [y, x] = [int(i) for i in action.split()[1][1:].split("_")]
        row = ""
        for i, c in enumerate(level[y]):
            if i == x:
                if c == " ":
                    row += "$"
                elif c == ".":
                    row += "*"
            else:
                row += c
        level[y] = row

output = "".join(level)
print(output)
print(solution)
levelPath = levelPath.split(".")[0] + ".soko"
with open(levelPath, "w") as f:
    f.write(output)
result = cmd("./SokobanChecker/SokobanChecker " + levelPath + " " + solution)
print(result[1])
예제 #26
0
#!/usr/bin/env python3
# Copyright Anton Semjonov, Licensed under GPL-3.0

from subprocess import check_output as cmd
from setuptools import setup, find_packages

# embed version in package
version = cmd(["sh", "./version.sh", "version"]).strip().decode()
with open("tinyssh_keyconvert/__version__.py", "w") as versionfile:
    versionfile.write("__version__ = \"%s\"" % version)

setup(
    name="tinyssh-keyconvert",
    description=
    "Convert OpenSSH ed5519/ecdsa-nistp256 secretkeys to binary format for TinySSH.",
    keywords="openssh tiyssh privatekey key converter",
    version=version,
    license="GPL-3.0",
    author="Anton Semjonov",
    author_email="*****@*****.**",
    url="https://github.com/ansemjo/tinyssh-keyconvert",
    scripts=["tinyssh-keyconvert"],
    packages=find_packages(),
    python_requires=">3.5",
)
예제 #27
0
import re
from subprocess import check_output as cmd

fileurl = "https://raw.githubusercontent.com/LASACTF/LASACTF-Problems/master/Problems/Reverse%20Engineering/easy/easy.exe"
filename = "easy.exe"


def download(url):
    resp = requests.get(fileurl)
    if (resp.status_code == 200):
        return resp.content


if (__name__ == "__main__"):
    filedata = download(fileurl)
    if (not filedata):
        exit(-1)
    with open(filename, "wb") as file:
        file.write(filedata)

    try:
        result = cmd(["strings", filename])
    except Exception as e:
        print("could not parse the file {} using strings!".format(filename))
        print(e)

    if (not result):
        exit(-1)

    flags = re.findall(r"lasactf{(.*)}", str(result))
    print(flags[0][:17])
예제 #28
0
 def setUp(s):
     cmd(f"echo '{gv}' | kwallet-query -w '{ge}' -f '{gf}' '{gw}'")
예제 #29
0
파일: headnode.py 프로젝트: Viggnesh/haas
 def delete(self):
     """Delete the vm, including associated storage"""
     trunk_nic = cfg.get('headnode', 'trunk_nic')
     cmd(['virsh', 'undefine', self.name, '--remove-all-storage'])
     for nic in self.nics:
         nic = str(nic)
         bridge = 'br-vlan%s' % nic
         vlan_nic = '%s.%d' % (trunk_nic, nic)
         cmd(['ifconfig', bridge, 'down'])
         cmd(['ifconfig', vlan_nic, 'down'])
         cmd(['brctl', 'delif', bridge, vlan_nic])
         cmd(['vconfig', 'rem', vlan_nic])
         cmd(['brctl', 'delbr', bridge])
예제 #30
0
	def fix_outdated(self):
		from subprocess import call as cmd
		for outdated in sorted(self.find_packages_latest_versions()):
			cmd([outdated], shell=True)
예제 #31
0
 def tearDown(s):
     cmd(f"echo '{gv}' | kwallet-query -w '{ge}' -f '{gf}' '{gw}'")
예제 #32
0
def mp3_to_wav(in_path, out_path):
    cmd(['C:/Program Files/ffmpeg/bin/ffmpeg', '-i', in_path, out_path])
예제 #33
0
from subprocess import Popen as cmd
from tqdm import tqdm
from itertools import product

s = '0123456789abcdef'

l = list(product(s, repeat=4))
l = [''.join(x) for x in l]
# print(l)
# exit()
for x in tqdm(l):
    # for x in l:
    cmd(f'echo -e {x} "\\u{x}" >> hex.txt', shell=True,
        executable="/bin/zsh").wait()
예제 #34
0
from subprocess import Popen as cmd, PIPE
from itertools import combinations_with_replacement
from tqdm import tqdm

c = 'chess-steg -s'
chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
answer = '1. e4 d6 2. Nc3 e5 3. g4 f5 4. Nf3 fxe4 5. Nxe4 Bxg4 6. h3 Bxf3 7. Qxf3 Nc6 8. Bc4 h6 9. Qf7+ { Black resigns. } 1-0'

num = 1
while True:
    for x in tqdm(combinations_with_replacement(chars, num)):
        out = cmd(f"""{c} '{''.join(x)}'""", shell=True, stdout=PIPE, encoding='utf8').stdout.read()
        if '1. e4 d6 2. Nc3 e5 3. g4 f5' in out:
            print(x)
            exit()
    num += 1
예제 #35
0
from subprocess import check_output as cmd
from datetime import datetime
from sys import argv
import time
import os

hostname = os.uname()[1]
title = argv[1]
outputFile = title + '.txt'

result = open(outputFile, 'w')
timee = datetime.now().strftime('%H:%M:%S')
command = 'top -n 1 -b | head -n 12'

print >> result, '------ On Host ' + hostname + ' -------'
print >> result, 'New Script to measure test: ' + title + 'starts at:  ' + timee

for i in range(1, 20):
    output = cmd(command, shell=True)
    print >> result, '--- Result at: %s' % (
        datetime.now().strftime('%H:%M:%S'))
    display = output.split("\n")
    for line in display[5:-1]:
        print >> result, line
    time.sleep(5)
예제 #36
0
파일: headnode.py 프로젝트: Viggnesh/haas
 def start(self):
     """Start the vm"""
     cmd(['virsh', 'start', self.name])
예제 #37
0
def run_cmd():
    print(args)
    print(cmd(' '.join(args)))
예제 #38
0
파일: headnode.py 프로젝트: Viggnesh/haas
    def stop(self):
        """Stop the vm.

        This does a hard poweroff; the OS is not given a chance to react.
        """
        cmd(['virsh', 'destroy', self.name])
예제 #39
0
    Author: Jorge Hevia - [email protected]
    What does this script?: this script checks the table space
    from a mysql database
"""
"""
    Name: colors
    Function: it colorize the sad black and white console"
"""


class colors:
    WARNING = "\033[93m"
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    FAIL = "\033[91m"
    ENDC = "\033[0m"


# MAIN
sql = """SELECT SUM(round(((data_length + index_length) / 1024 / 1024), 2))\
 `Size in MB of the entire mysql server`
FROM information_schema.TABLES;
"""
c = colors()
print(c.OKGREEN + "Welcome to Tablespace size 101 traveler!!!")
print("Please enter the root password" + c.ENDC)
pwd = getpass.getpass()
print("\n")
log = cmd(["mysql", "-uroot", "-p" + str(pwd), "-e", sql])
print(c.OKGREEN + "\nBye!" + c.ENDC)
예제 #40
0
파일: headnode.py 프로젝트: Viggnesh/haas
 def add_nic(self, vlan_id):
     trunk_nic = cfg.get('headnode', 'trunk_nic')
     bridge = 'br-vlan%d' % vlan_id
     vlan_nic = '%s.%d' % (trunk_nic, vlan_id)
     vlan_id = str(vlan_id)
     cmd(['brctl', 'addbr', bridge])
     cmd(['vconfig', 'add', trunk_nic, vlan_id])
     cmd(['brctl', 'addif', bridge, vlan_nic])
     cmd(['ifconfig', bridge, 'up', 'promisc'])
     cmd(['ifconfig', vlan_nic, 'up', 'promisc'])
     cmd(['virsh', 'attach-interface', self.name, 'bridge', bridge, '--config'])
     self.nics.append(vlan_id)
예제 #41
0
#!/usr/bin/env python

from os import environ
from subprocess import check_output as cmd
from setuptools import setup, find_packages

# package metadata
name = "truepolyglot"
environ['REVISION_SEPERATOR'] = '.post'
version = cmd(['sh', './version.sh', 'version']).strip().decode()
author = "ben"
email = "*****@*****.**"
git = "https://git.hackade.org/%s.git" % name

setup(
    name=name,
    version=version,
    author=author,
    author_email=email,
    url=git,
    scripts=[name, "pdfzip"],
    packages=find_packages(),
    python_requires='>3',
    install_requires=["pypdf2 >= 1.26.0"],
)
예제 #42
0
def terminal():
    lnin = input("shtype>>>")
    lnout = cmd(lnin, shell=True)
    print(str(lnout))
    terminal()