Python module Paramiko and SSH installation configuration tutorial

Source: Internet
Author: User
Tags sftp example

First, the installation of the Paramiko module Paramiko module relies on the Pycrypto module, and Pycrypto need to compile the GCC library, but the general distribution of the source with the module. Take CENTOS6 as an example, you can directly complete the installation directly with the following command:

The code is as follows Copy Code
# yum Install gcc python-crypto python-paramiko python-devel-y

Under Windows Edition you can install the Windows version of GCC (MinGW), then edit the installation Pycrypto and Paramiko, and after downloading Ancheng, run Python.exe setup.py build and Python.exe setup.py directly The install is ready.

Two, the Paramiko connection uses the Paramiko module to be connected the way, one is through the Paramiko. Sshclient () function, and the other is through Paramiko. The Transport () function.

Method One:

The code is as follows Copy Code
Import Paramiko ssh = 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:

The code is as follows Copy Code
Import Paramiko t = 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:

The code is as follows Copy Code
T.connect (username = "username", password = "password", hostkey= "key")

Paramiko SSH Connection The following is a simple function of SSH connection and executing command through the Paramiko module, as follows:

The code is as follows Copy Code
#!/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 '%s\tok\n '% (IP)         ssh.close ()     except:          print '%s\terror\n '% (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 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.

Four, Paramiko sftp example of a single file biography download example:

The code is as follows Copy Code
Import Paramiko #建立一个加密的管道 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 host Sftp.get ('/root/tes Tfile ', '/tmp/361way ') #Copy a local file (LocalPath) to the SFTP server as RemotePath sftp.put ('/root/crash-6.1.6.tar.gz ', '/tmp/crash-6.1.6.tar.gz ') scp.close ()

Example of uploading and downloading multiple files in one directory:

copy code
#!/usr/bin/env python #-*-coding:utf-8-*-import paramiko,datetime,os hostname= ' 192.168.0.102 ' username= ' root ' password= ' 361way ' port=22 local_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 '  & nbsp;      print ' ######################################### '          print ' Beginning to download file  from%s %s '% (Hostname,datetime.datetime.now ())  & nbsp;      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:

copy code

Import Paramiko transport = 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 implement SSH interactive connection The following is the operation code of the SSH protocol directly to the remote server via the Paramiko module, where a interactive module is defined with the following code:

The code is as follows Copy Code
Import socket Import SYS # Windows does not has Termios ... try:import termios import tty Has_termios = True     except Importerror:has_termios = False def 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:             & nbsp;           print ' \r\n*** eof\r\n ',                           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                  chan.send (x)     finally:         Termios.tcsetattr (Sys.stdin, Termios. Tcsadrain, Oldtty) # Thanks to Mike Looijmans for this Code def Windows_shell (chan):     Import Threading & nbsp;   sys.stdout.write ("Line-buffered terminal emulation. Press F6 or ^z to send eof.\r\n\r\n ")     def writeall (sock):         W Hile True:             data = Sock.recv              if not data:                  sys.stdout.write (' \r\n*** EOF ***\r\n\r\n ')                 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

The code content can be obtained from Paramiko on the GitHub project demo. Write another ssh_inter.py interactive main program, the content is as follows:

The code is as follows Copy Code
Import Paramiko Import Interactive #记录日志 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 use of the module, you can also use the Threading module block program concurrency speed, you can also use the Configparser module to process the configuration file, And we put all the IP, user information operations 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.

Python module Paramiko and SSH installation configuration tutorial

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.