Exemple #1
0
 def screenutil(self):
     host = socket.gethostname()
     list_screens()
     s = Screen('session1', True)
     s.send_commands('bash')
     s.send_commands('ls')
     s.enable_logs()
     s.send_commands("df")
     s.expect('\@%s' % host)
     print((s.before))
     print(next(s.logs))
def get_screens(component_name):
    screens = []
    for screen in list_screens():
        #print screen
        if component_name.lower() in screen.name.lower():
            screens.append(screen)
    return screens   #['chatroom31','chatroom32']
Exemple #3
0
 def fire(self, local_only=False):
     if len(self.hosts) == 0:
         print("[fjd-recruiter] No configured workers that I could search for!")
         return
     for host in self.hosts:
         if host['name'] == 'localhost':
             fired = 0
             for s in [s for s in list_screens()\
                       if s.name.startswith(self.project)]:
                 s.kill()
                 fired += 1
             if fired > 0:
                 for f in os.listdir('{}/workerqueue'.format(self.wdir)):
                     os.remove('{}/workerqueue/{}'.format(self.wdir, f))
                 print('[fjd-recruiter] Fired {} worker(s) in project "{}".'\
                         .format(fired, self.project))
             elif debug:
                 print('[fjd-recruiter] No workers busy (yet) in project "{}".'\
                         .format(self.project))
         elif not local_only:
             # for remote hosts, call the recruiter over there
             ssh_client = mk_ssh_client(host['name'], getuser())
             print("[fjd-recruiter] Host {}: {}".format(host['name'],
                     ssh(ssh_client, 'fjd-recruiter --local-only --project {} fire'\
                               .format(self.project)).strip().replace('\n', '\n        ....')))
 def __get_screens(self, component_name):
     screens = []
     for screen in list_screens():
         #print screen
         if component_name.lower() in screen.name.lower():
             screens.append(screen)
     return screens  #['chatroom31','chatroom32']
Exemple #5
0
 def search_ridx_screen(self):
     for sc in list_screens():
         self.dbg("Found screen: "+ sc.name)
         if (sc.name == self.cfg_idx_scr_name):
             self.dbg("Indexer Screen found")
             return sc
     syslog("RedisIndexerScreen was not found")
     sys.exit(1)
Exemple #6
0
 def search_ridx_screen(self):
     for sc in list_screens():
         self.dbg("Found screen: " + sc.name)
         if (sc.name == self.cfg_idx_scr_name):
             self.dbg("Indexer Screen found")
             return sc
     syslog("RedisIndexerScreen was not found")
     sys.exit(1)
    def __call__(self, parser, namespace, values, option_string = None):
        global has_args
        has_args = True
        for screen in list_screens():
            if screen.name == "mcs-{0}".format(values):
                print("Minecraft server {0} already spawned.".format(values))
                return

        call(["screen", "-dmS", "mcs-{0}".format(values), MCSERVER_WRAPPER, values])
        sleep(0.05)
        success = False
        for screen in list_screens():
            if screen.name == "mcs-{0}".format(values):
                success = True
                break
        if success:
            print("Successfully spawned minecraft server {0}.\n'$ screen -r mcs-{0}' to attach the screen.".format(
                values))
        else:
            print("Failed to spawn minecraft server {0}.".format(values))
def handler(signum = None, frame = None):
    global EXIT_FLAG
    global args
    if signum == 2 and not WAITING_FOR_RESTART:
        print("Will spawn process again.")
        EXIT_FLAG = False
        return
    print("Will not spawn process again.")
    EXIT_FLAG = True
    for screen in list_screens():
        if screen.name == "mcs-{0}".format(args.ident):
            screen.send_commands("")
            screen.send_commands("stop")
            screen.send_commands("end")
            return
 def __call__(self, parser, namespace, values, option_string = None):
     global has_args
     has_args = True
     success = False
     if len(values) <= 1:
         print("There must be at least 2 arguments.")
         return
     for screen in list_screens():
         if screen.name == "mcs-{0}".format(values[0]):
             success = True
             screen.send_commands("")
             screen.send_commands(" ".join(values[1:]))
     if success:
         print("Successfully sent '{0}' to minecraft server {1}.".format(" ".join(values[1:]), values[0]))
     else:
         print("Minecraft server {0} not found.".format(values[0]))
 def __call__(self, parser, namespace, values, option_string = None):
     global has_args
     has_args = True
     success = False
     for screen in list_screens():
         if screen.name == "mcs-{0}".format(values):
             cmd = "ps aux | grep {0}$ | grep python | grep {1} " \
                   "| grep -v grep | awk '{{print $2}}'".format(values, MCSERVER_WRAPPER)
             result = check_output(cmd, shell = True).decode()
             pid = int(result)
             while screen.exists:
                 call(["kill", str(pid)])
                 sleep(1)
             success = True
             break
     if success:
         print("Successfully terminated minecraft server {0}.".format(values))
     else:
         print("Minecraft server {0} not found.".format(values))
Exemple #11
0
 def __init__(self):
     for screen in list_screens():
         if screen.name.startswith("autopwn"):
             screen.kill()
Exemple #12
0
#!/usr/bin/env python3

from os import path
from os import system
import psutil
import time
import subprocess
from screenutils import list_screens, Screen

list_screens()
def kill_daemons():
    for screen in list_screens():
        print("Killing {}".format(screen))
        screen.kill()
