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.

This class extends pexpect.spawn to specialize setting up SSH connections. This adds methods for login, logout, and expecting the shell prompt.

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 <noah@noah.org> 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.

class pexpect.pxssh.ExceptionPxssh(value)[source]

Raised for pxssh exceptions.

pxssh class

class pexpect.pxssh.pxssh(timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None, ignore_sighup=True, echo=True, options={}, encoding=None, codec_errors='strict', debug_command_string=False, use_poll=False)[source]

This class extends pexpect.spawn to specialize setting up SSH connections. This adds methods for login, logout, and expecting the shell prompt. It does various tricky things to handle many situations in the SSH login process. For example, if the session is your first login, then pxssh automatically accepts the remote certificate; or if you have public key authentication setup then pxssh won’t wait for the password prompt.

pxssh uses the shell prompt to synchronize output from the remote host. In order to make this more robust it sets the shell prompt to something more unique than just $ or #. This should work on most Borne/Bash or Csh style shells.

Example that runs a few commands on a remote server and prints the result:

from pexpect import pxssh
import getpass
try:
    s = pxssh.pxssh()
    hostname = raw_input('hostname: ')
    username = raw_input('username: ')
    password = getpass.getpass('password: ')
    s.login(hostname, username, password)
    s.sendline('uptime')   # run a command
    s.prompt()             # match the prompt
    print(s.before)        # print everything before the prompt.
    s.sendline('ls -l')
    s.prompt()
    print(s.before)
    s.sendline('df')
    s.prompt()
    print(s.before)
    s.logout()
except pxssh.ExceptionPxssh as e:
    print("pxssh failed on login.")
    print(e)

Example showing how to specify SSH options:

from pexpect import pxssh
s = pxssh.pxssh(options={
                    "StrictHostKeyChecking": "no",
                    "UserKnownHostsFile": "/dev/null"})
...

Note that if you have ssh-agent running while doing development with pxssh then this can lead to a lot of confusion. Many X display managers (xdm, gdm, kdm, etc.) will automatically start a GUI agent. You may see a GUI dialog box popup asking for a password during development. You should turn off any key agents during testing. The ‘force_password’ attribute will turn off public key authentication. This will only work if the remote SSH server is configured to allow password logins. Example of using ‘force_password’ attribute:

s = pxssh.pxssh()
s.force_password = True
hostname = raw_input('hostname: ')
username = raw_input('username: ')
password = getpass.getpass('password: ')
s.login (hostname, username, password)

debug_command_string is only for the test suite to confirm that the string generated for SSH is correct, using this will not allow you to do anything other than get a string back from pxssh.pxssh.login().

__init__(timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None, ignore_sighup=True, echo=True, options={}, encoding=None, codec_errors='strict', debug_command_string=False, use_poll=False)[source]

This is the constructor. The command parameter may be a string that includes a command and any arguments to the command. For example:

child = pexpect.spawn('/usr/bin/ftp')
child = pexpect.spawn('/usr/bin/ssh user@example.com')
child = pexpect.spawn('ls -latr /tmp')

You may also construct it with a list of arguments like so:

child = pexpect.spawn('/usr/bin/ftp', [])
child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])
child = pexpect.spawn('ls', ['-latr', '/tmp'])

After this the child application will be created and will be ready to talk to. For normal use, see expect() and send() and sendline().

Remember that Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (>, |, or *). 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 > logs.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 > logs.txt'
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
child.expect(pexpect.EOF)

The maxread attribute sets the read buffer size. This is maximum number of bytes that Pexpect will try to read from a TTY at one time. Setting the maxread size to 1 will turn off buffering. Setting the maxread value higher may help performance in cases where large amounts of output are read back from the child. This feature is useful in conjunction with searchwindowsize.

When the keyword argument searchwindowsize is None (default), the full buffer is searched at each iteration of receiving incoming data. The default number of bytes scanned at each iteration is very large and may be reduced to collaterally reduce search cost. After expect() returns, the full buffer attribute remains up to size maxread irrespective of searchwindowsize value.

