Python module Paramiko and SSH

Source: Internet
Author: User

Paramiko is a module written in the Python language that follows the SSH2 protocol and supports the connection of remote servers in a way that is encrypted and authenticated. Paramiko supports Linux, Solaris, BSD, MacOS X, Windows and other platforms to connect to another platform via SSH from one platform. With this module, it is convenient to make an SSH connection and SFTP protocol for SFTP file transfer.


First, installation

The Paramiko module relies on the Pycrypto module, and Pycrypto requires the GCC library to compile, although the module is in the source of the general release. CENTOS6, you can directly complete the installation directly with the following command:

    1. # yum Install gcc python-crypto python-paramiko python-devel-y


Windows, you can download the binary package

PYCRYPTO:HTTP://WWW.VOIDSPACE.ORG.UK/PYTHON/PYCRYPTO-2.6.1/Next Step installation can be

paramiko:https://pypi.python.org/pypi/paramiko/1.7.4 unzip, then go to unzip directory, execute under DOS

Python setup.py buildpython setup.py Install

Or

Pip Install Paramiko

Second, the connection of Paramiko

There are two ways to connect using the Paramiko module, one through the Paramiko. Sshclient () function, and the other is through Paramiko. The Transport () function.

Method One:

Import paramikossh = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect ("One IP Address", 22, "username", "password")

The second line of code above is to allow connections to hosts that are not in the Know_hosts file.

Method Two:

