pax_global_header 0000666 0000000 0000000 00000000064 13610364777 0014530 g ustar 00root root 0000000 0000000 52 comment=5eed1a31a2853a09b7367c59fbd1a4a0b53341df
pexpect-4.8.0/ 0000775 0000000 0000000 00000000000 13610364777 0013211 5 ustar 00root root 0000000 0000000 pexpect-4.8.0/.coveragerc 0000664 0000000 0000000 00000000047 13610364777 0015333 0 ustar 00root root 0000000 0000000 [run]
source = pexpect
parallel = True
pexpect-4.8.0/.gitignore 0000664 0000000 0000000 00000000133 13610364777 0015176 0 ustar 00root root 0000000 0000000 *.pyc
doc/_build
tests/log
build/
dist/
MANIFEST
*~
.coverage*
htmlcov
*.egg-info/
.cache/
pexpect-4.8.0/.travis.yml 0000664 0000000 0000000 00000001271 13610364777 0015323 0 ustar 00root root 0000000 0000000 language: python
python:
- 2.7
- 3.4
- 3.5
- 3.6
- pypy
- nightly
matrix:
include:
- python: 3.7
dist: xenial # required for Python 3.7 (travis-ci/travis-ci#9069)
sudo: required # required for Python 3.7 (travis-ci/travis-ci#9069)
allow_failures:
# PyPy on Travis is currently incompatible with Cryptography.
- python: pypy
install:
- export PYTHONIOENCODING=UTF8
- pip install coveralls pytest-cov ptyprocess
script:
- ./tools/display-sighandlers.py
- ./tools/display-terminalinfo.py
- py.test --cov pexpect --cov-config .coveragerc
after_success:
- coverage combine
- coveralls
# Use new Travis stack, should be faster
sudo: false
pexpect-4.8.0/DEVELOPERS.rst 0000664 0000000 0000000 00000000644 13610364777 0015417 0 ustar 00root root 0000000 0000000 To run the tests, use `py.test `_::
py.test tests
The tests are all located in the tests/ directory. To add a new unit
test all you have to do is create the file in the tests/ directory with a
filename in this format::
test_*.py
New test case classes may wish to inherit from ``PexpectTestCase.PexpectTestCase``
in the tests directory, which sets up some convenient functionality.
pexpect-4.8.0/LICENSE 0000664 0000000 0000000 00000001733 13610364777 0014222 0 ustar 00root root 0000000 0000000 ISC LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2013-2014, Pexpect development team
Copyright (c) 2012, Noah Spurrier
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
pexpect-4.8.0/MANIFEST.in 0000664 0000000 0000000 00000000275 13610364777 0014753 0 ustar 00root root 0000000 0000000 recursive-include doc *
prune doc/_build
recursive-include examples *
include .coveragerc README.rst LICENSE pexpect/bashrc.sh
recursive-include tests *
global-exclude __pycache__ *.pyc *~
pexpect-4.8.0/README.rst 0000664 0000000 0000000 00000004567 13610364777 0014714 0 ustar 00root root 0000000 0000000 .. image:: https://travis-ci.org/pexpect/pexpect.svg?branch=master
:target: https://travis-ci.org/pexpect/pexpect
:align: right
:alt: Build status
Pexpect is a Pure Python Expect-like module
Pexpect makes Python a better tool for controlling other applications.
Pexpect is a pure Python module for spawning child applications; controlling
them; and responding to expected patterns in their output. Pexpect works like
Don Libes' Expect. Pexpect allows your script to spawn a child application and
control it as if a human were typing commands.
Pexpect can be used for automating interactive applications such as ssh, ftp,
passwd, telnet, etc. It can be used to automate setup scripts for duplicating
software package installations on different servers. It can be used for
automated software testing. Pexpect is in the spirit of Don Libes' Expect, but
Pexpect is pure Python.
The main features of Pexpect require the pty module in the Python standard
library, which is only available on Unix-like systems. Some features—waiting
for patterns from file descriptors or subprocesses—are also available on
Windows.
If you want to work with the development version of the source code then please
read the DEVELOPERS.rst document in the root of the source code tree.
Free, open source, and all that good stuff.
You can install Pexpect using pip::
pip install pexpect
`Docs on ReadTheDocs `_
PEXPECT LICENSE::
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2013-2016, Pexpect development team
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
This license is approved by the OSI and FSF as GPL-compatible.
pexpect-4.8.0/doc/ 0000775 0000000 0000000 00000000000 13610364777 0013756 5 ustar 00root root 0000000 0000000 pexpect-4.8.0/doc/FAQ.rst 0000664 0000000 0000000 00000016325 13610364777 0015126 0 ustar 00root root 0000000 0000000 FAQ
===
**Q: Where can I get help with pexpect? Is there a mailing list?**
A: You can use the `pexpect tag on Stackoverflow `__
to ask questions specifically related to Pexpect. For more general Python
support, there's the python-list_ mailing list, and the `#python`_
IRC channel. Please refrain from using github for general
python or systems scripting support.
.. _python-list: https://mail.python.org/mailman/listinfo/python-list
.. _#python: https://www.python.org/community/irc/
**Q: Why don't shell pipe and redirect (| and >) work when I spawn a command?**
A: Remember that Pexpect does NOT interpret shell meta characters such as
redirect, pipe, or wild cards (``>``, ``|``, or ``*``). That's done by a shell not
the command you are spawning. This is a common mistake. If you want to run a
command and pipe it through another command then you must also start a shell.
For example::
child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
child.expect(pexpect.EOF)
The second form of spawn (where you pass a list of arguments) is useful in
situations where you wish to spawn a command and pass it its own argument list.
This can make syntax more clear. For example, the following is equivalent to the
previous example::
shell_cmd = 'ls -l | grep LOG > log_list.txt'
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
child.expect(pexpect.EOF)
**Q: The `before` and `after` properties sound weird.**
A: This is how the -B and -A options in grep works, so that made it
easier for me to remember. Whatever makes my life easier is what's best.
Originally I was going to model Pexpect after Expect, but then I found
that I didn't actually like the way Expect did some things. It was more
confusing. The `after` property can be a little confusing at first,
because it will actually include the matched string. The `after` means
after the point of match, not after the matched string.
**Q: Why not just use Expect?**
A: I love it. It's great. I has bailed me out of some real jams, but I
wanted something that would do 90% of what I need from Expect; be 10% of
the size; and allow me to write my code in Python instead of TCL.
Pexpect is not nearly as big as Expect, but Pexpect does everything I
have ever used Expect for.
.. _whynotpipe:
**Q: Why not just use a pipe (popen())?**
A: A pipe works fine for getting the output to non-interactive programs.
If you just want to get the output from ls, uname, or ping then this
works. Pipes do not work very well for interactive programs and pipes
will almost certainly fail for most applications that ask for passwords
such as telnet, ftp, or ssh.
There are two reasons for this.
* First an application may bypass stdout and print directly to its
controlling TTY. Something like SSH will do this when it asks you for
a password. This is why you cannot redirect the password prompt because
it does not go through stdout or stderr.
* The second reason is because most applications are built using the C
Standard IO Library (anything that uses ``#include ``). One
of the features of the stdio library is that it buffers all input and
output. Normally output is line buffered when a program is printing to
a TTY (your terminal screen). Everytime the program prints a line-feed
the currently buffered data will get printed to your screen. The
problem comes when you connect a pipe. The stdio library is smart and
can tell that it is printing to a pipe instead of a TTY. In that case
it switches from line buffer mode to block buffered. In this mode the
currently buffered data is flushed when the buffer is full. This
causes most interactive programs to deadlock. Block buffering is more
efficient when writing to disks and pipes. Take the situation where a
program prints a message ``"Enter your user name:\n"`` and then waits
for you type type something. In block buffered mode, the stdio library
will not put the message into the pipe even though a linefeed is
printed. The result is that you never receive the message, yet the
child application will sit and wait for you to type a response. Don't
confuse the stdio lib's buffer with the pipe's buffer. The pipe buffer
is another area that can cause problems. You could flush the input
side of a pipe, whereas you have no control over the stdio library buffer.
More information: the Standard IO library has three states for a
``FILE *``. These are: _IOFBF for block buffered; _IOLBF for line buffered;
and _IONBF for unbuffered. The STDIO lib will use block buffering when
talking to a block file descriptor such as a pipe. This is usually not
helpful for interactive programs. Short of recompiling your program to
include fflush() everywhere or recompiling a custom stdio library there
is not much a controlling application can do about this if talking over
a pipe.
The program may have put data in its output that remains unflushed
because the output buffer is not full; then the program will go and
deadlock while waiting for input -- because you never send it any
because you are still waiting for its output (still stuck in the STDIO's
output buffer).
The answer is to use a pseudo-tty. A TTY device will force line
buffering (as opposed to block buffering). Line buffering means that you
will get each line when the child program sends a line feed. This
corresponds to the way most interactive programs operate -- send a line
of output then wait for a line of input.
I put "answer" in quotes because it's ugly solution and because there is
no POSIX standard for pseudo-TTY devices (even though they have a TTY
standard...). What would make more sense to me would be to have some way
to set a mode on a file descriptor so that it will tell the STDIO to be
line-buffered. I have investigated, and I don't think there is a way to
set the buffered state of a child process. The STDIO Library does not
maintain any external state in the kernel or whatnot, so I don't think
there is any way for you to alter it. I'm not quite sure how this
line-buffered/block-buffered state change happens internally in the
STDIO library. I think the STDIO lib looks at the file descriptor and
decides to change behavior based on whether it's a TTY or a block file
(see isatty()).
I hope that this qualifies as helpful. Don't use a pipe to control
another application.
**Q: Can I do screen scraping with this thing?**
A: That depends. If your application just does line-oriented output then
this is easy. If a program emits many terminal sequences, from video
attributes to screen addressing, such as programs using curses, then
it may become very difficult to ascertain what text is displayed on a screen.
We suggest using the `pyte `_ library to
screen-scrape. The module :mod:`pexpect.ANSI` released with previous versions
of pexpect is now marked deprecated and may be removed in the future.
**Q: I get strange behavior with pexect and gevent**
A: Pexpect uses fork(2), exec(2), select(2), waitpid(2), and implements its
own selector in expect family of calls. pexpect has been known to misbehave
when paired with gevent. A solution might be to isolate your pexpect
dependent code from any frameworks that manipulate event selection behavior
by running it in an another process entirely.
pexpect-4.8.0/doc/Makefile 0000664 0000000 0000000 00000012700 13610364777 0015416 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Pexpect.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Pexpect.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Pexpect"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Pexpect"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
pexpect-4.8.0/doc/api/ 0000775 0000000 0000000 00000000000 13610364777 0014527 5 ustar 00root root 0000000 0000000 pexpect-4.8.0/doc/api/fdpexpect.rst 0000664 0000000 0000000 00000000615 13610364777 0017245 0 ustar 00root root 0000000 0000000 fdpexpect - use pexpect with a file descriptor
==============================================
.. automodule:: pexpect.fdpexpect
fdspawn class
-------------
.. autoclass:: fdspawn
:show-inheritance:
.. automethod:: __init__
.. automethod:: isalive
.. automethod:: close
.. method:: expect
expect_exact
expect_list
As :class:`pexpect.spawn`.
pexpect-4.8.0/doc/api/index.rst 0000664 0000000 0000000 00000000745 13610364777 0016376 0 ustar 00root root 0000000 0000000 API documentation
=================
.. toctree::
:maxdepth: 2
pexpect
fdpexpect
popen_spawn
replwrap
pxssh
The modules ``pexpect.screen`` and ``pexpect.ANSI`` have been deprecated in
Pexpect version 4. They were separate from the main use cases for Pexpect, and
there are better maintained Python terminal emulator packages, such as
`pyte `__.
These modules are still present for now, but we don't advise using them in new
code.
pexpect-4.8.0/doc/api/pexpect.rst 0000664 0000000 0000000 00000005763 13610364777 0016744 0 ustar 00root root 0000000 0000000 Core pexpect components
=======================
.. automodule:: pexpect
spawn class
-----------
.. autoclass:: spawn
.. automethod:: __init__
.. automethod:: expect
.. automethod:: expect_exact
.. automethod:: expect_list
.. automethod:: compile_pattern_list
.. automethod:: send
.. automethod:: sendline
.. automethod:: write
.. automethod:: writelines
.. automethod:: sendcontrol
.. automethod:: sendeof
.. automethod:: sendintr
.. automethod:: read
.. automethod:: readline
.. automethod:: read_nonblocking
.. automethod:: eof
.. automethod:: interact
.. attribute:: logfile
logfile_read
logfile_send
Set these to a Python file object (or :data:`sys.stdout`) to log all
communication, data read from the child process, or data sent to the child
process.
.. note::
With :class:`spawn` in bytes mode, the log files should be open for
writing binary data. In unicode mode, they should
be open for writing unicode text. See :ref:`unicode`.
Controlling the child process
`````````````````````````````
.. class:: spawn
.. automethod:: kill
.. automethod:: terminate
.. automethod:: isalive
.. automethod:: wait
.. automethod:: close
.. automethod:: getwinsize
.. automethod:: setwinsize
.. automethod:: getecho
.. automethod:: setecho
.. automethod:: waitnoecho
.. attribute:: pid
The process ID of the child process.
.. attribute:: child_fd
The file descriptor used to communicate with the child process.
.. _unicode:
Handling unicode
````````````````
By default, :class:`spawn` is a bytes interface: its read methods return bytes,
and its write/send and expect methods expect bytes. If you pass the *encoding*
parameter to the constructor, it will instead act as a unicode interface:
strings you send will be encoded using that encoding, and bytes received will
be decoded before returning them to you. In this mode, patterns for
:meth:`~spawn.expect` and :meth:`~spawn.expect_exact` should also be unicode.
.. versionchanged:: 4.0
:class:`spawn` provides both the bytes and unicode interfaces. In Pexpect
3.x, the unicode interface was provided by a separate ``spawnu`` class.
For backwards compatibility, some Unicode is allowed in bytes mode: the
send methods will encode arbitrary unicode as UTF-8 before sending it to the
child process, and its expect methods can accept ascii-only unicode strings.
.. note::
Unicode handling with pexpect works the same way on Python 2 and 3, despite
the difference in names. I.e.:
- Bytes mode works with ``str`` on Python 2, and :class:`bytes` on Python 3,
- Unicode mode works with ``unicode`` on Python 2, and :class:`str` on Python 3.
run function
------------
.. autofunction:: run
Exceptions
----------
.. autoclass:: EOF
.. autoclass:: TIMEOUT
.. autoclass:: ExceptionPexpect
Utility functions
-----------------
.. autofunction:: which
.. autofunction:: split_command_line
pexpect-4.8.0/doc/api/popen_spawn.rst 0000664 0000000 0000000 00000001015 13610364777 0017607 0 ustar 00root root 0000000 0000000 popen_spawn - use pexpect with a piped subprocess
=================================================
.. automodule:: pexpect.popen_spawn
PopenSpawn class
----------------
.. autoclass:: PopenSpawn
.. automethod:: __init__
.. automethod:: send
.. automethod:: sendline
.. automethod:: write
.. automethod:: writelines
.. automethod:: kill
.. automethod:: sendeof
.. automethod:: wait
.. method:: expect
expect_exact
expect_list
As :class:`pexpect.spawn`.
pexpect-4.8.0/doc/api/pxssh.rst 0000664 0000000 0000000 00000003371 13610364777 0016432 0 ustar 00root root 0000000 0000000 pxssh - control an SSH session
==============================
.. note::
*pxssh* is a screen-scraping wrapper around the SSH command on your system.
In many cases, you should consider using
`Paramiko `_ or
`RedExpect `_ instead.
Paramiko is a Python module which speaks the SSH protocol directly, so it
doesn't have the extra complexity of running a local subprocess.
RedExpect is very similar to pxssh except that it reads and writes directly
into an SSH session all done via Python with all the SSH protocol in C,
additionally it is written for communicating to SSH servers that are not just
Linux machines. Meaning that it is extremely fast in comparison to Paramiko
and already has the familiar expect API. In most cases RedExpect and pxssh
code should be fairly interchangeable.
.. automodule:: pexpect.pxssh
.. autoclass:: ExceptionPxssh
pxssh class
-----------
.. autoclass:: pxssh
.. automethod:: __init__
.. attribute:: PROMPT
The regex pattern to search for to find the prompt. If you call :meth:`login`
with ``auto_prompt_reset=False``, you must set this attribute manually.
.. attribute:: force_password
If this is set to ``True``, public key authentication is disabled, forcing the
server to ask for a password. Note that the sysadmin can disable password
logins, in which case this won't work.
.. attribute:: options
The dictionary of user specified SSH options, eg, ``options = dict(StrictHostKeyChecking="no", UserKnownHostsFile="/dev/null")``
.. automethod:: login
.. automethod:: logout
.. automethod:: prompt
.. automethod:: sync_original_prompt
.. automethod:: set_unique_prompt
pexpect-4.8.0/doc/api/replwrap.rst 0000664 0000000 0000000 00000001154 13610364777 0017116 0 ustar 00root root 0000000 0000000 replwrap - Control read-eval-print-loops
========================================
.. automodule:: pexpect.replwrap
.. versionadded:: 3.3
.. autoclass:: REPLWrapper
.. automethod:: run_command
.. data:: PEXPECT_PROMPT
A string that can be used as a prompt, and is unlikely to be found in output.
Using the objects above, it is easy to wrap a REPL. For instance, to use a
Python shell::
py = REPLWrapper("python", ">>> ", "import sys; sys.ps1={!r}; sys.ps2={!r}")
py.run_command("4+7")
Convenience functions are provided for Python and bash shells:
.. autofunction:: python
.. autofunction:: bash
pexpect-4.8.0/doc/clean.css 0000664 0000000 0000000 00000003602 13610364777 0015553 0 ustar 00root root 0000000 0000000
body {
margin:0px;
padding:0px;
font-family:verdana, arial, helvetica, sans-serif;
color:#333;
background-color:white;
}
pre {
background: #eeeeee;
border: 1px solid #888888;
color: black;
padding: 1em;
white-space: pre;
}
h1 {
margin:5px 0px 5px 0px;
padding:0px;
font-size:20px;
line-height:28px;
font-weight:900;
color:#44f;
}
h2 {
margin:5px 0px 5px 0px;
padding:0px;
font-size:17px;
line-height:28px;
font-weight:900;
color:#226;
}
h3 {
margin:5px 0px 5px 0px;
padding:0px;
font-size:15px;
line-height:28px;
font-weight:900;
}
p
{
margin:0px 0px 16px 0px;
font:11px/20px verdana, arial, helvetica, sans-serif;
padding:0px;
}
table
{
font-size: 10pt;
color: #000000;
}
td{border:1px solid #999;}
table.pymenu {color: #000000; background-color: #99ccff}
th.pymenu {color: #ffffff; background-color: #003366}
.code
{
font-family: "Lucida Console", monospace; font-weight: bold;
color: #007700; background-color: #eeeeee
}
#Content>p {margin:0px;}
#Content>p+p {text-indent:30px;}
a {
text-decoration:none;
font-weight:600;
font-family:verdana, arial, helvetica, sans-serif;
color: #900;
}
//a:link {color:#09c;}
//a x:visited {color:#07a;}
a:hover {background-color:#ee0;}
#Header {
margin:10px 0px 10px 0px;
padding:10px 0px 10px 20px;
/* For IE5/Win's benefit height = [correct height] + [top padding] + [top and bottom border widths] */
height:33px; /* 14px + 17px + 2px = 33px */
border-style:solid;
border-color:black;
border-width:1px 0px; /* top and bottom borders: 1px; left and right borders: 0px */
line-height:33px;
background-color:#eee;
height:66px; /* the correct height */
}
#Content {
margin:0px 210px 50px 10px;
padding:10px;
}
#Menu {
position:absolute;
top:100px;
right:20px;
width:172px;
padding:10px;
background-color:#eee;
border:1px solid #999; // dashed #999;
line-height:17px;
width:150px;
font-size:11px;
}
pexpect-4.8.0/doc/commonissues.rst 0000664 0000000 0000000 00000010570 13610364777 0017237 0 ustar 00root root 0000000 0000000 Common problems
===============
Threads
-------
On Linux (RH 8) you cannot spawn a child from a different thread and pass the
handle back to a worker thread. The child is successfully spawned but you can't
interact with it. The only way to make it work is to spawn and interact with the
child all in the same thread. [Adam Kerrison]
Timing issue with send() and sendline()
---------------------------------------
This problem has been addressed and should not affect most users.
It is sometimes possible to read an echo of the string sent with
:meth:`~pexpect.spawn.send` and :meth:`~pexpect.spawn.sendline`. If you call
:meth:`~pexpect.spawn.send` and then immediately call :meth:`~pexpect.spawn.readline`,
you may get part of your output echoed back. You may read back what you just
wrote even if the child application does not explicitly echo it. Timing is
critical. This could be a security issue when talking to an application that
asks for a password; otherwise, this does not seem like a big deal. But why do
TTYs do this?
People usually report this when they are trying to control SSH or some other
login. For example, if your code looks something like this::
child.expect ('[pP]assword:')
child.sendline (my_password)
1. SSH prints "password:" prompt to the user.
2. SSH turns off echo on the TTY device.
3. SSH waits for user to enter a password.
When scripting with Pexpect what can happen is that Pexpect will respond to the
"password:" prompt before SSH has had time to turn off TTY echo. In other words,
Pexpect sends the password between steps 1. and 2., so the password gets echoed
back to the TTY. I would call this an SSH bug.
Pexpect now automatically adds a short delay before sending data to a child
process. This more closely mimics what happens in the usual human-to-app
interaction. The delay can be tuned with the ``delaybeforesend`` attribute of
objects of the spawn class. In general, this fixes the problem for everyone and so
this should not be an issue for most users. For some applications you might with
to turn it off::
child = pexpect.spawn ("ssh user@example.com")
child.delaybeforesend = None
Truncated output just before child exits
----------------------------------------
So far I have seen this only on older versions of Apple's MacOS X. If the child
application quits it may not flush its output buffer. This means that your
Pexpect application will receive an EOF even though it should have received a
little more data before the child died. This is not generally a problem when
talking to interactive child applications. One example where it is a problem is
when trying to read output from a program like *ls*. You may receive most of the
directory listing, but the last few lines will get lost before you receive an EOF.
The reason for this is that *ls* runs; completes its task; and then exits. The
buffer is not flushed before exit so the last few lines are lost. The following
example demonstrates the problem::
child = pexpect.spawn('ls -l')
child.expect(pexpect.EOF)
print child.before
Controlling SSH on Solaris
--------------------------
Pexpect does not yet work perfectly on Solaris. One common problem is that SSH
sometimes will not allow TTY password authentication. For example, you may
expect SSH to ask you for a password using code like this::
child = pexpect.spawn('ssh user@example.com')
child.expect('password')
child.sendline('mypassword')
You may see the following error come back from a spawned child SSH::
Permission denied (publickey,keyboard-interactive).
This means that SSH thinks it can't access the TTY to ask you for your password.
The only solution I have found is to use public key authentication with SSH.
This bypasses the need for a password. I'm not happy with this solution. The
problem is due to poor support for Solaris Pseudo TTYs in the Python Standard
Library.
child does not receive full input, emits BEL
--------------------------------------------
You may notice when running for example cat(1) or base64(1), when sending a
very long input line, that it is not fully received, and the BEL ('\a') may
be found in output.
By default the child terminal matches the parent, which is often in "canonical
mode processing". You may wish to disable this mode. The exact limit of a line
varies by operating system, and details of disabling canonical mode may be
found in the docstring of :meth:`~pexpect.spawn.send`.
pexpect-4.8.0/doc/conf.py 0000664 0000000 0000000 00000017707 13610364777 0015271 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# Pexpect documentation build configuration file, created by
# sphinx-quickstart on Tue Sep 17 11:05:11 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('sphinxext'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinx.ext.viewcode', 'github', # for easy GitHub links
]
github_project_url = "https://github.com/pexpect/pexpect"
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Pexpect'
copyright = u'2013, Noah Spurrier and contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '4.8'
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Pexpectdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Pexpect.tex', u'Pexpect Documentation',
u'Noah Spurrier and contributors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pexpect', u'Pexpect Documentation',
[u'Noah Spurrier and contributors'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Pexpect', u'Pexpect Documentation',
u'Noah Spurrier and contributors', 'Pexpect', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/3/': None}
pexpect-4.8.0/doc/examples.rst 0000664 0000000 0000000 00000006636 13610364777 0016341 0 ustar 00root root 0000000 0000000 Examples
========
Under the distribution tarball directory you should find an "examples" directory.
This is the best way to learn to use Pexpect. See the descriptions of Pexpect
Examples.
`topip.py `_
This runs `netstat` on a local or remote server. It calculates some simple
statistical information on the number of external inet connections. This can
be used to detect if one IP address is taking up an excessive number of
connections. It can also send an email alert if a given IP address exceeds a
threshold between runs of the script. This script can be used as a drop-in
Munin plugin or it can be used stand-alone from cron. I used this on a busy
web server that would sometimes get hit with denial of service attacks. This
made it easy to see if a script was opening many multiple connections. A
typical browser would open fewer than 10 connections at once. A script might
open over 100 simultaneous connections.
`hive.py `_
This script creates SSH connections to a list of hosts that you provide.
Then you are given a command line prompt. Each shell command that you
enter is sent to all the hosts. The response from each host is collected
and printed. For example, you could connect to a dozen different
machines and reboot them all at once.
`script.py `_
This implements a command similar to the classic BSD "script" command.
This will start a subshell and log all input and output to a file.
This demonstrates the :meth:`~pexpect.spawn.interact` method of Pexpect.
`ftp.py `_
This demonstrates an FTP "bookmark". This connects to an ftp site;
does a few ftp tasks; and then gives the user interactive control over
the session. In this case the "bookmark" is to a directory on the
OpenBSD ftp server. It puts you in the i386 packages directory. You
can easily modify this for other sites. This demonstrates the
:meth:`~pexpect.spawn.interact` method of Pexpect.
`monitor.py `_
This runs a sequence of commands on a remote host using SSH. It runs a
simple system checks such as uptime and free to monitor the state of
the remote host.
`passmass.py `_
This will login to each given server and change the password of the
given user. This demonstrates scripting logins and passwords.
`python.py `_
This starts the python interpreter and prints the greeting message
backwards. It then gives the user interactive control of Python. It's
pretty useless!
`ssh_tunnel.py `_
This starts an SSH tunnel to a remote machine. It monitors the
connection and restarts the tunnel if it goes down.
`uptime.py `_
This will run the uptime command and parse the output into variables.
This demonstrates using a single regular expression to match the
output of a command and capturing different variable in match groups.
The grouping regular expression handles a wide variety of different
uptime formats.
pexpect-4.8.0/doc/history.rst 0000664 0000000 0000000 00000044142 13610364777 0016216 0 ustar 00root root 0000000 0000000 History
=======
Releases
--------
Version 4.8
```````````
* Returned behavior of searchwindowsize to that in 4.3 and earlier (searches
are only done within the search window) (:ghpull:`579`).
* Fixed a bug truncating ``before`` attribute after a timeout (:ghpull:`579`).
* Fixed a bug where a search could be less than ``searchwindowsize`` if it
was increased between calls (:ghpull:`579`).
* Minor test cleanups to improve portability (:ghpull:`580`) (:ghpull:`581`)
(:ghpull:`582`) (:ghpull:`583`) (:ghpull:`584`) (:ghpull:`585`).
* Disable chaining of timeout and EOF exceptions (:gphull:`606`).
* Allow traceback included snippet length to be configured via
``str_last_chars`` rather than always 100 (:ghpull:`598`).
* Python 3 warning added to interact.py (:ghpull:`537`).
* Several doc updates.
Version 4.7
```````````
* The :meth:`.pxssh.login` method now no longer requires a username if an ssh
config is provided and will raise an error if neither are provided.
(:ghpull:`562`).
* The :meth:`.pxssh.login` method now supports providing your own ``ssh``
command via the ``cmd`` parameter.
(:ghpull:`528`) (:ghpull:`563`).
* :class:`.pxssh` now supports the ``use_poll`` parameter which is passed into :meth:`.pexpect.spawn`
(:ghpull:`542`).
* Minor bug fix with ``ssh_config``.
(:ghpull:`498`).
* :meth:`.replwrap.run_command` now has async support via an ``async_`` parameter.
(:ghpull:`501`).
* :meth:`.pexpect.spawn` will now read additional bytes if able up to a buffer limit.
(:ghpull:`304`).
Version 4.6
```````````
* The :meth:`.pxssh.login` method now supports an ``ssh_config`` parameter,
which can be used to specify a file path to an SSH config file
(:ghpull:`490`).
* Improved compatability for the ``crlf`` parameter of :class:`~.PopenSpawn`
(:ghpull:`493`)
* Fixed an issue in read timeout handling when using :class:`~.spawn` and
:class:`~.fdspawn` with the ``use_poll`` parameter (:ghpull:`492`).
Version 4.5
```````````
* :class:`~.spawn` and :class:`~.fdspawn` now have a ``use_poll`` parameter.
If this is True, they will use :func:`select.poll` instead of :func:`select.select`.
``poll()`` allows file descriptors above 1024, but it must be explicitly
enabled due to compatibility concerns (:ghpull:`474`).
* The :meth:`.pxssh.login` method has several new and changed options:
* The option ``password_regex`` allows changing
the password prompt regex, for servers that include ``password:`` in a banner
before reaching a prompt (:ghpull:`468`).
* :meth:`~.pxssh.login` now allows for setting up SSH tunnels to be requested once
logged in to the remote server. This option is ``ssh_tunnels`` (:ghpull:`473`).
The structure should be like this::
{
'local': ['2424:localhost:22'], # Local SSH tunnels
'remote': ['2525:localhost:22'], # Remote SSH tunnels
'dynamic': [8888], # Dynamic/SOCKS tunnels
}
* The option ``spawn_local_ssh=False`` allows subsequent logins from the
remote session and treats the session as if it was local (:ghpull:`472`).
* Setting ``sync_original_prompt=False`` will prevent changing the prompt to
something unique, in case the remote server is sensitive to new lines at login
(:ghpull:`468`).
* If ``ssh_key=True`` is passed, the SSH client forces forwarding the authentication
agent to the remote server instead of providing a key (:ghpull:`473`).
Version 4.4
```````````
* :class:`~.PopenSpawn` now has a ``preexec_fn`` parameter, like :class:`~.spawn`
and :class:`subprocess.Popen`, for a function to be called in the child
process before executing the new command. Like in ``Popen``, this works only
in POSIX, and can cause issues if your application also uses threads
(:ghpull:`460`).
* Significant performance improvements when processing large amounts of data
(:ghpull:`464`).
* Ensure that ``spawn.closed`` gets set by :meth:`~.spawn.close`, and improve
an example for passing ``SIGWINCH`` through to a child process (:ghpull:`466`).
Version 4.3.1
`````````````
* When launching bash for :mod:`pexpect.replwrap`, load the system ``bashrc``
from a couple of different common locations (:ghpull:`457`), and then unset
the ``PROMPT_COMMAND`` environment variable, which can interfere with the
prompt we're expecting (:ghpull:`459`).
Version 4.3
```````````
* The ``async=`` parameter to integrate with asyncio has become ``async_=``
(:ghpull:`431`), as *async* is becoming a Python keyword from Python 3.6.
Pexpect will still recognise ``async`` as an alternative spelling.
* Similarly, the module ``pexpect.async`` became ``pexpect._async``
(:ghpull:`450`). This module is not part of the public API.
* Fix problems with asyncio objects closing file descriptors during garbage
collection (:ghissue:`347`, :ghpull:`376`).
* Set the ``.pid`` attribute of a :class:`~.PopenSpawn` object (:ghpull:`417`).
* Fix passing Windows paths to :class:`~.PopenSpawn` (:ghpull:`446`).
* :class:`~.PopenSpawn` on Windows can pass string commands through to ``Popen``
without splitting them into a list (:ghpull:`447`).
* Stop ``shlex`` trying to read from stdin when :class:`~.PopenSpawn` is
passed ``cmd=None`` (:ghissue:`433`, :ghpull:`434`).
* Ensure that an error closing a Pexpect spawn object raises a Pexpect error,
rather than a Ptyprocess error (:ghissue:`383`, :ghpull:`386`).
* Cleaned up invalid backslash escape sequences in strings (:ghpull:`430`,
:ghpull:`445`).
* The pattern for a password prompt in :mod:`pexpect.pxssh` changed from
``password`` to ``password:`` (:ghpull:`452`).
* Correct docstring for using unicode with spawn (:ghpull:`395`).
* Various other improvements to documentation.
Version 4.2.1
`````````````
* Fix to allow running ``env`` in replwrap-ed bash.
* Raise more informative exception from pxssh if it fails to connect.
* Change ``passmass`` example to not log passwords entered.
Version 4.2
```````````
* Change: When an ``env`` parameter is specified to the :class:`~.spawn` or
:class:`~.run` family of calls containing a value for ``PATH``, its value is
used to discover the target executable from a relative path, rather than the
current process's environment ``PATH``. This mirrors the behavior of
:func:`subprocess.Popen` in the standard library (:ghissue:`348`).
* Regression: Re-introduce capability for :meth:`read_nonblocking` in class
:class:`fdspawn` as previously supported in version 3.3 (:ghissue:`359`).
Version 4.0
```````````
* Integration with :mod:`asyncio`: passing ``async=True`` to :meth:`~.spawn.expect`,
:meth:`~.spawn.expect_exact` or :meth:`~.spawn.expect_list` will make them return a
coroutine. You can get the result using ``yield from``, or wrap it in an
:class:`asyncio.Task`. This allows the event loop to do other things while
waiting for output that matches a pattern.
* Experimental support for Windows (with some caveats)—see :ref:`windows`.
* Enhancement: allow method as callbacks of argument ``events`` for
:func:`pexpect.run` (:ghissue:`176`).
* It is now possible to call :meth:`~.spawn.wait` multiple times, or after a process
is already determined to be terminated without raising an exception
(:ghpull:`211`).
* New :class:`pexpect.spawn` keyword argument, ``dimensions=(rows, columns)``
allows setting terminal screen dimensions before launching a program
(:ghissue:`122`).
* Fix regression that prevented executable, but unreadable files from
being found when not specified by absolute path -- such as
/usr/bin/sudo (:ghissue:`104`).
* Fixed regression when executing pexpect with some prior releases of
the multiprocessing module where stdin has been closed (:ghissue:`86`).
Backwards incompatible changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Deprecated ``pexpect.screen`` and ``pexpect.ANSI``. Please use other packages
such as `pyte `__ to emulate a terminal.
* Removed the independent top-level modules (``pxssh fdpexpect FSM screen ANSI``)
which were installed alongside Pexpect. These were moved into the Pexpect
package in 3.0, but the old names were left as aliases.
* Child processes created by Pexpect no longer ignore SIGHUP by default: the
``ignore_sighup`` parameter of :class:`pexpect.spawn` defaults to False. To
get the old behaviour, pass ``ignore_sighup=True``.
Version 3.3
```````````
* Added a mechanism to wrap REPLs, or shells, in an object which can conveniently
be used to send commands and wait for the output (:mod:`pexpect.replwrap`).
* Fixed issue where pexpect would attempt to execute a directory because
it has the 'execute' bit set (:ghissue:`37`).
* Removed the ``pexpect.psh`` module. This was never documented, and we found
no evidence that people use it. The new :mod:`pexpect.replwrap` module
provides a more flexible alternative.
* Fixed ``TypeError: got ('\r\n') as pattern`` in :meth:`spawnu.readline`
method (:ghissue:`67`).
* Fixed issue where EOF was not correctly detected in :meth:`~.interact`, causing
a repeating loop of output on Linux, and blocking before EOF on BSD and
Solaris (:ghissue:`49`).
* Several Solaris (SmartOS) bugfixes, preventing :exc:`IOError` exceptions, especially
when used with cron(1) (:ghissue:`44`).
* Added new keyword argument ``echo=True`` for :class:`spawn`. On SVR4-like
systems, the method :meth:`~.isatty` will always return *False*: the child pty
does not appear as a terminal. Therefore, :meth:`~.setecho`, :meth:`~.getwinsize`,
:meth:`~.setwinsize`, and :meth:`~.waitnoecho` are not supported on those platforms.
After this, we intend to start working on a bigger refactoring of the code, to
be released as Pexpect 4. There may be more bugfix 3.x releases, however.
Version 3.2
```````````
* Fix exception handling from :func:`select.select` on Python 2 (:ghpull:`38`).
This was accidentally broken in the previous release when it was fixed for
Python 3.
* Removed a workaround for ``TIOCSWINSZ`` on very old systems, which was causing
issues on some BSD systems (:ghpull:`40`).
* Fixed an issue with exception handling in :mod:`~pexpect.pxssh` (:ghpull:`43`)
The documentation for :mod:`~pexpect.pxssh` was improved.
Version 3.1
```````````
* Fix an issue that prevented importing pexpect on Python 3 when ``sys.stdout``
was reassigned (:ghissue:`30`).
* Improve prompt synchronisation in :mod:`~pexpect.pxssh` (:ghpull:`28`).
* Fix pickling exception instances (:ghpull:`34`).
* Fix handling exceptions from :func:`select.select` on Python 3 (:ghpull:`33`).
The examples have also been cleaned up somewhat - this will continue in future
releases.
Version 3.0
```````````
The new major version number doesn't indicate any deliberate API incompatibility.
We have endeavoured to avoid breaking existing APIs. However, pexpect is under
new maintenance after a long dormancy, so some caution is warranted.
* A new :ref:`unicode API ` was introduced.
* Python 3 is now supported, using a single codebase.
* Pexpect now requires at least Python 2.6 or 3.2.
* The modules other than pexpect, such as :mod:`pexpect.fdpexpect` and
:mod:`pexpect.pxssh`, were moved into the pexpect package. For now, wrapper
modules are installed to the old locations for backwards compatibility (e.g.
``import pxssh`` will still work), but these will be removed at some point in
the future.
* Ignoring ``SIGHUP`` is now optional - thanks to Kimmo Parviainen-Jalanko for
the patch.
We also now have `docs on ReadTheDocs `_,
and `continuous integration on Travis CI `_.
Version 2.4
```````````
* Fix a bug regarding making the pty the controlling terminal when the process
spawning it is not, actually, a terminal (such as from cron)
Version 2.3
```````````
* Fixed OSError exception when a pexpect object is cleaned up. Previously, you
might have seen this exception::
Exception exceptions.OSError: (10, 'No child processes')
in > ignored
You should not see that anymore. Thanks to Michael Surette.
* Added support for buffering reads. This greatly improves speed when trying to
match long output from a child process. When you create an instance of the spawn
object you can then set a buffer size. For now you MUST do the following to turn
on buffering -- it may be on by default in future version::
child = pexpect.spawn ('my_command')
child.maxread=1000 # Sets buffer to 1000 characters.
* I made a subtle change to the way TIMEOUT and EOF exceptions behave.
Previously you could either expect these states in which case pexpect
will not raise an exception, or you could just let pexpect raise an
exception when these states were encountered. If you expected the
states then the ``before`` property was set to everything before the
state was encountered, but if you let pexpect raise the exception then
``before`` was not set. Now, the ``before`` property will get set either
way you choose to handle these states.
* The spawn object now provides iterators for a *file-like interface*.
This makes Pexpect a more complete file-like object. You can now write
code like this::
child = pexpect.spawn ('ls -l')
for line in child:
print line
* write and writelines() no longer return a value. Use send() if you need that
functionality. I did this to make the Spawn object more closely match a
file-like object.
* Added the attribute ``exitstatus``. This will give the exit code returned
by the child process. This will be set to ``None`` while the child is still
alive. When ``isalive()`` returns 0 then ``exitstatus`` will be set.
* Made a few more tweaks to ``isalive()`` so that it will operate more
consistently on different platforms. Solaris is the most difficult to support.
* You can now put ``TIMEOUT`` in a list of expected patterns. This is just like
putting ``EOF`` in the pattern list. Expecting for a ``TIMEOUT`` may not be
used as often as ``EOF``, but this makes Pexpect more consistent.
* Thanks to a suggestion and sample code from Chad J. Schroeder I added the ability
for Pexpect to operate on a file descriptor that is already open. This means that
Pexpect can be used to control streams such as those from serial port devices. Now,
you just pass the integer file descriptor as the "command" when constructing a
spawn open. For example on a Linux box with a modem on ttyS1::
fd = os.open("/dev/ttyS1", os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY)
m = pexpect.spawn(fd) # Note integer fd is used instead of usual string.
m.send("+++") # Escape sequence
m.send("ATZ0\r") # Reset modem to profile 0
rval = m.expect(["OK", "ERROR"])
* ``read()`` was renamed to ``read_nonblocking()``. Added new ``read()`` method
that matches file-like object interface. In general, you should not notice
the difference except that ``read()`` no longer allows you to directly set the
timeout value. I hope this will not effect any existing code. Switching to
``read_nonblocking()`` should fix existing code.
* Changed the name of ``set_echo()`` to ``setecho()``.
* Changed the name of ``send_eof()`` to ``sendeof()``.
* Modified ``kill()`` so that it checks to make sure the pid ``isalive()``.
* modified ``spawn()`` (really called from ``__spawn()``) so that it does not
raise an exception if ``setwinsize()`` fails. Some platforms such as Cygwin
do not like setwinsize. This was a constant problem and since it is not a
critical feature I decided to just silence the error. Normally I don't like
to do that, but in this case I'm making an exception.
* Added a method ``close()`` that does what you think. It closes the file
descriptor of the child application. It makes no attempt to actually kill the
child or wait for its status.
* Add variables ``__version__`` and ``__revision__`` (from cvs) to the pexpect
modules. This is mainly helpful to me so that I can make sure that I'm testing
with the right version instead of one already installed.
* ``log_open()`` and ``log_close(`` have been removed. Now use ``setlog()``.
The ``setlog()`` method takes a file object. This is far more flexible than
the previous log method. Each time data is written to the file object it will
be flushed. To turn logging off simply call ``setlog()`` with None.
* renamed the ``isAlive()`` method to ``isalive()`` to match the more typical
naming style in Python. Also the technique used to detect child process
status has been drastically modified. Previously I did some funky stuff
with signals which caused indigestion in other Python modules on some
platforms. It was a big headache. It still is, but I think it works
better now.
* attribute ``matched`` renamed to ``after``
* new attribute ``match``
* The ``expect_eof()`` method is gone. You can now simply use the
``expect()`` method to look for EOF.
* **Pexpect works on OS X**, but the nature of the quirks cause many of the
tests to fail. See bugs. (Incomplete Child Output). The problem is more
than minor, but Pexpect is still more than useful for most tasks.
* **Solaris**: For some reason, the *second* time a pty file descriptor is created and
deleted it never gets returned for use. It does not effect the first time
or the third time or any time after that. It's only the second time. This
is weird... This could be a file descriptor leak, or it could be some
peculiarity of how Solaris recycles them. I thought it was a UNIX requirement
for the OS to give you the lowest available filedescriptor number. In any case,
this should not be a problem unless you create hundreds of pexpect instances...
It may also be a pty module bug.
Moves and forks
---------------
* Pexpect development used to be hosted on Sourceforge.
* In 2011, Thomas Kluyver forked pexpect as 'pexpect-u', to support
Python 3. He later decided he had taken the wrong approach with this.
* In 2012, Noah Spurrier, the original author of Pexpect, moved the
project to Github, but was still too busy to develop it much.
* In 2013, Thomas Kluyver and Jeff Quast forked Pexpect again, intending
to call the new fork Pexpected. Noah Spurrier agreed to let them use
the name Pexpect, so Pexpect versions 3 and above are based on this
fork, which now lives `here on Github `_.
pexpect-4.8.0/doc/index.rst 0000664 0000000 0000000 00000002775 13610364777 0015632 0 ustar 00root root 0000000 0000000 Pexpect version |version|
=========================
.. image:: https://travis-ci.org/pexpect/pexpect.png?branch=master
:target: https://travis-ci.org/pexpect/pexpect
:align: right
:alt: Build status
Pexpect makes Python a better tool for controlling other
applications.
Pexpect is a pure Python module for spawning child applications;
controlling them; and responding to expected patterns in their output.
Pexpect works like Don Libes' Expect. Pexpect allows your script to
spawn a child application and control it as if a human were typing
commands.
Pexpect can be used for automating interactive applications such as
ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
scripts for duplicating software package installations on different
servers. It can be used for automated software testing. Pexpect is in
the spirit of Don Libes' Expect, but Pexpect is pure Python. Unlike
other Expect-like modules for Python, Pexpect does not require TCL or
Expect nor does it require C extensions to be compiled. It should work
on any platform that supports the standard Python pty module. The
Pexpect interface was designed to be easy to use.
Contents:
.. toctree::
:maxdepth: 2
install
overview
api/index
examples
FAQ
commonissues
history
Pexpect is developed `on Github `_. Please
report `issues `_ there as well.
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
pexpect-4.8.0/doc/install.rst 0000664 0000000 0000000 00000000770 13610364777 0016162 0 ustar 00root root 0000000 0000000 Installation
============
Pexpect is on PyPI, and can be installed with standard tools::
pip install pexpect
Or::
easy_install pexpect
Requirements
------------
This version of Pexpect requires Python 3.3 or above, or Python 2.7.
As of version 4.0, Pexpect can be used on Windows and POSIX systems. However,
:class:`pexpect.spawn` and :func:`pexpect.run` are only available on POSIX,
where the :mod:`pty` module is present in the standard library. See
:ref:`windows` for more information.
pexpect-4.8.0/doc/make.bat 0000664 0000000 0000000 00000011752 13610364777 0015371 0 ustar 00root root 0000000 0000000 @ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^` where ^ is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Pexpect.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Pexpect.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end
pexpect-4.8.0/doc/overview.rst 0000664 0000000 0000000 00000026421 13610364777 0016363 0 ustar 00root root 0000000 0000000 API Overview
============
Pexpect can be used for automating interactive applications such as ssh, ftp,
mencoder, passwd, etc. The Pexpect interface was designed to be easy to use.
Here is an example of Pexpect in action::
# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('Password:')
child.sendline('noah@example.com')
child.expect('ftp> ')
child.sendline('lcd /tmp')
child.expect('ftp> ')
child.sendline('cd pub/OpenBSD')
child.expect('ftp> ')
child.sendline('get README')
child.expect('ftp> ')
child.sendline('bye')
Obviously you could write an ftp client using Python's own :mod:`ftplib` module,
but this is just a demonstration. You can use this technique with any application.
This is especially handy if you are writing automated test tools.
There are two important methods in Pexpect -- :meth:`~pexpect.spawn.expect` and
:meth:`~pexpect.spawn.send` (or :meth:`~pexpect.spawn.sendline` which is
like :meth:`~pexpect.spawn.send` with a linefeed). The :meth:`~pexpect.spawn.expect`
method waits for the child application to return a given string. The string you
specify is a regular expression, so you can match complicated patterns. The
:meth:`~pexpect.spawn.send` method writes a string to the child application.
From the child's point of view it looks just like someone typed the text from a
terminal. After each call to :meth:`~pexpect.spawn.expect` the ``before`` and ``after``
properties will be set to the text printed by child application. The ``before``
property will contain all text up to the expected string pattern. The ``after``
string will contain the text that was matched by the expected pattern.
The match property is set to the `re match object `_.
An example of Pexpect in action may make things more clear. This example uses
ftp to login to the OpenBSD site; list files in a directory; and then pass
interactive control of the ftp session to the human user::
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('ls /pub/OpenBSD/')
child.expect ('ftp> ')
print child.before # Print the result of the ls command.
child.interact() # Give control of the child to the user.
Special EOF and TIMEOUT patterns
--------------------------------
There are two special patterns to match the End Of File (:class:`~pexpect.EOF`)
or a Timeout condition (:class:`~pexpect.TIMEOUT`). You can pass these
patterns to :meth:`~pexpect.spawn.expect`. These patterns are not regular
expressions. Use them like predefined constants.
If the child has died and you have read all the child's output then ordinarily
:meth:`~pexpect.spawn.expect` will raise an :class:`~pexpect.EOF` exception.
You can read everything up to the EOF without generating an exception by using
the EOF pattern expect. In this case everything the child has output will be
available in the ``before`` property.
The pattern given to :meth:`~pexpect.spawn.expect` may be a regular expression
or it may also be a list of regular expressions. This allows you to match
multiple optional responses. The :meth:`~pexpect.spawn.expect` method returns
the index of the pattern that was matched. For example, say you wanted to login
to a server. After entering a password you could get various responses from the
server -- your password could be rejected; or you could be allowed in and asked
for your terminal type; or you could be let right in and given a command prompt.
The following code fragment gives an example of this::
child.expect('password:')
child.sendline(my_secret_password)
# We expect any of these three patterns...
i = child.expect (['Permission denied', 'Terminal type', '[#\$] '])
if i==0:
print('Permission denied on host. Can\'t login')
child.kill(0)
elif i==1:
print('Login OK... need to send terminal type.')
child.sendline('vt100')
child.expect('[#\$] ')
elif i==2:
print('Login OK.')
print('Shell command prompt', child.after)
If nothing matches an expected pattern then :meth:`~pexpect.spawn.expect` will
eventually raise a :class:`~pexpect.TIMEOUT` exception. The default time is 30
seconds, but you can change this by passing a timeout argument to
:meth:`~pexpect.spawn.expect`::
# Wait no more than 2 minutes (120 seconds) for password prompt.
child.expect('password:', timeout=120)
Find the end of line -- CR/LF conventions
-----------------------------------------
Pexpect matches regular expressions a little differently than what you might be
used to.
The :regexp:`$` pattern for end of line match is useless. The :regexp:`$`
matches the end of string, but Pexpect reads from the child one character at a
time, so each character looks like the end of a line. Pexpect can't do a
look-ahead into the child's output stream. In general you would have this
situation when using regular expressions with any stream.
.. note::
Pexpect does have an internal buffer, so reads are faster than one character
at a time, but from the user's perspective the regex patterns test happens
one character at a time.
The best way to match the end of a line is to look for the newline: ``"\r\n"``
(CR/LF). Yes, that does appear to be DOS-style. It may surprise some UNIX people
to learn that terminal TTY device drivers (dumb, vt100, ANSI, xterm, etc.) all
use the CR/LF combination to signify the end of line. Pexpect uses a Pseudo-TTY
device to talk to the child application, so when the child app prints ``"\n"``
you actually see ``"\r\n"``.
UNIX uses just linefeeds to end lines of text, but not when it comes to TTY
devices! TTY devices are more like the Windows world. Each line of text ends
with a CR/LF combination. When you intercept data from a UNIX command from a
TTY device you will find that the TTY device outputs a CR/LF combination. A
UNIX command may only write a linefeed (``\n``), but the TTY device driver
converts it to CR/LF. This means that your terminal will see lines end with
CR/LF (hex ``0D 0A``). Since Pexpect emulates a terminal, to match ends of
lines you have to expect the CR/LF combination::
child.expect('\r\n')
If you just need to skip past a new line then ``expect('\n')`` by itself will
work, but if you are expecting a specific pattern before the end of line then
you need to explicitly look for the ``\r``. For example the following expects a
word at the end of a line::
child.expect('\w+\r\n')
But the following would both fail::
child.expect('\w+\n')
And as explained before, trying to use :regexp:`$` to match the end of line
would not work either::
child.expect ('\w+$')
So if you need to explicitly look for the END OF LINE, you want to look for the
CR/LF combination -- not just the LF and not the $ pattern.
This problem is not limited to Pexpect. This problem happens any time you try
to perform a regular expression match on a stream. Regular expressions need to
look ahead. With a stream it is hard to look ahead because the process
generating the stream may not be finished. There is no way to know if the
process has paused momentarily or is finished and waiting for you. Pexpect must
implicitly always do a NON greedy match (minimal) at the end of a input.
Pexpect compiles all regular expressions with the :data:`re.DOTALL` flag.
With the :data:`~re.DOTALL` flag, a ``"."`` will match a newline.
Beware of + and * at the end of patterns
----------------------------------------
Remember that any time you try to match a pattern that needs look-ahead that
you will always get a minimal match (non greedy). For example, the following
will always return just one character::
child.expect ('.+')
This example will match successfully, but will always return no characters::
child.expect ('.*')
Generally any star * expression will match as little as possible.
One thing you can do is to try to force a non-ambiguous character at the end of
your :regexp:`\\d+` pattern. Expect that character to delimit the string. For
example, you might try making the end of your pattern be :regexp:`\\D+` instead
of :regexp:`\\D*`. Number digits alone would not satisfy the :regexp:`(\\d+)\\D+`
pattern. You would need some numbers and at least one non-number at the end.
Debugging
---------
If you get the string value of a :class:`pexpect.spawn` object you will get lots
of useful debugging information. For debugging it's very useful to use the
following pattern::
try:
i = child.expect ([pattern1, pattern2, pattern3, etc])
except:
print("Exception was thrown")
print("debug information:")
print(str(child))
It is also useful to log the child's input and out to a file or the screen. The
following will turn on logging and send output to stdout (the screen)::
child = pexpect.spawn(foo)
child.logfile = sys.stdout.buffer
The `sys.stdout.buffer` object is available since Python 3. With Python 2, one
has to assign just `sys.stdout` instead.
Exceptions
----------
:class:`~pexpect.EOF`
Note that two flavors of EOF Exception may be thrown. They are virtually
identical except for the message string. For practical purposes you should have
no need to distinguish between them, but they do give a little extra information
about what type of platform you are running. The two messages are:
- "End Of File (EOF) in read(). Exception style platform."
- "End Of File (EOF) in read(). Empty string style platform."
Some UNIX platforms will throw an exception when you try to read from a file
descriptor in the EOF state. Other UNIX platforms instead quietly return an
empty string to indicate that the EOF state has been reached.
If you wish to read up to the end of the child's output without generating an
:class:`~pexpect.EOF` exception then use the ``expect(pexpect.EOF)`` method.
:class:`~pexpect.TIMEOUT`
The :meth:`~pexpect.spawn.expect` and :meth:`~pexpect.spawn.read` methods will
also timeout if the child does not generate any output for a given amount of
time. If this happens they will raise a :class:`~pexpect.TIMEOUT` exception.
You can have these methods ignore timeout and block indefinitely by passing
``None`` for the timeout parameter::
child.expect(pexpect.EOF, timeout=None)
.. _windows:
Pexpect on Windows
------------------
.. versionadded:: 4.0
Windows support
Pexpect can be used on Windows to wait for a pattern to be produced by a child
process, using :class:`pexpect.popen_spawn.PopenSpawn`, or a file descriptor,
using :class:`pexpect.fdpexpect.fdspawn`.
:class:`pexpect.spawn` and :func:`pexpect.run` are *not* available on Windows,
as they rely on Unix pseudoterminals (ptys). Cross platform code must not use
these.
``PopenSpawn`` is not a direct replacement for ``spawn``. Many programs only
offer interactive behaviour if they detect that they are running in a terminal.
When run by ``PopenSpawn``, they may behave differently.
.. seealso::
`winpexpect `__ and `wexpect `__
Two unmaintained pexpect-like modules for Windows, which work with a
hidden console.
pexpect-4.8.0/doc/requirements.txt 0000664 0000000 0000000 00000000013 13610364777 0017234 0 ustar 00root root 0000000 0000000 ptyprocess
pexpect-4.8.0/doc/sphinxext/ 0000775 0000000 0000000 00000000000 13610364777 0016010 5 ustar 00root root 0000000 0000000 pexpect-4.8.0/doc/sphinxext/github.py 0000664 0000000 0000000 00000012403 13610364777 0017644 0 ustar 00root root 0000000 0000000 """Define text roles for GitHub
* ghissue - Issue
* ghpull - Pull Request
* ghuser - User
Adapted from bitbucket example here:
https://bitbucket.org/birkenfeld/sphinx-contrib/src/tip/bitbucket/sphinxcontrib/bitbucket.py
Authors
-------
* Doug Hellmann
* Min RK
"""
#
# Original Copyright (c) 2010 Doug Hellmann. All rights reserved.
#
from docutils import nodes, utils
from docutils.parsers.rst.roles import set_classes
def make_link_node(rawtext, app, type, slug, options):
"""Create a link to a github resource.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param type: Link type (issues, changeset, etc.)
:param slug: ID of the thing to link to
:param options: Options dictionary passed to role func.
"""
try:
base = app.config.github_project_url
if not base:
raise AttributeError
if not base.endswith('/'):
base += '/'
except AttributeError as err:
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
ref = base + type + '/' + slug + '/'
set_classes(options)
prefix = "#"
if type == 'pull':
prefix = "PR " + prefix
node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref,
**options)
return node
def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub issue.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
try:
issue_num = int(text)
if issue_num <= 0:
raise ValueError
except ValueError:
msg = inliner.reporter.error(
'GitHub issue number must be a number greater than or equal to 1; '
'"%s" is invalid.' % text, line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
app = inliner.document.settings.env.app
#app.info('issue %r' % text)
if 'pull' in name.lower():
category = 'pull'
elif 'issue' in name.lower():
category = 'issues'
else:
msg = inliner.reporter.error(
'GitHub roles include "ghpull" and "ghissue", '
'"%s" is invalid.' % name, line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
node = make_link_node(rawtext, app, category, str(issue_num), options)
return [node], []
def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub user.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
app = inliner.document.settings.env.app
#app.info('user link %r' % text)
ref = 'https://www.github.com/' + text
node = nodes.reference(rawtext, text, refuri=ref, **options)
return [node], []
def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub commit.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
app = inliner.document.settings.env.app
#app.info('user link %r' % text)
try:
base = app.config.github_project_url
if not base:
raise AttributeError
if not base.endswith('/'):
base += '/'
except AttributeError as err:
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
ref = base + text
node = nodes.reference(rawtext, text[:6], refuri=ref, **options)
return [node], []
def setup(app):
"""Install the plugin.
:param app: Sphinx application context.
"""
app.info('Initializing GitHub plugin')
app.add_role('ghissue', ghissue_role)
app.add_role('ghpull', ghissue_role)
app.add_role('ghuser', ghuser_role)
app.add_role('ghcommit', ghcommit_role)
app.add_config_value('github_project_url', None, 'env')
return
pexpect-4.8.0/examples/ 0000775 0000000 0000000 00000000000 13610364777 0015027 5 ustar 00root root 0000000 0000000 pexpect-4.8.0/examples/README 0000664 0000000 0000000 00000007677 13610364777 0015730 0 ustar 00root root 0000000 0000000 This directory contains scripts that give examples of using Pexpect.
hive.py
This script creates SSH connections to a list of hosts that
you provide. Then you are given a command line prompt. Each
shell command that you enter is sent to all the hosts. The
response from each host is collected and printed. For example,
you could connect to a dozen different machines and reboot
them all at once.
script.py
This implements a command similar to the classic BSD "script" command.
This will start a subshell and log all input and output to a file.
This demonstrates the interact() method of Pexpect.
fix_cvs_files.py
This is for cleaning up binary files improperly added to
CVS. This script scans the given path to find binary files;
checks with CVS to see if the sticky options are set to -kb;
finally if sticky options are not -kb then uses 'cvs admin'
to set the -kb option.
ftp.py
This demonstrates an FTP "bookmark".
This connects to an ftp site; does a few ftp commands; and then gives the user
interactive control over the session. In this case the "bookmark" is to a
directory on the OpenBSD ftp server. It puts you in the i386 packages
directory. You can easily modify this for other sites.
This demonstrates the interact() method of Pexpect.
monitor.py
This runs a sequence of system status commands on a remote host using SSH.
It runs a simple system checks such as uptime and free to monitor
the state of the remote host.
passmass.py
This will login to a list of hosts and change the password of the
given user. This demonstrates scripting logins; although, you could
more easily do this using the pxssh subclass of Pexpect.
See also the "hive.py" example script for a more general example
of scripting a collection of servers.
python.py
This starts the python interpreter and prints the greeting message backwards.
It then gives the user interactive control of Python. It's pretty useless!
rippy.py
This is a wizard for mencoder. It greatly simplifies the process of
ripping a DVD to mpeg4 format (XviD, DivX). It can transcode from any
video file to another. It has options for resampling the audio stream;
removing interlace artifacts, fitting to a target file size, etc.
There are lots of options, but the process is simple and easy to use.
ssh_tunnel.py
This starts an SSH tunnel to a remote machine. It monitors the connection
and restarts the tunnel if it goes down.
uptime.py
This will run the uptime command and parse the output into python variables.
This demonstrates using a single regular expression to match the output
of a command and capturing different variable in match groups.
The regular expression takes into account a wide variety of different
formats for uptime output.
df.py
This collects filesystem capacity info using the 'df' command.
Tuples of filesystem name and percentage are stored in a list.
A simple report is printed. Filesystems over 95% capacity are highlighted.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
pexpect-4.8.0/examples/astat.py 0000775 0000000 0000000 00000005517 13610364777 0016530 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''This runs Apache Status on the remote host and returns the number of requests per second.
./astat.py [-s server_hostname] [-u username] [-p password]
-s : hostname of the remote server to login to.
-u : username to user for login.
-p : Password to user for login.
Example:
This will print information about the given host:
./astat.py -s www.example.com -u mylogin -p mypassword
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import getopt
import getpass
from pexpect import pxssh
try:
raw_input
except NameError:
raw_input = input
def exit_with_usage():
print(globals()['__doc__'])
os._exit(1)
def main():
######################################################################
## Parse the options, arguments, get ready, etc.
######################################################################
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h?s:u:p:', ['help','h','?'])
except Exception as e:
print(str(e))
exit_with_usage()
options = dict(optlist)
if len(args) > 1:
exit_with_usage()
if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
print("Help:")
exit_with_usage()
if '-s' in options:
hostname = options['-s']
else:
hostname = raw_input('hostname: ')
if '-u' in options:
username = options['-u']
else:
username = raw_input('username: ')
if '-p' in options:
password = options['-p']
else:
password = getpass.getpass('password: ')
#
# Login via SSH
#
p = pxssh.pxssh()
p.login(hostname, username, password)
p.sendline('apachectl status')
p.expect(r'([0-9]+\.[0-9]+)\s*requests/sec')
requests_per_second = p.match.groups()[0]
p.logout()
print(requests_per_second)
if __name__ == "__main__":
main()
pexpect-4.8.0/examples/cgishell.cgi 0000775 0000000 0000000 00000060476 13610364777 0017325 0 ustar 00root root 0000000 0000000 #!/usr/bin/python
##!/usr/bin/env python
"""CGI shell server
This exposes a shell terminal on a web page.
It uses AJAX to send keys and receive screen updates.
The client web browser needs nothing but CSS and Javascript.
--hostname : sets the remote host name to open an ssh connection to.
--username : sets the user name to login with
--password : (optional) sets the password to login with
--port : set the local port for the server to listen on
--watch : show the virtual screen after each client request
This project is probably not the most security conscious thing I've ever built.
This should be considered an experimental tool -- at best.
"""
from __future__ import absolute_import
from __future__ import print_function
import sys,os
sys.path.insert (0,os.getcwd()) # let local modules precede any installed modules
import socket, random, string, traceback, cgi, time, getopt, getpass, threading, resource, signal
import pxssh, pexpect, ANSI
def exit_with_usage(exit_code=1):
print(globals()['__doc__'])
os._exit(exit_code)
def client (command, host='localhost', port=-1):
"""This sends a request to the server and returns the response.
If port <= 0 then host is assumed to be the filename of a Unix domain socket.
If port > 0 then host is an inet hostname.
"""
if port <= 0:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(host)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(command)
data = s.recv (2500)
s.close()
return data
def server (hostname, username, password, socket_filename='/tmp/server_sock', daemon_mode = True, verbose=False):
"""This starts and services requests from a client.
If daemon_mode is True then this forks off a separate daemon process and returns the daemon's pid.
If daemon_mode is False then this does not return until the server is done.
"""
if daemon_mode:
mypid_name = '/tmp/%d.pid' % os.getpid()
daemon_pid = daemonize(daemon_pid_filename=mypid_name)
time.sleep(1)
if daemon_pid != 0:
os.unlink(mypid_name)
return daemon_pid
virtual_screen = ANSI.ANSI (24,80)
child = pxssh.pxssh()
try:
child.login (hostname, username, password, login_naked=True)
except:
return
if verbose: print('login OK')
virtual_screen.write (child.before)
virtual_screen.write (child.after)
if os.path.exists(socket_filename): os.remove(socket_filename)
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.bind(socket_filename)
os.chmod(socket_filename, 0o777)
if verbose: print('Listen')
s.listen(1)
r = roller (endless_poll, (child, child.PROMPT, virtual_screen))
r.start()
if verbose: print("started screen-poll-updater in background thread")
sys.stdout.flush()
try:
while True:
conn, addr = s.accept()
if verbose: print('Connected by', addr)
data = conn.recv(1024)
request = data.split(' ', 1)
if len(request)>1:
cmd = request[0].strip()
arg = request[1].strip()
else:
cmd = request[0].strip()
arg = ''
if cmd == 'exit':
r.cancel()
break
elif cmd == 'sendline':
child.sendline (arg)
time.sleep(0.1)
shell_window = str(virtual_screen)
elif cmd == 'send' or cmd=='xsend':
if cmd=='xsend':
arg = arg.decode("hex")
child.send (arg)
time.sleep(0.1)
shell_window = str(virtual_screen)
elif cmd == 'cursor':
shell_window = '%x,%x' % (virtual_screen.cur_r, virtual_screen.cur_c)
elif cmd == 'refresh':
shell_window = str(virtual_screen)
elif cmd == 'hash':
shell_window = str(hash(str(virtual_screen)))
response = []
response.append (shell_window)
if verbose: print('\n'.join(response))
sent = conn.send('\n'.join(response))
if sent < len (response):
if verbose: print("Sent is too short. Some data was cut off.")
conn.close()
except e:
pass
r.cancel()
if verbose: print("cleaning up socket")
s.close()
if os.path.exists(socket_filename): os.remove(socket_filename)
if verbose: print("server done!")
class roller (threading.Thread):
"""This class continuously loops a function in a thread.
This is basically a thin layer around Thread with a
while loop and a cancel.
"""
def __init__(self, function, args=[], kwargs={}):
threading.Thread.__init__(self)
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = threading.Event()
def cancel(self):
"""Stop the roller."""
self.finished.set()
def run(self):
while not self.finished.isSet():
self.function(*self.args, **self.kwargs)
def endless_poll (child, prompt, screen, refresh_timeout=0.1):
"""This keeps the screen updated with the output of the child.
This will be run in a separate thread. See roller class.
"""
#child.logfile_read = screen
try:
s = child.read_nonblocking(4000, 0.1)
screen.write(s)
except:
pass
def daemonize (stdin=None, stdout=None, stderr=None, daemon_pid_filename=None):
"""This runs the current process in the background as a daemon.
The arguments stdin, stdout, stderr allow you to set the filename that the daemon reads and writes to.
If they are set to None then all stdio for the daemon will be directed to /dev/null.
If daemon_pid_filename is set then the pid of the daemon will be written to it as plain text
and the pid will be returned. If daemon_pid_filename is None then this will return None.
"""
UMASK = 0
WORKINGDIR = "/"
MAXFD = 1024
# The stdio file descriptors are redirected to /dev/null by default.
if hasattr(os, "devnull"):
DEVNULL = os.devnull
else:
DEVNULL = "/dev/null"
if stdin is None: stdin = DEVNULL
if stdout is None: stdout = DEVNULL
if stderr is None: stderr = DEVNULL
try:
pid = os.fork() # fork first child
except OSError as e:
raise Exception("%s [%d]" % (e.strerror, e.errno))
if pid != 0:
os.waitpid(pid,0)
if daemon_pid_filename is not None:
daemon_pid = int(file(daemon_pid_filename,'r').read())
return daemon_pid
else:
return None
# first child
os.setsid()
signal.signal(signal.SIGHUP, signal.SIG_IGN)
try:
pid = os.fork() # fork second child
except OSError as e:
raise Exception("%s [%d]" % (e.strerror, e.errno))
if pid != 0:
if daemon_pid_filename is not None:
file(daemon_pid_filename,'w').write(str(pid))
os._exit(0) # exit parent (the first child) of the second child.
# second child
os.chdir(WORKINGDIR)
os.umask(UMASK)
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if maxfd == resource.RLIM_INFINITY:
maxfd = MAXFD
# close all file descriptors
for fd in range(0, maxfd):
try:
os.close(fd)
except OSError: # fd wasn't open to begin with (ignored)
pass
os.open (DEVNULL, os.O_RDWR) # standard input
# redirect standard file descriptors
si = open(stdin, 'r')
so = open(stdout, 'a+')
se = open(stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
return 0
def client_cgi ():
"""This handles the request if this script was called as a cgi.
"""
sys.stderr = sys.stdout
ajax_mode = False
TITLE="Shell"
SHELL_OUTPUT=""
SID="NOT"
print("Content-type: text/html;charset=utf-8\r\n")
try:
form = cgi.FieldStorage()
if 'ajax' in form:
ajax_mode = True
ajax_cmd = form['ajax'].value
SID=form['sid'].value
if ajax_cmd == 'send':
command = 'xsend'
arg = form['arg'].value.encode('hex')
result = client (command + ' ' + arg, '/tmp/'+SID)
print(result)
elif ajax_cmd == 'refresh':
command = 'refresh'
result = client (command, '/tmp/'+SID)
print(result)
elif ajax_cmd == 'cursor':
command = 'cursor'
result = client (command, '/tmp/'+SID)
print(result)
elif ajax_cmd == 'exit':
command = 'exit'
result = client (command, '/tmp/'+SID)
print(result)
elif ajax_cmd == 'hash':
command = 'hash'
result = client (command, '/tmp/'+SID)
print(result)
elif 'sid' not in form:
SID=random_sid()
print(LOGIN_HTML % locals());
else:
SID=form['sid'].value
if 'start_server' in form:
USERNAME = form['username'].value
PASSWORD = form['password'].value
dpid = server ('127.0.0.1', USERNAME, PASSWORD, '/tmp/'+SID)
SHELL_OUTPUT="daemon pid: " + str(dpid)
else:
if 'cli' in form:
command = 'sendline ' + form['cli'].value
else:
command = 'sendline'
SHELL_OUTPUT = client (command, '/tmp/'+SID)
print(CGISH_HTML % locals())
except:
tb_dump = traceback.format_exc()
if ajax_mode:
print(str(tb_dump))
else:
SHELL_OUTPUT=str(tb_dump)
print(CGISH_HTML % locals())
def server_cli():
"""This is the command line interface to starting the server.
This handles things if the script was not called as a CGI
(if you run it from the command line).
"""
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h?d', ['help','h','?', 'hostname=', 'username=', 'password=', 'port=', 'watch'])
except Exception as e:
print(str(e))
exit_with_usage()
command_line_options = dict(optlist)
options = dict(optlist)
# There are a million ways to cry for help. These are but a few of them.
if [elem for elem in command_line_options if elem in ['-h','--h','-?','--?','--help']]:
exit_with_usage(0)
hostname = "127.0.0.1"
#port = 1664
username = os.getenv('USER')
password = ""
daemon_mode = False
if '-d' in options:
daemon_mode = True
if '--watch' in options:
watch_mode = True
else:
watch_mode = False
if '--hostname' in options:
hostname = options['--hostname']
if '--port' in options:
port = int(options['--port'])
if '--username' in options:
username = options['--username']
if '--password' in options:
password = options['--password']
else:
password = getpass.getpass('password: ')
server (hostname, username, password, '/tmp/mysock', daemon_mode)
def random_sid ():
a=random.randint(0,65535)
b=random.randint(0,65535)
return '%04x%04x.sid' % (a,b)
def parse_host_connect_string (hcs):
"""This parses a host connection string in the form
username:password@hostname:port. All fields are options expcet hostname. A
dictionary is returned with all four keys. Keys that were not included are
set to empty strings ''. Note that if your password has the '@' character
then you must backslash escape it.
"""
if '@' in hcs:
p = re.compile (r'(?P[^@:]*)(:?)(?P.*)(?!\\)@(?P[^:]*):?(?P[0-9]*)')
else:
p = re.compile (r'(?P)(?P)(?P[^:]*):?(?P[0-9]*)')
m = p.search (hcs)
d = m.groupdict()
d['password'] = d['password'].replace('\\@','@')
return d
def pretty_box (s, rows=24, cols=80):
"""This puts an ASCII text box around the given string.
"""
top_bot = '+' + '-'*cols + '+\n'
return top_bot + '\n'.join(['|'+line+'|' for line in s.split('\n')]) + '\n' + top_bot
def main ():
if os.getenv('REQUEST_METHOD') is None:
server_cli()
else:
client_cgi()
# It's mostly HTML and Javascript from here on out.
CGISH_HTML="""
%(TITLE)s %(SID)s
"""
LOGIN_HTML="""
Shell Login
"""
if __name__ == "__main__":
try:
main()
except Exception as e:
print(str(e))
tb_dump = traceback.format_exc()
print(str(tb_dump))
pexpect-4.8.0/examples/chess.py 0000775 0000000 0000000 00000010624 13610364777 0016514 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''This demonstrates controlling a screen oriented application (curses).
It starts two instances of gnuchess and then pits them against each other.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
from __future__ import absolute_import
import pexpect
from pexpect import ANSI
REGEX_MOVE = r'(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)'
REGEX_MOVE_PART = r'(?:[0-9]|\x1b\[C)(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)'
class Chess:
def __init__(self, engine = "/usr/local/bin/gnuchess -a -h 1"):
self.child = pexpect.spawn (engine)
self.term = ANSI.ANSI ()
self.child.expect ('Chess')
if self.child.after != 'Chess':
raise IOError('incompatible chess program')
self.term.process_list (self.before)
self.term.process_list (self.after)
self.last_computer_move = ''
def read_until_cursor (self, r,c):
while 1:
self.child.read(1, 60)
self.term.process (c)
if self.term.cur_r == r and self.term.cur_c == c:
return 1
def do_first_move (self, move):
self.child.expect ('Your move is')
self.child.sendline (move)
self.term.process_list (self.before)
self.term.process_list (self.after)
return move
def do_move (self, move):
self.read_until_cursor (19,60)
self.child.sendline (move)
return move
def get_first_computer_move (self):
self.child.expect ('My move is')
self.child.expect (REGEX_MOVE)
return self.child.after
def get_computer_move (self):
print('Here')
i = self.child.expect ([r'\[17;59H', r'\[17;58H'])
print(i)
if i == 0:
self.child.expect (REGEX_MOVE)
if len(self.child.after) < 4:
self.child.after = self.child.after + self.last_computer_move[3]
if i == 1:
self.child.expect (REGEX_MOVE_PART)
self.child.after = self.last_computer_move[0] + self.child.after
print('', self.child.after)
self.last_computer_move = self.child.after
return self.child.after
def switch (self):
self.child.sendline ('switch')
def set_depth (self, depth):
self.child.sendline ('depth')
self.child.expect ('depth=')
self.child.sendline ('%d' % depth)
def quit(self):
self.child.sendline ('quit')
import sys
print('Starting...')
white = Chess()
white.child.echo = 1
white.child.expect ('Your move is')
white.set_depth(2)
white.switch()
move_white = white.get_first_computer_move()
print('first move white:', move_white)
white.do_move ('e7e5')
move_white = white.get_computer_move()
print('move white:', move_white)
white.do_move ('f8c5')
move_white = white.get_computer_move()
print('move white:', move_white)
white.do_move ('b8a6')
move_white = white.get_computer_move()
print('move white:', move_white)
sys.exit(1)
black = Chess()
white = Chess()
white.child.expect ('Your move is')
white.switch()
move_white = white.get_first_computer_move()
print('first move white:', move_white)
black.do_first_move (move_white)
move_black = black.get_first_computer_move()
print('first move black:', move_black)
white.do_move (move_black)
done = 0
while not done:
move_white = white.get_computer_move()
print('move white:', move_white)
black.do_move (move_white)
move_black = black.get_computer_move()
print('move black:', move_black)
white.do_move (move_black)
print('tail of loop')
g.quit()
pexpect-4.8.0/examples/chess2.py 0000775 0000000 0000000 00000011635 13610364777 0016601 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''This demonstrates controlling a screen oriented application (curses).
It starts two instances of gnuchess and then pits them against each other.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
from __future__ import absolute_import
import pexpect
from pexpect import ANSI
import sys
import time
class Chess:
def __init__(self, engine = "/usr/local/bin/gnuchess -a -h 1"):
self.child = pexpect.spawn (engine)
self.term = ANSI.ANSI ()
#self.child.expect ('Chess')
#if self.child.after != 'Chess':
# raise IOError, 'incompatible chess program'
#self.term.process_list (self.child.before)
#self.term.process_list (self.child.after)
self.last_computer_move = ''
def read_until_cursor (self, r,c, e=0):
'''Eventually something like this should move into the screen class or
a subclass. Maybe a combination of pexpect and screen...
'''
fout = open ('log','a')
while self.term.cur_r != r or self.term.cur_c != c:
try:
k = self.child.read(1, 10)
except Exception as e:
print('EXCEPTION, (r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c))
sys.stdout.flush()
self.term.process (k)
fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c))
fout.flush()
if e:
sys.stdout.write (k)
sys.stdout.flush()
if self.term.cur_r == r and self.term.cur_c == c:
fout.close()
return 1
print('DIDNT EVEN HIT.')
fout.close()
return 1
def expect_region (self):
'''This is another method that would be moved into the
screen class.
'''
pass
def do_scan (self):
fout = open ('log','a')
while 1:
c = self.child.read(1,10)
self.term.process (c)
fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c))
fout.flush()
sys.stdout.write (c)
sys.stdout.flush()
def do_move (self, move, e = 0):
time.sleep(1)
self.read_until_cursor (19,60, e)
self.child.sendline (move)
def wait (self, color):
while 1:
r = self.term.get_region (14,50,14,60)[0]
r = r.strip()
if r == color:
return
time.sleep (1)
def parse_computer_move (self, s):
i = s.find ('is: ')
cm = s[i+3:i+9]
return cm
def get_computer_move (self, e = 0):
time.sleep(1)
self.read_until_cursor (19,60, e)
time.sleep(1)
r = self.term.get_region (17,50,17,62)[0]
cm = self.parse_computer_move (r)
return cm
def switch (self):
print('switching')
self.child.sendline ('switch')
def set_depth (self, depth):
self.child.sendline ('depth')
self.child.expect ('depth=')
self.child.sendline ('%d' % depth)
def quit(self):
self.child.sendline ('quit')
def LOG (s):
print(s)
sys.stdout.flush ()
fout = open ('moves.log', 'a')
fout.write (s + '\n')
fout.close()
print('Starting...')
black = Chess()
white = Chess()
white.read_until_cursor (19,60,1)
white.switch()
done = 0
while not done:
white.wait ('Black')
move_white = white.get_computer_move(1)
LOG ( 'move white:'+ move_white )
black.do_move (move_white)
black.wait ('White')
move_black = black.get_computer_move()
LOG ( 'move black:'+ move_black )
white.do_move (move_black, 1)
g.quit()
pexpect-4.8.0/examples/chess3.py 0000775 0000000 0000000 00000011362 13610364777 0016577 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''This demonstrates controlling a screen oriented application (curses).
It starts two instances of gnuchess and then pits them against each other.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
from __future__ import absolute_import
import pexpect
from pexpect import ANSI
REGEX_MOVE = r'(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)'
REGEX_MOVE_PART = r'(?:[0-9]|\x1b\[C)(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)'
class Chess:
def __init__(self, engine = "/usr/local/bin/gnuchess -a -h 1"):
self.child = pexpect.spawn (engine)
self.term = ANSI.ANSI ()
# self.child.expect ('Chess')
# if self.child.after != 'Chess':
# raise IOError, 'incompatible chess program'
# self.term.process_list (self.before)
# self.term.process_list (self.after)
self.last_computer_move = ''
def read_until_cursor (self, r,c):
fout = open ('log','a')
while 1:
k = self.child.read(1, 10)
self.term.process (k)
fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c))
fout.flush()
if self.term.cur_r == r and self.term.cur_c == c:
fout.close()
return 1
sys.stdout.write (k)
sys.stdout.flush()
def do_scan (self):
fout = open ('log','a')
while 1:
c = self.child.read(1,10)
self.term.process (c)
fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c))
fout.flush()
sys.stdout.write (c)
sys.stdout.flush()
def do_move (self, move):
self.read_until_cursor (19,60)
self.child.sendline (move)
return move
def get_computer_move (self):
print('Here')
i = self.child.expect ([r'\[17;59H', r'\[17;58H'])
print(i)
if i == 0:
self.child.expect (REGEX_MOVE)
if len(self.child.after) < 4:
self.child.after = self.child.after + self.last_computer_move[3]
if i == 1:
self.child.expect (REGEX_MOVE_PART)
self.child.after = self.last_computer_move[0] + self.child.after
print('', self.child.after)
self.last_computer_move = self.child.after
return self.child.after
def switch (self):
self.child.sendline ('switch')
def set_depth (self, depth):
self.child.sendline ('depth')
self.child.expect ('depth=')
self.child.sendline ('%d' % depth)
def quit(self):
self.child.sendline ('quit')
import sys
print('Starting...')
white = Chess()
white.do_move('b2b4')
white.read_until_cursor (19,60)
c1 = white.term.get_abs(17,58)
c2 = white.term.get_abs(17,59)
c3 = white.term.get_abs(17,60)
c4 = white.term.get_abs(17,61)
fout = open ('log','a')
fout.write ('Computer:%s%s%s%s\n' %(c1,c2,c3,c4))
fout.close()
white.do_move('c2c4')
white.read_until_cursor (19,60)
c1 = white.term.get_abs(17,58)
c2 = white.term.get_abs(17,59)
c3 = white.term.get_abs(17,60)
c4 = white.term.get_abs(17,61)
fout = open ('log','a')
fout.write ('Computer:%s%s%s%s\n' %(c1,c2,c3,c4))
fout.close()
white.do_scan ()
#white.do_move ('b8a6')
#move_white = white.get_computer_move()
#print 'move white:', move_white
sys.exit(1)
black = Chess()
white = Chess()
white.child.expect ('Your move is')
white.switch()
move_white = white.get_first_computer_move()
print('first move white:', move_white)
black.do_first_move (move_white)
move_black = black.get_first_computer_move()
print('first move black:', move_black)
white.do_move (move_black)
done = 0
while not done:
move_white = white.get_computer_move()
print('move white:', move_white)
black.do_move (move_white)
move_black = black.get_computer_move()
print('move black:', move_black)
white.do_move (move_black)
print('tail of loop')
g.quit()
pexpect-4.8.0/examples/df.py 0000775 0000000 0000000 00000003666 13610364777 0016010 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''This collects filesystem capacity info using the 'df' command. Tuples of
filesystem name and percentage are stored in a list. A simple report is
printed. Filesystems over 95% capacity are highlighted. Note that this does not
parse filesystem names after the first space, so names with spaces in them will
be truncated. This will produce ambiguous results for automount filesystems on
Apple OSX.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
from __future__ import absolute_import
import pexpect
child = pexpect.spawn ('df')
# parse 'df' output into a list.
pattern = r"\n(\S+).*?([0-9]+)%"
filesystem_list = []
for dummy in range (0, 1000):
i = child.expect ([pattern, pexpect.EOF])
if i == 0:
filesystem_list.append (child.match.groups())
else:
break
# Print report
print()
for m in filesystem_list:
s = "Filesystem %s is at %s%%" % (m[0], m[1])
# highlight filesystems over 95% capacity
if int(m[1]) > 95:
s = '! ' + s
else:
s = ' ' + s
print(s)
pexpect-4.8.0/examples/ftp.py 0000775 0000000 0000000 00000005503 13610364777 0016200 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''This demonstrates an FTP "bookmark". This connects to an ftp site; does a
few ftp stuff; and then gives the user interactive control over the session. In
this case the "bookmark" is to a directory on the OpenBSD ftp server. It puts
you in the i386 packages directory. You can easily modify this for other sites.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import pexpect
import sys
# Note that, for Python 3 compatibility reasons, we are using spawnu and
# importing unicode_literals (above). spawnu accepts Unicode input and
# unicode_literals makes all string literals in this script Unicode by default.
child = pexpect.spawnu('ftp ftp.openbsd.org')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline('pexpect@sourceforge.net')
child.expect('ftp> ')
child.sendline('cd /pub/OpenBSD/3.7/packages/i386')
child.expect('ftp> ')
child.sendline('bin')
child.expect('ftp> ')
child.sendline('prompt')
child.expect('ftp> ')
child.sendline('pwd')
child.expect('ftp> ')
print("Escape character is '^]'.\n")
sys.stdout.write (child.after)
sys.stdout.flush()
child.interact() # Escape character defaults to ^]
# At this point this script blocks until the user presses the escape character
# or until the child exits. The human user and the child should be talking
# to each other now.
# At this point the script is running again.
print('Left interactve mode.')
# The rest is not strictly necessary. This just demonstrates a few functions.
# This makes sure the child is dead; although it would be killed when Python exits.
if child.isalive():
child.sendline('bye') # Try to ask ftp child to exit.
child.close()
# Print the final state of the child. Normally isalive() should be FALSE.
if child.isalive():
print('Child did not exit gracefully.')
else:
print('Child exited gracefully.')
pexpect-4.8.0/examples/hive.py 0000775 0000000 0000000 00000042541 13610364777 0016345 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''hive -- Hive Shell
This lets you ssh to a group of servers and control them as if they were one.
Each command you enter is sent to each host in parallel. The response of each
host is collected and printed. In normal synchronous mode Hive will wait for
each host to return the shell command line prompt. The shell prompt is used to
sync output.
Example:
$ hive.py --sameuser --samepass host1.example.com host2.example.net
username: myusername
password:
connecting to host1.example.com - OK
connecting to host2.example.net - OK
targeting hosts: 192.168.1.104 192.168.1.107
CMD (? for help) > uptime
=======================================================================
host1.example.com
-----------------------------------------------------------------------
uptime
23:49:55 up 74 days, 5:14, 2 users, load average: 0.15, 0.05, 0.01
=======================================================================
host2.example.net
-----------------------------------------------------------------------
uptime
23:53:02 up 1 day, 13:36, 2 users, load average: 0.50, 0.40, 0.46
=======================================================================
Other Usage Examples:
1. You will be asked for your username and password for each host.
hive.py host1 host2 host3 ... hostN
2. You will be asked once for your username and password.
This will be used for each host.
hive.py --sameuser --samepass host1 host2 host3 ... hostN
3. Give a username and password on the command-line:
hive.py user1:pass2@host1 user2:pass2@host2 ... userN:passN@hostN
You can use an extended host notation to specify username, password, and host
instead of entering auth information interactively. Where you would enter a
host name use this format:
username:password@host
This assumes that ':' is not part of the password. If your password contains a
':' then you can use '\\:' to indicate a ':' and '\\\\' to indicate a single
'\\'. Remember that this information will appear in the process listing. Anyone
on your machine can see this auth information. This is not secure.
This is a crude script that begs to be multithreaded. But it serves its
purpose.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
from __future__ import absolute_import
# TODO add feature to support username:password@host combination
# TODO add feature to log each host output in separate file
import sys
import os
import re
import optparse
import time
import getpass
import readline
import atexit
try:
import pexpect
from pexpect import pxssh
except ImportError:
sys.stderr.write("You do not have 'pexpect' installed.\n")
sys.stderr.write("On Ubuntu you need the 'python-pexpect' package.\n")
sys.stderr.write(" aptitude -y install python-pexpect\n")
exit(1)
try:
raw_input
except NameError:
raw_input = input
histfile = os.path.join(os.environ["HOME"], ".hive_history")
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
CMD_HELP='''Hive commands are preceded by a colon : (just think of vi).
:target name1 name2 name3 ...
set list of hosts to target commands
:target all
reset list of hosts to target all hosts in the hive.
:to name command
send a command line to the named host. This is similar to :target, but
sends only one command and does not change the list of targets for future
commands.
:sync
set mode to wait for shell prompts after commands are run. This is the
default. When Hive first logs into a host it sets a special shell prompt
pattern that it can later look for to synchronize output of the hosts. If
you 'su' to another user then it can upset the synchronization. If you need
to run something like 'su' then use the following pattern:
CMD (? for help) > :async
CMD (? for help) > sudo su - root
CMD (? for help) > :prompt
CMD (? for help) > :sync
:async
set mode to not expect command line prompts (see :sync). Afterwards
commands are send to target hosts, but their responses are not read back
until :sync is run. This is useful to run before commands that will not
return with the special shell prompt pattern that Hive uses to synchronize.
:refresh
refresh the display. This shows the last few lines of output from all hosts.
This is similar to resync, but does not expect the promt. This is useful
for seeing what hosts are doing during long running commands.
:resync
This is similar to :sync, but it does not change the mode. It looks for the
prompt and thus consumes all input from all targeted hosts.
:prompt
force each host to reset command line prompt to the special pattern used to
synchronize all the hosts. This is useful if you 'su' to a different user
where Hive would not know the prompt to match.
:send my text
This will send the 'my text' wihtout a line feed to the targeted hosts.
This output of the hosts is not automatically synchronized.
:control X
This will send the given control character to the targeted hosts.
For example, ":control c" will send ASCII 3.
:exit
This will exit the hive shell.
'''
def login (args, cli_username=None, cli_password=None):
# I have to keep a separate list of host names because Python dicts are not ordered.
# I want to keep the same order as in the args list.
host_names = []
hive_connect_info = {}
hive = {}
# build up the list of connection information (hostname, username, password, port)
for host_connect_string in args:
hcd = parse_host_connect_string (host_connect_string)
hostname = hcd['hostname']
port = hcd['port']
if port == '':
port = None
if len(hcd['username']) > 0:
username = hcd['username']
elif cli_username is not None:
username = cli_username
else:
username = raw_input('%s username: ' % hostname)
if len(hcd['password']) > 0:
password = hcd['password']
elif cli_password is not None:
password = cli_password
else:
password = getpass.getpass('%s password: ' % hostname)
host_names.append(hostname)
hive_connect_info[hostname] = (hostname, username, password, port)
# build up the list of hive connections using the connection information.
for hostname in host_names:
print('connecting to', hostname)
try:
fout = file("log_"+hostname, "w")
hive[hostname] = pxssh.pxssh()
# Disable host key checking.
hive[hostname].SSH_OPTS = (hive[hostname].SSH_OPTS
+ " -o 'StrictHostKeyChecking=no'"
+ " -o 'UserKnownHostsFile /dev/null' ")
hive[hostname].force_password = True
hive[hostname].login(*hive_connect_info[hostname])
print(hive[hostname].before)
hive[hostname].logfile = fout
print('- OK')
except Exception as e:
print('- ERROR', end=' ')
print(str(e))
print('Skipping', hostname)
hive[hostname] = None
return host_names, hive
def main ():
global options, args, CMD_HELP
rows = 24
cols = 80
if options.sameuser:
cli_username = raw_input('username: ')
else:
cli_username = None
if options.samepass:
cli_password = getpass.getpass('password: ')
else:
cli_password = None
host_names, hive = login(args, cli_username, cli_password)
synchronous_mode = True
target_hostnames = host_names[:]
print('targeting hosts:', ' '.join(target_hostnames))
while True:
cmd = raw_input('CMD (? for help) > ')
cmd = cmd.strip()
if cmd=='?' or cmd==':help' or cmd==':h':
print(CMD_HELP)
continue
elif cmd==':refresh':
refresh (hive, target_hostnames, timeout=0.5)
for hostname in target_hostnames:
print('/' + '=' * (cols - 2))
print('| ' + hostname)
print('\\' + '-' * (cols - 2))
if hive[hostname] is None:
print('# DEAD: %s' % hostname)
else:
print(hive[hostname].before)
print('#' * 79)
continue
elif cmd==':resync':
resync (hive, target_hostnames, timeout=0.5)
for hostname in target_hostnames:
print('/' + '=' * (cols - 2))
print('| ' + hostname)
print('\\' + '-' * (cols - 2))
if hive[hostname] is None:
print('# DEAD: %s' % hostname)
else:
print(hive[hostname].before)
print('#' * 79)
continue
elif cmd==':sync':
synchronous_mode = True
resync (hive, target_hostnames, timeout=0.5)
continue
elif cmd==':async':
synchronous_mode = False
continue
elif cmd==':prompt':
for hostname in target_hostnames:
try:
if hive[hostname] is not None:
hive[hostname].set_unique_prompt()
except Exception as e:
print("Had trouble communicating with %s, so removing it from the target list." % hostname)
print(str(e))
hive[hostname] = None
continue
elif cmd[:5] == ':send':
cmd, txt = cmd.split(None,1)
for hostname in target_hostnames:
try:
if hive[hostname] is not None:
hive[hostname].send(txt)
except Exception as e:
print("Had trouble communicating with %s, so removing it from the target list." % hostname)
print(str(e))
hive[hostname] = None
continue
elif cmd[:3] == ':to':
cmd, hostname, txt = cmd.split(None,2)
print('/' + '=' * (cols - 2))
print('| ' + hostname)
print('\\' + '-' * (cols - 2))
if hive[hostname] is None:
print('# DEAD: %s' % hostname)
continue
try:
hive[hostname].sendline (txt)
hive[hostname].prompt(timeout=2)
print(hive[hostname].before)
except Exception as e:
print("Had trouble communicating with %s, so removing it from the target list." % hostname)
print(str(e))
hive[hostname] = None
continue
elif cmd[:7] == ':expect':
cmd, pattern = cmd.split(None,1)
print('looking for', pattern)
try:
for hostname in target_hostnames:
if hive[hostname] is not None:
hive[hostname].expect(pattern)
print(hive[hostname].before)
except Exception as e:
print("Had trouble communicating with %s, so removing it from the target list." % hostname)
print(str(e))
hive[hostname] = None
continue
elif cmd[:7] == ':target':
target_hostnames = cmd.split()[1:]
if len(target_hostnames) == 0 or target_hostnames[0] == all:
target_hostnames = host_names[:]
print('targeting hosts:', ' '.join(target_hostnames))
continue
elif cmd == ':exit' or cmd == ':q' or cmd == ':quit':
break
elif cmd[:8] == ':control' or cmd[:5] == ':ctrl' :
cmd, c = cmd.split(None,1)
if ord(c)-96 < 0 or ord(c)-96 > 255:
print('/' + '=' * (cols - 2))
print('| Invalid character. Must be [a-zA-Z], @, [, ], \\, ^, _, or ?')
print('\\' + '-' * (cols - 2))
continue
for hostname in target_hostnames:
try:
if hive[hostname] is not None:
hive[hostname].sendcontrol(c)
except Exception as e:
print("Had trouble communicating with %s, so removing it from the target list." % hostname)
print(str(e))
hive[hostname] = None
continue
elif cmd == ':esc':
for hostname in target_hostnames:
if hive[hostname] is not None:
hive[hostname].send(chr(27))
continue
#
# Run the command on all targets in parallel
#
for hostname in target_hostnames:
try:
if hive[hostname] is not None:
hive[hostname].sendline (cmd)
except Exception as e:
print("Had trouble communicating with %s, so removing it from the target list." % hostname)
print(str(e))
hive[hostname] = None
#
# print the response for each targeted host.
#
if synchronous_mode:
for hostname in target_hostnames:
try:
print('/' + '=' * (cols - 2))
print('| ' + hostname)
print('\\' + '-' * (cols - 2))
if hive[hostname] is None:
print('# DEAD: %s' % hostname)
else:
hive[hostname].prompt(timeout=2)
print(hive[hostname].before)
except Exception as e:
print("Had trouble communicating with %s, so removing it from the target list." % hostname)
print(str(e))
hive[hostname] = None
print('#' * 79)
def refresh (hive, hive_names, timeout=0.5):
'''This waits for the TIMEOUT on each host.
'''
# TODO This is ideal for threading.
for hostname in hive_names:
if hive[hostname] is not None:
hive[hostname].expect([pexpect.TIMEOUT,pexpect.EOF],timeout=timeout)
def resync (hive, hive_names, timeout=2, max_attempts=5):
'''This waits for the shell prompt for each host in an effort to try to get
them all to the same state. The timeout is set low so that hosts that are
already at the prompt will not slow things down too much. If a prompt match
is made for a hosts then keep asking until it stops matching. This is a
best effort to consume all input if it printed more than one prompt. It's
kind of kludgy. Note that this will always introduce a delay equal to the
timeout for each machine. So for 10 machines with a 2 second delay you will
get AT LEAST a 20 second delay if not more. '''
# TODO This is ideal for threading.
for hostname in hive_names:
if hive[hostname] is not None:
for attempts in range(0, max_attempts):
if not hive[hostname].prompt(timeout=timeout):
break
def parse_host_connect_string (hcs):
'''This parses a host connection string in the form
username:password@hostname:port. All fields are optional except hostname. A
dictionary is returned with all four keys. Keys that were not included are
set to empty strings ''. Note that if your password has the '@' character
then you must backslash escape it. '''
if '@' in hcs:
p = re.compile (r'(?P[^@:]*)(:?)(?P.*)(?!\\)@(?P[^:]*):?(?P[0-9]*)')
else:
p = re.compile (r'(?P)(?P)(?P[^:]*):?(?P[0-9]*)')
m = p.search (hcs)
d = m.groupdict()
d['password'] = d['password'].replace('\\@','@')
return d
if __name__ == '__main__':
start_time = time.time()
parser = optparse.OptionParser(formatter=optparse.TitledHelpFormatter(), usage=globals()['__doc__'], version='$Id: hive.py 533 2012-10-20 02:19:33Z noah $',conflict_handler="resolve")
parser.add_option ('-v', '--verbose', action='store_true', default=False, help='verbose output')
parser.add_option ('--samepass', action='store_true', default=False, help='Use same password for each login.')
parser.add_option ('--sameuser', action='store_true', default=False, help='Use same username for each login.')
(options, args) = parser.parse_args()
if len(args) < 1:
parser.error ('missing argument')
if options.verbose: print(time.asctime())
main()
if options.verbose: print(time.asctime())
if options.verbose: print('TOTAL TIME IN MINUTES:', end=' ')
if options.verbose: print((time.time() - start_time) / 60.0)
pexpect-4.8.0/examples/monitor.py 0000775 0000000 0000000 00000016424 13610364777 0017102 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
''' This runs a sequence of commands on a remote host using SSH. It runs a
simple system checks such as uptime and free to monitor the state of the remote
host.
./monitor.py [-s server_hostname] [-u username] [-p password]
-s : hostname of the remote server to login to.
-u : username to user for login.
-p : Password to user for login.
Example:
This will print information about the given host:
./monitor.py -s www.example.com -u mylogin -p mypassword
It works like this:
Login via SSH (This is the hardest part).
Run and parse 'uptime'.
Run 'iostat'.
Run 'vmstat'.
Run 'netstat'
Run 'free'.
Exit the remote host.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
from __future__ import absolute_import
import os, sys, re, getopt, getpass
import pexpect
try:
raw_input
except NameError:
raw_input = input
#
# Some constants.
#
COMMAND_PROMPT = '[#$] ' ### This is way too simple for industrial use -- we will change is ASAP.
TERMINAL_PROMPT = r'(?i)terminal type\?'
TERMINAL_TYPE = 'vt100'
# This is the prompt we get if SSH does not have the remote host's public key stored in the cache.
SSH_NEWKEY = '(?i)are you sure you want to continue connecting'
def exit_with_usage():
print(globals()['__doc__'])
os._exit(1)
def main():
global COMMAND_PROMPT, TERMINAL_PROMPT, TERMINAL_TYPE, SSH_NEWKEY
######################################################################
## Parse the options, arguments, get ready, etc.
######################################################################
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h?s:u:p:', ['help','h','?'])
except Exception as e:
print(str(e))
exit_with_usage()
options = dict(optlist)
if len(args) > 1:
exit_with_usage()
if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
print("Help:")
exit_with_usage()
if '-s' in options:
host = options['-s']
else:
host = raw_input('hostname: ')
if '-u' in options:
user = options['-u']
else:
user = raw_input('username: ')
if '-p' in options:
password = options['-p']
else:
password = getpass.getpass('password: ')
#
# Login via SSH
#
child = pexpect.spawn('ssh -l %s %s'%(user, host))
i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, COMMAND_PROMPT, '(?i)password'])
if i == 0: # Timeout
print('ERROR! could not login with SSH. Here is what SSH said:')
print(child.before, child.after)
print(str(child))
sys.exit (1)
if i == 1: # In this case SSH does not have the public key cached.
child.sendline ('yes')
child.expect ('(?i)password')
if i == 2:
# This may happen if a public key was setup to automatically login.
# But beware, the COMMAND_PROMPT at this point is very trivial and
# could be fooled by some output in the MOTD or login message.
pass
if i == 3:
child.sendline(password)
# Now we are either at the command prompt or
# the login process is asking for our terminal type.
i = child.expect ([COMMAND_PROMPT, TERMINAL_PROMPT])
if i == 1:
child.sendline (TERMINAL_TYPE)
child.expect (COMMAND_PROMPT)
#
# Set command prompt to something more unique.
#
COMMAND_PROMPT = r"\[PEXPECT\]\$ "
child.sendline (r"PS1='[PEXPECT]\$ '") # In case of sh-style
i = child.expect ([pexpect.TIMEOUT, COMMAND_PROMPT], timeout=10)
if i == 0:
print("# Couldn't set sh-style prompt -- trying csh-style.")
child.sendline (r"set prompt='[PEXPECT]\$ '")
i = child.expect ([pexpect.TIMEOUT, COMMAND_PROMPT], timeout=10)
if i == 0:
print("Failed to set command prompt using sh or csh style.")
print("Response was:")
print(child.before)
sys.exit (1)
# Now we should be at the command prompt and ready to run some commands.
print('---------------------------------------')
print('Report of commands run on remote host.')
print('---------------------------------------')
# Run uname.
child.sendline ('uname -a')
child.expect (COMMAND_PROMPT)
print(child.before)
if 'linux' in child.before.lower():
LINUX_MODE = 1
else:
LINUX_MODE = 0
# Run and parse 'uptime'.
child.sendline ('uptime')
child.expect(r'up\s+(.*?),\s+([0-9]+) users?,\s+load averages?: ([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9])')
duration, users, av1, av5, av15 = child.match.groups()
days = '0'
hours = '0'
mins = '0'
if 'day' in duration:
child.match = re.search(r'([0-9]+)\s+day',duration)
days = str(int(child.match.group(1)))
if ':' in duration:
child.match = re.search('([0-9]+):([0-9]+)',duration)
hours = str(int(child.match.group(1)))
mins = str(int(child.match.group(2)))
if 'min' in duration:
child.match = re.search(r'([0-9]+)\s+min',duration)
mins = str(int(child.match.group(1)))
print()
print('Uptime: %s days, %s users, %s (1 min), %s (5 min), %s (15 min)' % (
duration, users, av1, av5, av15))
child.expect (COMMAND_PROMPT)
# Run iostat.
child.sendline ('iostat')
child.expect (COMMAND_PROMPT)
print(child.before)
# Run vmstat.
child.sendline ('vmstat')
child.expect (COMMAND_PROMPT)
print(child.before)
# Run free.
if LINUX_MODE:
child.sendline ('free') # Linux systems only.
child.expect (COMMAND_PROMPT)
print(child.before)
# Run df.
child.sendline ('df')
child.expect (COMMAND_PROMPT)
print(child.before)
# Run lsof.
child.sendline ('lsof')
child.expect (COMMAND_PROMPT)
print(child.before)
# # Run netstat
# child.sendline ('netstat')
# child.expect (COMMAND_PROMPT)
# print child.before
# # Run MySQL show status.
# child.sendline ('mysql -p -e "SHOW STATUS;"')
# child.expect (PASSWORD_PROMPT_MYSQL)
# child.sendline (password_mysql)
# child.expect (COMMAND_PROMPT)
# print
# print child.before
# Now exit the remote host.
child.sendline ('exit')
index = child.expect([pexpect.EOF, "(?i)there are stopped jobs"])
if index==1:
child.sendline("exit")
child.expect(EOF)
if __name__ == "__main__":
main()
pexpect-4.8.0/examples/passmass.py 0000775 0000000 0000000 00000007677 13610364777 0017257 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''Change passwords on the named machines. passmass host1 host2 host3 . . .
Note that login shell prompt on remote machine must end in # or $.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
from __future__ import absolute_import
import pexpect
import sys, getpass
try:
raw_input
except NameError:
raw_input = input
USAGE = '''passmass host1 host2 host3 . . .'''
COMMAND_PROMPT = '[$#] '
TERMINAL_PROMPT = r'Terminal type\?'
TERMINAL_TYPE = 'vt100'
SSH_NEWKEY = r'Are you sure you want to continue connecting \(yes/no\)\?'
def login(host, user, password):
child = pexpect.spawn('ssh -l %s %s'%(user, host))
fout = file ("LOG.TXT","wb")
child.logfile_read = fout #use child.logfile to also log writes (passwords!)
i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, '[Pp]assword: '])
if i == 0: # Timeout
print('ERROR!')
print('SSH could not login. Here is what SSH said:')
print(child.before, child.after)
sys.exit (1)
if i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
child.expect ('[Pp]assword: ')
child.sendline(password)
# Now we are either at the command prompt or
# the login process is asking for our terminal type.
i = child.expect (['Permission denied', TERMINAL_PROMPT, COMMAND_PROMPT])
if i == 0:
print('Permission denied on host:', host)
sys.exit (1)
if i == 1:
child.sendline (TERMINAL_TYPE)
child.expect (COMMAND_PROMPT)
return child
# (current) UNIX password:
def change_password(child, user, oldpassword, newpassword):
child.sendline('passwd')
i = child.expect(['[Oo]ld [Pp]assword', '.current.*password', '[Nn]ew [Pp]assword'])
# Root does not require old password, so it gets to bypass the next step.
if i == 0 or i == 1:
child.sendline(oldpassword)
child.expect('[Nn]ew [Pp]assword')
child.sendline(newpassword)
i = child.expect(['[Nn]ew [Pp]assword', '[Rr]etype', '[Rr]e-enter'])
if i == 0:
print('Host did not like new password. Here is what it said...')
print(child.before)
child.send (chr(3)) # Ctrl-C
child.sendline('') # This should tell remote passwd command to quit.
return
child.sendline(newpassword)
def main():
if len(sys.argv) <= 1:
print(USAGE)
return 1
user = raw_input('Username: ')
password = getpass.getpass('Current Password: ')
newpassword = getpass.getpass('New Password: ')
newpasswordconfirm = getpass.getpass('Confirm New Password: ')
if newpassword != newpasswordconfirm:
print('New Passwords do not match.')
return 1
for host in sys.argv[1:]:
child = login(host, user, password)
if child == None:
print('Could not login to host:', host)
continue
print('Changing password on host:', host)
change_password(child, user, password, newpassword)
child.expect(COMMAND_PROMPT)
child.sendline('exit')
if __name__ == '__main__':
main()
pexpect-4.8.0/examples/python.py 0000775 0000000 0000000 00000003550 13610364777 0016730 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''This starts the python interpreter; captures the startup message; then gives
the user interactive control over the session. Why? For fun...
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import pexpect
# Don't do this unless you like being John Malkovich
# c = pexpect.spawnu('/usr/bin/env python ./python.py')
# Note that, for Python 3 compatibility reasons, we are using spawnu and
# importing unicode_literals (above). spawnu accepts Unicode input and
# unicode_literals makes all string literals in this script Unicode by default.
c = pexpect.spawnu('/usr/bin/env python')
c.expect('>>>')
print('And now for something completely different...')
print(''.join(reversed((c.before))))
print('Yes, it\'s python, but it\'s backwards.')
print()
print('Escape character is \'^]\'.')
print(c.after, end=' ')
c.interact()
c.kill(1)
print('is alive:', c.isalive())
pexpect-4.8.0/examples/script.py 0000775 0000000 0000000 00000007377 13610364777 0016726 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''This spawns a sub-shell (bash) and gives the user interactive control. The
entire shell session is logged to a file called script.log. This behaves much
like the classic BSD command 'script'.
./script.py [-a] [-c command] {logfilename}
logfilename : This is the name of the log file. Default is script.log.
-a : Append to log file. Default is to overwrite log file.
-c : spawn command. Default is to spawn the sh shell.
Example:
This will start a bash shell and append to the log named my_session.log:
./script.py -a -c bash my_session.log
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
from __future__ import absolute_import
import os, sys, time, getopt
import signal, fcntl, termios, struct
import pexpect
global_pexpect_instance = None # Used by signal handler
def exit_with_usage():
print(globals()['__doc__'])
os._exit(1)
def main():
######################################################################
# Parse the options, arguments, get ready, etc.
######################################################################
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h?ac:', ['help','h','?'])
except Exception as e:
print(str(e))
exit_with_usage()
options = dict(optlist)
if len(args) > 1:
exit_with_usage()
if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
print("Help:")
exit_with_usage()
if len(args) == 1:
script_filename = args[0]
else:
script_filename = "script.log"
if '-a' in options:
fout = open(script_filename, "ab")
else:
fout = open(script_filename, "wb")
if '-c' in options:
command = options['-c']
else:
command = "sh"
# Begin log with date/time in the form CCCCyymm.hhmmss
fout.write ('# %4d%02d%02d.%02d%02d%02d \n' % time.localtime()[:-3])
######################################################################
# Start the interactive session
######################################################################
p = pexpect.spawn(command)
p.logfile = fout
global global_pexpect_instance
global_pexpect_instance = p
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
print("Script recording started. Type ^] (ASCII 29) to escape from the script shell.")
p.interact(chr(29))
fout.close()
return 0
def sigwinch_passthrough (sig, data):
# Check for buggy platforms (see pexpect.setwinsize()).
if 'TIOCGWINSZ' in dir(termios):
TIOCGWINSZ = termios.TIOCGWINSZ
else:
TIOCGWINSZ = 1074295912 # assume
s = struct.pack ("HHHH", 0, 0, 0, 0)
a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s))
global global_pexpect_instance
global_pexpect_instance.setwinsize(a[0],a[1])
if __name__ == "__main__":
main()
pexpect-4.8.0/examples/ssh_tunnel.py 0000775 0000000 0000000 00000006635 13610364777 0017600 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
'''This starts an SSH tunnel to a given host. If the SSH process ever dies then
this script will detect that and restart it. I use this under Cygwin to keep
open encrypted tunnels to port 25 (SMTP), port 143 (IMAP4), and port 110
(POP3). I set my mail client to talk to localhost and I keep this script
running in the background.
Note that this is a rather stupid script at the moment because it just looks to
see if any ssh process is running. It should really make sure that our specific
ssh process is running. The problem is that ssh is missing a very useful
feature. It has no way to report the process id of the background daemon that
it creates with the -f command. This would be a really useful script if I could
figure a way around this problem.
PEXPECT LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2012, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from __future__ import print_function
from __future__ import absolute_import
import pexpect
import getpass
import time
try:
raw_input
except NameError:
raw_input = input
# SMTP:25 IMAP4:143 POP3:110
tunnel_command = 'ssh -C -N -f -L 25:127.0.0.1:25 -L 143:127.0.0.1:143 -L 110:127.0.0.1:110 %(user)@%(host)'
host = raw_input('Hostname: ')
user = raw_input('Username: ')
X = getpass.getpass('Password: ')
def get_process_info ():
# This seems to work on both Linux and BSD, but should otherwise be considered highly UNportable.
ps = pexpect.run ('ps ax -O ppid')
pass
def start_tunnel ():
try:
ssh_tunnel = pexpect.spawn (tunnel_command % globals())
ssh_tunnel.expect ('password:')
time.sleep (0.1)
ssh_tunnel.sendline (X)
time.sleep (60) # Cygwin is slow to update process status.
ssh_tunnel.expect (pexpect.EOF)
except Exception as e:
print(str(e))
def main ():
while True:
ps = pexpect.spawn ('ps')
time.sleep (1)
index = ps.expect (['/usr/bin/ssh', pexpect.EOF, pexpect.TIMEOUT])
if index == 2:
print('TIMEOUT in ps command...')
print(str(ps))
time.sleep (13)
if index == 1:
print(time.asctime(), end=' ')
print('restarting tunnel')
start_tunnel ()
time.sleep (11)
print('tunnel OK')
else:
# print 'tunnel OK'
time.sleep (7)
if __name__ == '__main__':
main ()
# This was for older SSH versions that didn't have -f option
#tunnel_command = 'ssh -C -n -L 25:%(host)s:25 -L 110:%(host)s:110 %(user)s@%(host)s -f nothing.sh'
#nothing_script = '''#!/bin/sh
#while true; do sleep 53; done
#'''
pexpect-4.8.0/examples/table_test.html 0000664 0000000 0000000 00000007640 13610364777 0020052 0 ustar 00root root 0000000 0000000
TEST