def get_tmux_server() -> libtmux.Server: """ Returns tmux server if it's running, and starts one if it's not. """ server = libtmux.Server() try: server.list_sessions() except libtmux.exc.LibTmuxException: print_blue("Starting tmux server...") # Apparently, there is no way to start a server without any sessions # (https://github.com/tmux/tmux/issues/182). So, we're going to spawn a # new server, create a dummy session and then kill it later. I'm sorry. hack_session = "zsh-startify-tmux-server-hack" start_server_hack = f"tmux has-session -t {hack_session} || \ tmux new-session -d -s {hack_session}" system(start_server_hack) # Sleep to give tmux some time to restore sessions if tmux-resurrect or # tmux-continuum is used # TODO: Make this sleep value configurable in .zshrc sleep_with_spinner(5) server = libtmux.Server() # Kill the hacky tmux session we just started. get_tmux_session(server, hack_session).kill_session() return server
def _getServer(self, name, firstWindow=""): try: s = tmuxp.Server() s.list_sessions() except Exception as e: if firstWindow == "": j.tools.cuisine.local.tmux.createSession(name, ["ignore"]) else: j.tools.cuisine.local.tmux.createSession(name, [firstWindow]) s = tmuxp.Server() s.list_sessions() return s
def __init__(self): self.tmux = libtmux.Server() try: self.tmux.list_sessions() except: print("Starting new tmux server") subprocess.call( "tmux new -s temp -d", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, ) self.tmux = libtmux.Server() start_core_vm()
def init_ops(f=example_file, operation='ansible'): server = libtmux.Server() if operation == 'ssh': # get dict with machine-info and ssh-commands (key = ssh) target_dict = tmc_ssh.create_ssh_commands(f) elif operation == 'ansible': target_dict = tmc_ansible_v1.create_ansible_v1_commands( '/home/dey25201/Projekte/Talanx/ansible') elif operation == 'foo': # target_dict = tmc_foo.create_foo_commands() pass # add window-names and -ids to target-dict (window_id, window_name) # also actually creates ops-session and the windows print >> sys.stderr, "%s" % (target_dict) try: target_dict = tmc_session_manager.create_windows(target_dict) #session = server.find_where({ "session_name": "tmc_ops" }) #pane_id = 1 #for el in target_dict: # window = session.find_where({ "window_name": el['window_name']}) # pane = window.select_pane('%{0}'.format(pane_id)) # pane = pane.select_pane() # pane.send_keys(el['cmd']) # pane_id += 1 except (Exception, ), e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print >> sys.stderr, "### Unexpected exception: '%s' [%s] in file '%s' at line: %d" % ( str(e), exc_type, fname, exc_tb.tb_lineno)
def kill_tmux_session(session_name: str): """Find and kill this session""" server = libtmux.Server() if server and server.has_session(session_name): logger.info('%s Killing the running tmux session "%s" ...' % (settings.TERM_LBL, session_name)) call(["tmux", "kill-session", "-t", session_name])
def server(self): def start(): cmd = "/sandbox/bin/js_mux start" j.sal.process.execute(cmd, die=True) time.sleep(0.1) if self._server is None: rc, out, err = j.core.tools.execute("tmux ls", die=False) if rc > 0: if err.find("No such file or directory") != -1: start() rc, out, err = j.core.tools.execute("tmux ls", die=False) if err.find("no server running") != -1: start() rc, out, err = j.core.tools.execute("tmux ls", die=False) if rc > 0: raise RuntimeError("could not execute tmux ls\n%s" % err) if out.strip().count("\n") > 0: j.shell() raise RuntimeError("found too many tmux sessions, there should only be 1") rc, out, err = j.sal.process.execute("tmux -f /sandbox/cfg/.tmux.conf has-session -t main", die=False) if rc > 0: j.shell() raise RuntimeError("did not find tmux session -t main") self._server = tmuxp.Server() time.sleep(1) self._log_info("tmux server is running") return self._server
def connect_and_run(self, key): self.running = True logging.info('Creating launch file for tintin++...') with open('dr.tin', 'w') as tt_file: tt_file.write(f'#ses dr prime.dr.game.play.net 4901;{key};;') tt_file.write(''' #nop Global Variables #var \{CURRENT_RT\} \{0\}; #nop Global Roundtime Tracker #action \{%?Roundtime: %1 sec%+\} \{ #var CURRENT_RT %1; \ #var rtn @roundtime\{\}; #unvar $rtn; \ #delay \{roundtime\} \{#showme <118>Roundtime complete.; \} \{%1\} \} #action \{%?Roundtime %1 sec%+\} \{ #var CURRENT_RT %1; \ #var rtn @roundtime\{\};#unvar $rtn; \ #delay \{roundtime\} \{#showme <118>Roundtime complete.;\} \{%1\} \} #read tt/highlight.conf #read tt/function.conf #nop #read tt/prompt.conf''') logging.info('Creating clean tmux server "dr-tmux-server"... ') server = libtmux.Server(socket_name='dr-tmux-server') session = server.new_session('dr-window') window = session.select_window(0) pane = window.select_pane(0) logging.info('Starting up DragonRealms via tintin++ client and re-attaching...') log_name = f"{self.log_prefix}_{time.strftime('%Y%m%d-%H%M%S')}.raw" log_path = os.path.join('tt/temp', log_name) pane.send_keys('tt++ dr.tin', enter=True) time.sleep(30) pane.send_keys('#config log plain', enter=True) pane.send_keys(f'#log overwrite {log_path}', enter=True) logging.info(f'tintin++ is now logging to {log_path}') pane.send_keys('inhale', enter=True) seconds_recording = 0 while self.running: # pulse every 3 minutes if seconds_recording % 180 == 0: pane.send_keys('scrib', enter=True) time.sleep(5) seconds_recording += 5 # Upload to discord channel channel = discord.utils.get(self.bot.get_all_channels(), id=int(self.upload_channel_id)) pane.send_keys('nod', enter=True) pane.send_keys('wave', enter=True) pane.send_keys('exit') logging.info('DR Cleanly exited. Killing tmux...') server.kill_server() self.running = False return log_path
def __init__(self): signal.signal(signal.SIGINT, lambda signal, frmae: self._signal_handler()) self.server = libtmux.Server() # find current tmux session name current_session_name = os.popen("tmux display-message -p '#S'").read().strip('\n') self.session = self.server.find_where({'session_name': current_session_name}) self.window_name = 'running_loggers'
def init_tmux(): tmux_server = libtmux.Server() tmux_sess = tmux_server.list_sessions()[-1] tmux_win = tmux_sess.attached_window less_pane = tmux_win.split_window(attach=False) return less_pane
def __enter__(self): # pylint: disable=attribute-defined-outside-init self._server = libtmux.Server() self._session = self._server.new_session( session_name=self._session_name, start_directory=self._cwd, kill_session=True ) self._window = self._session.new_window(self._window_name) self._pane = self._window.panes[0] self._pane.split_window(attach=False) # split vertical self._pane.split_window(vertical=False, attach=False) # attached to upper left self._pane.set_height(self._pane_height) self._pane.set_width(self._pane_width) # send the config envvar + other set up commands venv = "source $VIRTUAL_ENV/bin/activate" navigator_config = f"export ANSIBLE_NAVIGATOR_CONFIG={self._config_path}" set_up_commands = [venv, navigator_config] + self._setup_commands set_up_command = " && ".join(set_up_commands) self._pane.send_keys(set_up_command) # get the cli prompt from pane self._cli_prompt = self._get_cli_prompt() return self
def setUpClass(cls): # Create a temporary Tmux server for testing. libtmux.Server(socket_name=_TEST_SERVER).kill_server() cls.mock_server_name = mock.patch.object(tmux.cluster, '_SERVER_NAME', new=_TEST_SERVER) cls.mock_server_name.start()
async def tmux(args): last_contest = None if args.contest: last_contest = os.path.join(work_dir, args.contest) else: last_contest = Infer.latest_in_dir() cont = Infer.infer_dir(last_contest) server = libtmux.Server() name = "cf-" + cont.contest session = None try: session = server.find_where({'session_name': name}) except libtmux.exc.LibTmuxException: session = None if session == None: session = server.new_session(session_name=name, detach=True) else: print("Error, session already found ", session) # session = server.new_session(session_name=name, detach=True) for d in os.listdir(last_contest): w = session.new_window(attach=False, window_name=d) comp = w.split_window(attach=False, vertical=False) code = w.attached_pane code.send_keys('cd ' + os.path.join(last_contest, d)) comp.send_keys('cd ' + os.path.join(last_contest, d)) comp.send_keys('cmpc main.cpp', enter=False) code.send_keys('vim main.cpp')
def run_session(self): print('-' * 80) os.system("cd " + self.work_dir) #print(self.data) server = libtmux.Server() session = server.new_session(session_name="session_test", kill_session=True, attach=False) session = server.find_where({"session_name": "session_test"}) window = session.new_window(attach=True, window_name="session_test") pane1 = window.attached_pane pane2 = window.split_window(vertical=True) window.select_layout('tiled') #time.sleep(3) if self.emon: pane1.send_keys('timeout 45 ./../dsa_micros/src/dsa_micros ' + self.command) pane2.send_keys('timeout 40 python2 emon.py -w ' + str(self.dir) + "/" + self.emon_dir) pane1.send_keys('sleep 5') else: pane1.send_keys('./../dsa_micros/src/dsa_micros ' + self.command) pane1.send_keys('sleep 5') pane1.send_keys('tmux kill-session -t session_test') server.attach_session(target_session="session_test")
def handle_julia_intent(self): self.acknowledge() session_name = "Julia_Voice_Programer" skill_dir = "/opt/mycroft/skills/mycroft-julia-skill-2.calacuda/" call = f"{skill_dir + 'term.sh'} {session_name} {mycroft_python_dir}" #call = f"./term.sh {session_name} {mycroft_python_dir}" self.repl = subprocess.Popen(call, shell=True) time.sleep(0.1) #print("repl : ", self.repl) connected = False #while not connected: for i in range(10): print("looking for the tmux server") try: self.tmux_server = libtmux.Server(session_name) self.session = self.tmux_server.find_where( {"session_name": session_name}) # connected = True print(self.tmux_server.list_sessions()) except libtmux.exc.LibTmuxException: time.sleep(0.1) else: print("found tmux server") connected = True break if not connected: self.speak("there was an error connecting ot the tmux session") return False print("free willie") self.window = self.session.attached_window self.pane = self.window.attached_pane self.speak("your julia console is ready sir") return True
def multi(self, pattern): if '*' not in pattern: pattern += '*' hosts = SuperSSH.ssh_host_filter(pattern) if not hosts: print("Not match any hosts") exit() server = libtmux.Server() session = server.new_session( session_name='ssh-%s-%d' % (pattern.replace("*", ""), random.randint(1000, 9999)), ) w1 = session.attached_window w1.move_window(99) w = session.new_window(attach=True, ) for i, host in enumerate(hosts, start=1): if i == 1: p = w.attached_pane else: p = w.split_window( attach=False, target=p.id, ) p.send_keys("printf '\\033]2;%s\\033\\\\'" % host) p.cmd("set", "pane-border-format", "#{pane_index} #T") p.cmd("set", "pane-border-status", "top") p.send_keys('ssh %s && exit' % host) p.send_keys('clear') w1.kill_window() w.cmd("set", "synchronize-panes") session.set_option('mouse', True) session.set_option('main-pane-height', 300) w.select_layout(self.layout) session.attach_session()
def run_session(self): print('-' * 80) os.system("cd " + self.spdk_work_dir) #print(self.data) server = libtmux.Server() session = server.new_session(session_name="session_test", kill_session=True, attach=False) session = server.find_where({"session_name": "session_test"}) window = session.new_window(attach=True, window_name="session_test") pane1 = window.attached_pane pane2 = window.split_window(vertical=True) if self.spdk_top: pane4 = window.split_window(vertical=True) window.select_layout('tiled') pane1.send_keys(self.spdk_work_dir + '/build/examples/accel_perf ' + self.command) time.sleep(3) pane2.send_keys(self.spdk_work_dir + '/scripts/rpc.py idxd_scan_accel_engine -c 0') pane2.send_keys(self.spdk_work_dir + '/scripts/rpc.py framework_start_init') if self.spdk_top: pane4.send_keys(self.spdk_work_dir + '/build/bin/spdk_top') pane1.send_keys('tmux kill-session -t session_test') server.attach_session(target_session="session_test")
def main(_): tmux_sess_name = FLAGS.sess_name tmux_win_name = FLAGS.new_win_name cmd_str = FLAGS.cmd.lstrip('\"').rstrip('\"') print('sending command to tmux sess {}'.format(tmux_sess_name)) print(cmd_str) # find or create the session tmux_server = libtmux.Server() tmux_sess = None try: tmux_sess = tmux_server.find_where({'session_name': tmux_sess_name}) except: pass if tmux_sess is None: tmux_sess = tmux_server.new_session(tmux_sess_name) # create new window/pane, get it and send the command tmux_sess.new_window(window_name=tmux_win_name) pane = tmux_sess.windows[-1].panes[0] # run the command if len(cmd_str) < 512: pane.send_keys(cmd_str, suppress_history=False) else: # tmux may reject too long command # so let's write it to a temp file, and run it in tmux tmp_file_path = _long_cmd_to_tmp_file(cmd_str) tmp_cmd_str = ["cat {}".format(tmp_file_path), "sh {}".format(tmp_file_path)] pane.send_keys("\n".join(tmp_cmd_str), suppress_history=False) #pos.unlink(tmp_file_path) print("done sending command to tmux.")
def tmux(self): ''' tought Maybe split tmux with a collum on the left side running a iteractive program showing open connections. Selecting a connection and pressing enter would send apropiate tmux commands to show shell of that session on right section of the screen''' ncat = "ncat -U /{0}/{1}/{2}.s".format(self.locatie, self.addr[0], self.addr[1]) tmuxcreate = "tmux -S {0}/tmux new -s netcat -d".format(self.locatie) tmuxsendkeys = "tmux -S {0}/tmux send-keys -t netcat.0 \ \"{1}\" ENTER".format(self.locatie, ncat) if not os.path.exists("{0}/tmux".format(self.locatie)): os.system(tmuxcreate) os.system(tmuxsendkeys) print("you can now connect to: {0}/tmux using \"tmux -S\"".format( self.locatie)) else: try: tmux = libtmux.Server("", "{0}/tmux".format(self.locatie)) time.sleep(1) tmux_session = tmux.find_where({"session_name": "netcat"}) window = tmux_session.new_window(attach=False) pane = window.select_pane(1) pane.send_keys(ncat) except: os.system(tmuxcreate) os.system(tmuxsendkeys)
def start(): """Start the background processes. Will raise an exception if already running. """ server = libtmux.Server(socket_name=TMUX_SOCKET_NAME) session = server.find_where({"session_name": TMUX_SESSION_NAME}) ## Ensure the session is not currently running if session: raise ProcessAlreadyRunningError() print("Starting background session...") session = server.new_session(session_name=TMUX_SESSION_NAME, start_directory=_replay_dir()) ## Start the epics IOC print("Starting EPICS IOC...") epics_win = session.new_window(window_name="epics", start_directory=EPICS_DIR, attach=False, window_shell=EPICS_CMD) print(" ...Waiting 10s") time.sleep(10) ## Start runinfod print("Starting runinfod...") runinfod_win = session.new_window(window_name="runinfod", start_directory=_replay_dir(), attach=False, window_shell=RUNINFOD_CMD) print("Background processess started.")
def handle(self, *args, sudo_pwd="", **kwargs): tmux_server = libtmux.Server() tmux_session = tmux_server.find_where( {"session_name": settings.TMUX_SESSION_NAME} ) restart_frequency = ( settings.PROCESS_RESTART_INTERVAL_IN_SECONDS / settings.STATUS_MONITORING_INTERVAL_IN_SECONDS ) logger.info( "I will restart processes after %d status check(s)..." % restart_frequency ) monitoring_count = 0 while True: start_time = time.time() monitor_tmux_windows(tmux_session) sleep_until_interval_is_complete( start_time, settings.STATUS_MONITORING_INTERVAL_IN_SECONDS ) monitoring_count += 1 if monitoring_count == restart_frequency: restart_airomon_ng(tmux_session, sudo_pwd) monitoring_count = 0 print()
def get_tmux_session_info(session_name: str) -> TmuxSessionInfo: tmux = libtmux.Server() name2_regex = re.compile(r'^%s-\d+$' % re.escape(session_name)) # find the primary/secondary sessions by name sess1: libtmux.Session = None sess2: libtmux.Session = None for sess in tmux.list_sessions(): if sess.get('session_name') == session_name: if sess1 is not None: raise Exception('Multiple tmux sessions with name {!r}'.format( session_name)) sess1 = sess elif name2_regex.match(sess.get('session_name')): if sess2 is not None: logging.warn('Found multiple secondary tmux sessions') else: sess2 = sess if not sess1: raise SessionNotFound("Couldn't find session %r" % name_re) # noqa info = SessionInfo(session_name, Platforms.TERMINAL_TMUX) info.setPrimaryTmuxSession(TmuxSessionInfo.loadFromLibtmuxSession(sess1)) info.addOtherSession(TmuxSessionInfo.loadFromLibtmuxSession(sess2)) return info
def get_slash_tmux_session(session_name): try: tmux_server = libtmux.Server() return tmux_server.find_where({"session_name":session_name}) except libtmux.exc.LibTmuxException: _logger.debug('No tmux server is running') return
def run_yaml(self, cfg='./goodluck/test/default.yaml', name=None, exit=True, wait=False, v=True, vv=True): self.v = v self.vv = vv if self.v or self.vv: self.logger.vinfo() assert os.path.exists(cfg), "The configuration doesn't exist" with open(cfg) as f: exp_dict = yaml.load(f) session_name = name if name else cfg.split('/')[-1].replace('.', '_') server = libtmux.Server() # import pdb;pdb.set_trace() session = get_session(server, session_name) for i, (exp_name, kwargs) in enumerate(exp_dict.items()): if i==0: session.attached_window.rename_window(exp_name) #Rename the name of window 0 else: window = session.new_window(attach=True, window_name=exp_name) pane = session.attached_pane ssh_command = self.get_command(**kwargs) pane.send_keys(ssh_command) if exit: print("The opened session will be closed.") time.sleep(5) server.kill_session(session_name)
def wrap(self, cmd='', exit=False, env=None, virt_env=False): server = libtmux.Server() # Summarize cmd to get the session name cmd_name = cmd if ';' in cmd_name: cmd_name = cmd_name.split(';')[-1] else: cmd_name = cmd_name session_name = cmd_name.split(' ')[0] + '_' + datetime.now().strftime("%Y-%m-%d_%H_%M_%S") print(f"Session name: {session_name}") log_with_color(f"tmux attach -t {session_name}", fore=Fore.YELLOW) session = get_session(server, session_name) session.set_option("status", "off") pane = session.attached_pane if env: if virt_env: assert os.path.exists(env), "The virtual environment doesn't exist" pane.send_keys('source {self.env}') else: pane.send_keys(f"source activate {env}") if len(cmd)>0: python_cmd = f"""goodluck run_program '{cmd}' """ pane.send_keys(python_cmd) if exit: pane.send_keys("exit") else: os.system(f"unset TMUX;tmux attach -t {session_name}")
def start_gdb_in_tmux_pane(command): import libtmux server = libtmux.Server() if server is None: raise Exception("Tmux server not found") sessions = server.list_sessions() if len(sessions) != 1: raise Exception( "There should be only one tmux session running") session = server.list_sessions()[0] window = session.attached_window # type: libtmux.Window pane = window.attached_pane # Note: multiply by two since most monospace fonts are taller than wide vertical = int(pane.height) * 2 > int(pane.width) self.verbose_print("Current window h =", window.height, "w =", window.width) self.verbose_print("Current pane h =", window.attached_pane.height, "w =", window.attached_pane.width) if self.config.pretend: self.info("Would have split current tmux pane", "vertically." if vertical else "horizontally.") self.info("Would have run", coloured(AnsiColour.yellow, command), "in new pane.") else: pane = pane.split_window(vertical=vertical, attach=False) pane.send_keys(command)
def main(start, ntraj): s = libtmux.Server() env_id = start while (env_id < 10): try: t = load_occ_table(env_id) # print(t) except: pass print("env{}, size:{}".format(env_id, len(t))) if len(t) < ntraj and s.find_where( {"session_name": "linjun_{}".format(env_id)}) is None: os.system("bash run.sh {env_id}".format(env_id=env_id)) elif len(t) >= ntraj: for i in range(10): if s.find_where({"session_name": "linjun_{}".format(i)}) is not None: s.find_where({ "session_name": "linjun_{}".format(i) }).kill_session() print("env {} finished.".format(env_id)) env_id += 2 else: time.sleep(60)
def run_cmds_local(cmds, tmux_sess_name, tmux_win_name): print('sending command to tmux sess {}'.format(tmux_sess_name)) print("\n".join(cmds)) # find or create the session tmux_server = libtmux.Server() tmux_sess = None try: tmux_sess = tmux_server.find_where({'session_name': tmux_sess_name}) except: pass if tmux_sess is None: tmux_sess = tmux_server.new_session(tmux_sess_name) # create new window/pane, get it and send the command tmux_sess.new_window(window_name=tmux_win_name) pane = tmux_sess.windows[-1].panes[0] # run the command pre_cmds = _RUN_WORKER_LOCAL_PRE_CMDS cmd_str = "\n".join(pre_cmds + cmds) if len(cmd_str) < 512: pane.send_keys(cmd_str, suppress_history=False) sleep(0.6) else: # tmux may reject too long command # so let's write it to a temp file, and run it in tmux cmd_str = "\n".join(cmds) tmp_file_path = _long_cmd_to_tmp_file(cmd_str) tmp_cmd_str = pre_cmds + [ "cat {}".format(tmp_file_path), "sh {}".format(tmp_file_path) ] pane.send_keys("\n".join(tmp_cmd_str), suppress_history=False) sleep(0.7) #pos.unlink(tmp_file_path) print("done.\n")
def _getServer(self, name, firstWindow="ignore"): try: s = tmuxp.Server() s.list_sessions() except Exception as e: session1 = s.new_session(firstWindow) return s
def main(): session = libtmux.Server().list_sessions()[0] session.attached_window.split_window(vertical=False) for i, p in enumerate(session.attached_window.children): p.clear() p.send_keys("python ./timing-federate{}.py".format(i+1)) p.enter()
def __init__(self): if TMUX.__instance is not None: raise Exception("This class is a singleton!") else: self._sessions = {} self._server = libtmux.Server() TMUX.__instance = self