Exemple #14
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 15 10:49:19 2019

@author: matteo
"""

import argparse
import screenutils as su

parser = argparse.ArgumentParser(
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--name',
                    help='First characters of screens to kill',
                    type=str,
                    default='hello')
args = parser.parse_args()

screens = su.list_screens()
for screen in screens:
    if screen.name.startswith(args.name):
        screen.kill()
Exemple #15
0
                % file_path,
                quit=True)
        if type(screens["configurations"]) != dict:
            error("<screens> entry in configuration file %s is not valid" %
                  file_path,
                  quit=True)
        screens_dict = screens["configurations"]
    elif args.name and args.cmd:
        screens_dict = {args.name: defaults}
    else:
        error(
            "You need to specify a configuration file or at least a screen name (--name) and a command (--cmd)"
        )
        exit()

    screens_list = list_screens()

    for name, screen in screens_dict.items():
        screen = {x: replace_envs(y) for x, y in screen.items()}
        active = screen["active"]
        screen_name = screen["name"]

        if not active:
            info("Screen configuration <%s> is DISABLED" % screen_name)
            continue

        for key, value in defaults.items():
            if not key in screen or screen is None:
                screen[key] = value
                info("Set default key <%s> to <%s>" % (key, value))
Exemple #16
0
 def __init__(self):
    # Kill screen sessions. Needs improvement
    for screen in list_screens():
       if screen.name.startswith("autopwn"):
          screen.kill()
 def __keep_screen(self, component_name):
     if component_name not in list_screens():
         screen = Screen(component_name, True)
         return screen
     else:
         return component_name
Exemple #18
0
 def get_screens(self):
     for screen in list_screens():
         if self.component_name.lower() in screen.name.lower():
             return screen
     return
 def get_screens(self):
     for screen in list_screens():
         if self.component_name.lower() in screen.name.lower():
             return screen
     return
Exemple #20
0
 def __init__(self):
     # Kill screen sessions. Needs improvement
     for screen in list_screens():
         if screen.name.startswith("autopwn"):
             screen.kill()
# -*- coding:utf-8 -*-
"""Screen module."""

from screenutils import list_screens, Screen
import time

# kill known open screens
screens = list_screens()
print(screens)
for screen in screens:
    print(screen.name)
    if screen.name in ['session1', 'session2']:
        screen.kill()

# s1
session_Name = 'session1'
s1 = Screen(session_Name, True)

if not s1.exists:
    raise RuntimeError("ERROR: Session not started: %s" % session_Name)

time.sleep(5000)
# funky prompts could reduce log visibility. Use sh or bash for best results
s1.send_commands('bash')
s1.enable_logs()
s1.send_commands("df")
print(next(s1.logs))

s1.disable_logs()

# s1 = None
Exemple #22
0
 def __init__(self):
    for screen in list_screens():
       if screen.name.startswith("autopwn"):
          screen.kill()
if __name__ == '__main__':
    rooms_path = '/home/room/server'
    components_name = sys.argv[1]
    segment = sys.argv[2]
    if len(sys.argv) < 3:
        print 'segment error! '
        sys.exit(1)
    if len(sys.argv) > 3:
        range_type = sys.argv[3]
        components_list = get_components_list(components_name,range_type)
    else:
        components_list = get_components_list(components_name)

    for component_name in components_list:
        if component_name not in list_screens():
            NewScreen(component_name)
        for screen in get_screens(component_name):

            if segment == 'start':
                # if not isalived(screen.name):
                #     path = getpwd(rooms_path,screen.name)
                #     screen.send_commands('cd '+  path)
                #     screen.send_commands('./'+component_name)
                #     print '%s started success!' % component_name
                print start(rooms_path,component_name,screen)
            elif segment == 'stop':
                 # if isalived(screen.name):
                 #     component_process = isalived(screen.name)
                 #     component_process.kill()
                 #     print '%s stopped success' % component_name
Exemple #24
0
                _c += '--' + str(p).strip() + '=' + str(row[p]).strip() + ' '
        # Add the exit command to terminate the experiment
        _c += '&& exit'
        cmds.append(_c)
    scr = Screener()
    scr.run(cmds, name=args.name)

elif args.command == 'view':
    from baselines.common.sacred_utils import load_runs, filter_runs
    from baselines.common import colorize
    assert args.name is not None, "Provide an experiment name."
    assert args.dir is not None, "Provide a directory for experiment."
    rule = re.compile(args.name + '_*')
    # Get all screens
    all_active_screens = 0
    for s in list_screens():
        if rule.match(s.name):
            all_active_screens += 1
    # Load runs to get active ones
    runs = load_runs(args.dir)
    running_runs = filter_runs({'run.status': 'RUNNING'}, runs)
    print(colorize("==========================================", color='red'))
    max_eta, max_duration = None, None
    for key in running_runs.keys():
        run = running_runs[key]
        print(colorize('Run:', color='blue'),
              "{0} ({1})".format(key, run['config']['env']))
        print("\t" + colorize("Steps:", color='blue') + "{0}/{1}".format(
            len(run['metrics']['EpRewMean']['steps']) +
            1, run['config']['max_iters']) + "\t\t" +
              colorize("Reward:", color='blue') +
Exemple #25
0
def main(args=None):
    # start_time = time.time()

    print(type(list_screens()))