Openssh Python



  1. Python Openssh Windows
  2. Python Ssh Module

SSH (secure shell) is good for remotely managing machines using a secure connection. Typically you will log in to a server using the command-line ssh tool, or something like PuTTy or MobaXTerm. This guide will show you how to use Python to connect and run commands over SSH using the Paramiko package. Paramiko Documentation. -type f -iname '.'.

Note

Github

pxssh is a screen-scraping wrapper around the SSH command on your system.In many cases, you should consider usingParamiko orRedExpect instead.Paramiko is a Python module which speaks the SSH protocol directly, so itdoesn’t have the extra complexity of running a local subprocess.RedExpect is very similar to pxssh except that it reads and writes directlyinto 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 justLinux machines. Meaning that it is extremely fast in comparison to Paramikoand already has the familiar expect API. In most cases RedExpect and pxsshcode 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 ANYPURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVECOPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIESWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OFMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FORANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGESWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN ANACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OFOR 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 SSHconnections. This adds methods for login, logout, and expecting the shellprompt. It does various tricky things to handle many situations in the SSHlogin process. For example, if the session is your first login, then pxsshautomatically accepts the remote certificate; or if you have public keyauthentication setup then pxssh won’t wait for the password prompt.

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

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

Example showing how to specify SSH options:

Note that if you have ssh-agent running while doing development with pxsshthen 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 GUIdialog box popup asking for a password during development. You should turnoff any key agents during testing. The ‘force_password’ attribute will turnoff public key authentication. This will only work if the remote SSH serveris configured to allow password logins. Example of using ‘force_password’attribute:

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

Python Openssh Windows

__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 thatincludes a command and any arguments to the command. For example:

Python

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

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

Remember that Pexpect does NOT interpret shell meta characters such asredirect, pipe, or wild cards (>, |, or *). This is acommon mistake. If you want to run a command and pipe it throughanother command then you must also start a shell. For example:

The second form of spawn (where you pass a list of arguments) is usefulin situations where you wish to spawn a command and pass it its ownargument list. This can make syntax more clear. For example, thefollowing is equivalent to the previous example:

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

Ssh

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

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

The logfile member turns on or off logging. All input and output willbe copied to the given file object. Set logfile to None to stoplogging. This is the default. Set logfile to sys.stdout to echoeverything to standard output. The logfile is flushed after each write.

Example log input and output to a file:

Example log to stdout:

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

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

To separately log output sent to the child use logfile_send:

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

The delaybeforesend helps overcome a weird behavior that many userswere experiencing. The typical problem was that a user would expect() a“Password:” prompt and then immediately call sendline() to send thepassword. The user would then see that their password was echoed backto them. Passwords don’t normally echo. The problem is caused by thefact that most applications print out the “Password” prompt and thenturn off stdin echo, but if you send your password before theapplication turned off echo, then you get your password echoed.Normally this wouldn’t be a problem when interacting with a human at areal keyboard. If you introduce a slight delay just before writing thenthis seems to clear up the problem. This was such a common problem formany users that I decided that the default pexpect behavior should beto sleep just before writing to the child application. 1/20th of asecond (50 ms) seems to be enough to clear up the problem. You can setdelaybeforesend 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 theclose() method. The exit or signal status of the child will be storedin self.exitstatus or self.signalstatus. If the child exited normallythen exitstatus will store the exit return code and signalstatus willbe None. If the child was terminated abnormally with a signal thensignalstatus will store the signal value and exitstatus will be None:

If you need more detail you can also read the self.status member whichstores the status returned by os.waitpid. You can interpret this usingos.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 isnot desirable to have echo enabled, and it may be later disabledusing setecho(False) followed by waitnoecho(). However, for someplatforms such as Solaris, this is not possible, and should bedisabled immediately on spawn.

If preexec_fn is given, it will be called in the child process beforelaunching the given command. This is useful to e.g. reset inheritedsignal handlers.

The dimensions attribute specifies the size of the pseudo-terminal asseen 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 theserver to ask for a password. Note that the sysadmin can disable passwordlogins, 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 tosomething more easily matched. The default ‘original_prompt’ is veryoptimistic and is easily fooled. It’s more reliable to try to match the originalprompt as exactly as possible to prevent false matches by serverstrings such as the “Message Of The Day”. On many systems you candisable the MOTD on the remote server by creating a zero-length filecalled ~/.hushlogin on the remote server. If a prompt cannot be foundthen this will not necessarily cause the login to fail. In the case ofa timeout when looking for the prompt we assume that the originalprompt was so weird that we could not match it, so we use a few tricksto guess when we have reached the prompt. Then we hope for the best andblindly try to reset the prompt to something more unique. If that failsthen login() raises an ExceptionPxssh exception.

In some situations it is not possible or desirable to reset theoriginal prompt. In this case, pass auto_prompt_reset=False toinhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxsshuses a unique prompt in the prompt() method. If the original prompt isnot reset then this will disable the prompt() method unless youmanually 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 straightaway.

Openssh Python

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

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

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

Alter the cmd to change the ssh client used, or to prepend it with networknamespaces. For example `cmd='ipnetnsexecvlan2ssh'` to execute the ssh innetwork 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() withauto_prompt_reset=False, then before calling prompt() you mustset the PROMPT attribute to a regex that it will use formatching the prompt.

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

Python Ssh Module

Returns:True if the shell prompt was matched, False if the timeout wasreached.
sync_original_prompt(sync_multiplier=1.0)[source]

This attempts to find the prompt. Basically, press enter and recordthe response; press enter again and record the response; if the tworesponses are similar then assume we are at the original prompt.This can be a slow function. Worst case with the default sync_multipliercan take 12 seconds. Low latency connections are more likely to failwith a low sync_multiplier. Best case sync time gets worse with ahigh 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 promptunambiguously. This method is called automatically by the login()method, but you may want to call it manually if you somehow reset theshell prompt. For example, if you ‘su’ to a different user then youwill need to manually reset the prompt. This sends shell commands tothe remote host to set the prompt, so this assumes the remote host isready to receive commands.

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