When the keyword argument timeout is specified as a number, (default: 30), then TIMEOUT will be raised after the value specified has elapsed, in seconds, for any of the expect() family of method calls. When None, TIMEOUT will not be raised, and expect() may block indefinitely until match.

The logfile member turns on or off logging. All input and output will be copied to the given file object. Set logfile to None to stop logging. This is the default. Set logfile to sys.stdout to echo everything to standard output. The logfile is flushed after each write.

Example log input and output to a file:

child = pexpect.spawn('some_command')
fout = open('mylog.txt','wb')
child.logfile = fout

Example log to stdout:

# In Python 2:
child = pexpect.spawn('some_command')
child.logfile = sys.stdout

# In Python 3, we'll use the ``encoding`` argument to decode data
# from the subprocess and handle it as unicode:
child = pexpect.spawn('some_command', encoding='utf-8')
child.logfile = sys.stdout

The logfile_read and logfile_send members can be used to separately log the input from the child and output sent to the child. Sometimes you don’t want to see everything you write to the child. You only want to log what the child sends back. For example:

child = pexpect.spawn('some_command')
child.logfile_read = sys.stdout

You will need to pass an encoding to spawn in the above code if you are using Python 3.

To separately log output sent to the child use logfile_send:

child.logfile_send = fout

If ignore_sighup is True, the child process will ignore SIGHUP signals. The default is False from Pexpect 4.0, meaning that SIGHUP will be handled normally by the child.

The delaybeforesend helps overcome a weird behavior that many users were experiencing. The typical problem was that a user would expect() a “Password:” prompt and then immediately call sendline() to send the password. The user would then see that their password was echoed back to them. Passwords don’t normally echo. The problem is caused by the fact that most applications print out the “Password” prompt and then turn off stdin echo, but if you send your password before the application turned off echo, then you get your password echoed. Normally this wouldn’t be a problem when interacting with a human at a real keyboard. If you introduce a slight delay just before writing then this seems to clear up the problem. This was such a common problem for many users that I decided that the default pexpect behavior should be to sleep just before writing to the child application. 1/20th of a second (50 ms) seems to be enough to clear up the problem. You can set delaybeforesend to None to return to the old behavior.

Note that spawn is clever about finding commands on your path. It uses the same logic that “which” uses to find executables.

If you wish to get the exit status of the child you must call the close() method. The exit or signal status of the child will be stored in self.exitstatus or self.signalstatus. If the child exited normally then exitstatus will store the exit return code and signalstatus will be None. If the child was terminated abnormally with a signal then signalstatus will store the signal value and exitstatus will be None:

child = pexpect.spawn('some_command')
child.close()
print(child.exitstatus, child.signalstatus)

If you need more detail you can also read the self.status member which stores the status returned by os.waitpid. You can interpret this using os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.

The echo attribute may be set to False to disable echoing of input. As a pseudo-terminal, all input echoed by the “keyboard” (send() or sendline()) will be repeated to output. For many cases, it is not desirable to have echo enabled, and it may be later disabled using setecho(False) followed by waitnoecho(). However, for some platforms such as Solaris, this is not possible, and should be disabled immediately on spawn.

If preexec_fn is given, it will be called in the child process before launching the given command. This is useful to e.g. reset inherited signal handlers.

The dimensions attribute specifies the size of the pseudo-terminal as seen by the subprocess, and is specified as a two-entry tuple (rows, columns). If this is unspecified, the defaults in ptyprocess will apply.

The use_poll attribute enables using select.poll() over select.select() for socket handling. This is handy if your system could have > 1024 fds

PROMPT

The regex pattern to search for to find the prompt. If you call login() with auto_prompt_reset=False, you must set this attribute manually.

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.

options

The dictionary of user specified SSH options, eg, options = dict(StrictHostKeyChecking="no", UserKnownHostsFile="/dev/null")

