With Paramiko , you can do a ssh2 secure connection via python, you can also use remote command, file transfer and ssh proxy, etc.

Install paramiko:

To install paramiko, we need the dependencies python-dev ,and modules pycrypto and ecdsa.

apt-get install python-dev

Centos:

yum -y install python-devel
pip install pycrypto ecdsa

Then install paramiko

pip install paramiko

To test the success of the installation:

# python
Python 2.6.6 r26684292Jul 10 2013224845[GCC 4.4.7 20120313 Red Hat 4.4.7-3] on linux2
Type "help""copyright""credits" or "license" for more information.
>>> import paramiko
>>>

If there is no error message, then it means you installed the module successfully.

core class

There are two core classes: SSHClient class and SFTPClient class.

1, SSHClient class

We can use the methods to connect, transport, build channel, and verify.

Here is a simple example:

hostname='192.168.10.110'
username='administrator'
password='adminpassword'
paramiko.util.log_to_file('syslogin.log')   #write the paramiko logging to a log file 
client=SSHClient()                          #Create a ssh client objectclient.load_system_host_keys()              #Get the host key from ./ssh/know_hosts, if the host is not in this file, use following line and comment this line out.
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())   # Automatically add the unknown host to the known_host
client.connect(hostname=hostname, username=username, password=password)
stdin, stdout, stderr=client.exec_command('free -m') #execute the command 'free -m' to show the free memory
print stdout.read()
stdout.readlines()
client.close() #terminate the ssh connection

set_missing_host_key_policy(policy) : Set policy to use when connecting to servers without a known host key.

Specifically:

A policy is a “policy class” (or instance thereof), namely some subclass of MissingHostKeyPolicy such as RejectPolicy (the default), AutoAddPolicy, WarningPolicy, or a user-created subclass.

Reference: http://docs.paramiko.org/en/2.4/api/client.html

Parameters:
  • hostname (str) – the server to connect to
  • port (int) – the server port to connect to
  • username (str) – the username to authenticate as (defaults to the current local username)
  • password (str) – Used for password authentication; is also used for private key decryption if passphrase is not given.
  • passphrase (str) – Used for decrypting private keys.
  • pkey (PKey) – an optional private key to use for authentication
  • key_filename (str) – the filename, or list of filenames, of optional private key(s) and/or certs to try for authentication
  • timeout (float) – an optional timeout (in seconds) for the TCP connect
  • allow_agent (bool) – set to False to disable connecting to the SSH agent
  • look_for_keys (bool) – set to False to disable searching for discoverable private key files in ~/.ssh/
  • compress (bool) – set to True to turn on compression
  • sock (socket) – an open socket or socket-like object (such as a Channel) to use for communication to the target host
  • gss_auth (bool) – True if you want to use GSS-API authentication
  • gss_kex (bool) – Perform GSS-API Key Exchange and user authentication
  • gss_deleg_creds (bool) – Delegate GSS-API client credentials or not
  • gss_host (str) – The targets name in the kerberos database. default: hostname
  • gss_trust_dns (bool) – Indicates whether or not the DNS is trusted to securely canonicalize the name of the host being connected to (default True).
  • banner_timeout (float) – an optional timeout (in seconds) to wait for the SSH banner to be presented.
  • auth_timeout (float) – an optional timeout (in seconds) to wait for an authentication response.
2. exec_command

Execute a command on the SSH server. A new Channel is opened and the requested command is executed. The command’s input and output streams are returned as Python file-like objects representing stdin, stdout, and stderr.

Parameters:
  • command (str) – the command to execute
  • bufsize (int) – interpreted the same way as by the built-in file() function in Python
  • timeout (int) – set command’s channel timeout. See Channel.settimeout
  • environment (dict) –a dict of shell environment variables, to be merged into the default environment that the remote command executes within.

    Warning

    Servers may silently reject some environment variables; see the warning in Channel.set_environment_variable for details.

Returns:

the stdin, stdout, and stderr of the executing command, as a 3-tuple