Import Paramikot = Paramiko. Transport (("Host", "Port") t.connect (username = "username", password = "password")

If a key is required to connect to the remote host, the second line of code above can be changed to:

T.connect (username = "username", password = "password", hostkey= "key")

Third, Paramiko SSH connection

The following is a simple function of the SSH connection that is defined by the Paramiko module and executes the command, as follows:


#!/usr/bin/python#-*- coding: utf-8 -*-import paramiko#paramiko.util.log_to_file ('/tmp/ Sshout ') def ssh2 (ip,username,passwd,cmd):    try:         ssh = paramiko. Sshclient ()         ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())         ssh.connect (ip,22,username,passwd,timeout=5)         stdin,stdout,stderr = ssh.exec_command (CMD) #            stdin.write ("Y")     #简单交互, enter   ' Y '         print stdout.read () #         for x in  stdout.readlines ():#           print x.strip ("n")         print  '%stokN '% (IP)         ssh.close ()     except :         print  '%sterrorn '% (IP) ssh2 ("192.168.0.102", "root", "361way", " Hostname;ifconfig ") ssh2 (" 192.168.0.107 "," root "," 123456 "," Ifconfig ")

The fourth line of the log section, is to record the SSH connection interaction when some information, can be seen as similar to debug output, generally do not need to open.


The Stdin.write section is used in an interactive situation where the interaction can be performed by this command. Note that this may cause ambiguity, and the interaction here is not an interaction with the input yes that occurs during the SSH connection, because the Paramiko module automatically handles the Yes acknowledgement during the connection process. The interaction here means that the following CMD requires the execution of a program that can interact with this parameter in case of interaction.


StdOut standard output, when the output content is relatively young, you can read out all the output by using read directly, but when the output content is relatively long, it is recommended to be processed by read by the line. However, when reading by rows, there is a newline character n at the end of each line, which results in a very ugly output. The processing of strings can be done through strip.


In the process of function calls, it is important to note that IP, username, passwd are all string types, so quotation marks are required. After executing the cmd, if you have more than one command to operate, you need to split by semicolons.


Iv. Examples of Paramiko sftp

An example of a single file biography download:

import paramiko# establish an encrypted pipeline Scp=paramiko. Transport ((' 192.168.0.102 ')) #建立连接scp. Connect (username= ' root ', password= ' 361way ') #建立一个sftp客户端对象, via ssh  Transport operation remote file Sftp=paramiko. Sftpclient.from_transport (SCP) #Copy  a remote file  (RemotePath)  from the  Sftp server to the local hostsftp.get ('/root/testfile ', '/tmp/361way ') #Copy  a  local file  (LocalPath)  to the sftp server as remotepathsftp.put ( '/root/crash-6.1.6.tar.gz ', '/tmp/crash-6.1.6.tar.gz ') scp.close () 

#!/usr/bin/env python#-*- coding: utf-8 -*-import paramiko,datetime,oshostname= ' 192.168.0.102 ' username= ' root ' password= ' 361way ' port=22local_dir= '/tmp/getfile ' remote_dir= '/tmp/abc ' try:     t=paramiko. Transport ((Hostname,port))     t.connect (Username=username,password=password)      sftp=paramiko. Sftpclient.from_transport (t)      #files =sftp.listdir (dir_path)     files =sftp.listdir (Remote_dir)     for f in files:         print  '         print  ' ################### ###################### '         print  ' beginning to  download file  from %s  %s  '  %  (Hostname,datetime.datetime.now ())         print  ' Downloading fiLe: ', Os.path.join (remote_dir,f)         sftp.get (Os.path.join (remote_ DIR,F), Os.path.join (local_dir,f)) #下载          #sftp. Put (Os.path.join ( LOCAL_DIR,F), Os.path.join (remote_dir,f)) #上传         print  ' download file success %s  '  % datetime.datetime.now ()          print  '         print  ' ############# ############################# '     t.close () except exception:        print  "connect error!"

Note: In this section of the directory of all the files to download or upload the example, in the encounter directory and nested directory exists, the directory is also treated as a file, so if you want to be more perfect, you can introduce the Stat module under the S_isdir method for processing

The Paramiko.transport object also supports connecting as a socket, as in the following example:

Import Paramikotransport = Paramiko. Transport (' localhost ', ()) Transport.connect (username= ' root ', password = ' password ') sftp = Paramiko. Sftpclient.from_transport (transport) Sftp.get (remotefile,localfile) #如果是上传则用: #sftp. Put (LocalFile, remotefile) Transport.close () #用socket连接tcpsock = Socket.socket (socket.af_inet,socket. SOCK_STREAM) Tcpsock.settimeout (5) Tcpsock.connect ((ip,22),) ssh = Paramiko. Transport (Tcpsock) ssh.connect (Username=user,password=password) Sftpconnect=paramiko. Sftpclient.from_transport (SSH)

V. Using Paramiko to realize the interactive connection of SSH

The following is an operation code that logs directly to the remote server with the SSH protocol via the Paramiko module, where a interactive module is defined with the following code:

import socketimport sys# windows does not have termios...try:     import termios    import tty    has_termios  = Trueexcept ImportError:    has_termios = Falsedef  Interactive_shell (Chan):    if has_termios:         posix_shell (Chan)     else:        windows_ Shell (Chan) Def posix_shell (chan):     import select    oldtty  = termios.tcgetattr (Sys.stdin)     try:         tty.setraw (Sys.stdin.fileno ())         tty.setcbreak ( Sys.stdin.fileno ())         chan.settimeout (0.0)          while true:            r, w, e =  Select.select ([chan, sys.stdin], [], [])              if chan in r:                 try:                     X = CHAN.RECV (1024x768)                      if len (x)  == 0:                         print  ' RN*** EOFRN ',                          break                     Sys.stdout.write (x)                      sys.stdout.flush ()                  except socket.timeout:                     pass             if sys.stdin in r:                 x = sys.stdin.read (1)                  if len (x)   == 0:                     break &nbsP;              chan.send (x)      finally:        termios.tcsetattr (Sys.stdin, termios. Tcsadrain, oldtty) # thanks to mike looijmans for this codedef  Windows_shell (chan):     import threading    sys.stdout.write (" Line-buffered terminal emulation. press f6 or ^z to send eof.rnrn ")     def writeall (sock):        while  TRUE:            DATA = SOCK.RECV (256)             if not data:                 sys.stdout.write (' rn***  eof ***rnrn ') &nBsp;               sys.stdout.flush ()                 break             sys.stdout.write (data)              sys.stdout.flush ()     writer =  threading. Thread (Target=writeall, args= (Chan,))     writer.start ()     try:         while True:             d = sys.stdin.read (1)              if not d:                 break             Chan.send (d)     except eoferror:        # user  hit ^z or f6        pass

style= font-family: Arial, Helvetica, sans-serif;font-size:16px; >paramiko on the GitHub project is the demo get. Write another ssh_inter.py interactive main program, with the following contents:

Import paramikoimport interactive# log paramiko.util.log_to_file ('/tmp/test ') #建立ssh连接ssh =paramiko. Sshclient () Ssh.load_system_host_keys () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) ssh.connect (' 192.168.0.102 ', port=22,username= ' root ', password= ' xxxxxx ', compress=true) # Establish an interactive shell connection Channel=ssh.invoke_shell () #建立交互式管道interactive. Interactive_shell (channel) #关闭连接channel. Close () Ssh.close ()

It works just like we normally do with SSH.


Vi. Summary

Paramiko module is a more powerful SSH connection module, the above example just lists some simple ways to use the module, you can also use the Threading module block program concurrency, you can also use the Configparser module to process the configuration file, and we will all IP , user information operations are put into the configuration file, using the Setproctitle module for the execution of the program to add an easy to distinguish the title and so on.


Similarly, although the use of SSH in the famous software such as fabric is encapsulated with the Paramiko module, you can still choose not to use it, you can also choose the Pexpect module to encapsulate a simple SSH connection tool, Or use a SALT-SSH module with the same fire.


This article is from the "Baby God" blog, make sure to keep this source http://babyshen.blog.51cto.com/8405584/1887832

Python module Paramiko and SSH

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.