login(server, username=None, password='', terminal_type='ansi', original_prompt='[#$]', login_timeout=10, port=None, auto_prompt_reset=True, ssh_key=None, quiet=True, sync_multiplier=1, check_local_ip=True, password_regex='(?i)(?:password:)|(?:passphrase for key)', ssh_tunnels={}, spawn_local_ssh=True, sync_original_prompt=True, ssh_config=None, cmd='ssh')[source]

This logs the user into the given server.

It uses ‘original_prompt’ to try to find the prompt right after login. When it finds the prompt it immediately tries to reset the prompt to something more easily matched. The default ‘original_prompt’ is very optimistic and is easily fooled. It’s more reliable to try to match the original prompt as exactly as possible to prevent false matches by server strings such as the “Message Of The Day”. On many systems you can disable the MOTD on the remote server by creating a zero-length file called ~/.hushlogin on the remote server. If a prompt cannot be found then this will not necessarily cause the login to fail. In the case of a timeout when looking for the prompt we assume that the original prompt was so weird that we could not match it, so we use a few tricks to guess when we have reached the prompt. Then we hope for the best and blindly try to reset the prompt to something more unique. If that fails then login() raises an ExceptionPxssh exception.

In some situations it is not possible or desirable to reset the original prompt. In this case, pass auto_prompt_reset=False to inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh uses a unique prompt in the prompt() method. If the original prompt is not reset then this will disable the prompt() method unless you manually set the PROMPT attribute.

Set password_regex if there is a MOTD message with password in it. Changing this is like playing in traffic, don’t (p)expect it to match straight away.

If you require to connect to another SSH server from the your original SSH connection set spawn_local_ssh to False and this will use your current session to do so. Setting this option to False and not having an active session will trigger an error.

Set ssh_key to a file path to an SSH private key to use that SSH key for the session authentication. Set ssh_key to True to force passing the current SSH authentication socket to the desired hostname.

Set ssh_config to a file path string of an SSH client config file to pass that file to the client to handle itself. You may set any options you wish in here, however doing so will require you to post extra information that you may not want to if you run into issues.

Alter the cmd to change the ssh client used, or to prepend it with network namespaces. For example `cmd="ip netns exec vlan2 ssh"` to execute the ssh in network namespace named `vlan`.

logout()[source]

Sends exit to the remote shell.

If there are stopped jobs then this automatically sends exit twice.

prompt(timeout=-1)[source]

Match the next shell prompt.

This is little more than a short-cut to the expect() method. Note that if you called login() with auto_prompt_reset=False, then before calling prompt() you must set the PROMPT attribute to a regex that it will use for matching the prompt.

Calling prompt() will erase the contents of the before attribute even if no prompt is ever matched. If timeout is not given or it is set to -1 then self.timeout is used.

Returns

True if the shell prompt was matched, False if the timeout was reached.

sync_original_prompt(sync_multiplier=1.0)[source]

This attempts to find the prompt. Basically, press enter and record the response; press enter again and record the response; if the two responses are similar then assume we are at the original prompt. This can be a slow function. Worst case with the default sync_multiplier can take 12 seconds. Low latency connections are more likely to fail with a low sync_multiplier. Best case sync time gets worse with a high sync multiplier (500 ms with default).

set_unique_prompt()[source]

This sets the remote prompt to something more unique than # or $. This makes it easier for the prompt() method to match the shell prompt unambiguously. This method is called automatically by the login() method, but you may want to call it manually if you somehow reset the shell prompt. For example, if you ‘su’ to a different user then you will need to manually reset the prompt. This sends shell commands to the remote host to set the prompt, so this assumes the remote host is ready to receive commands.

Alternatively, you may use your own prompt pattern. In this case you should call login() with auto_prompt_reset=False; then set the PROMPT attribute to a regular expression. After that, the prompt() method will try to match your prompt pattern.