Introduction to the Python Paramiko module

Source: Internet
Author: User
Tags stdin

A: Introduction

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.

All Python-supported platforms, such as Linux, Solaris, BSD, MacOS X, Windows, and so on, are supported by the use of Python, which can run across platforms, so Paramiko Paramiko is one of the best tools when you need to use SSH to connect to another platform from one platform and perform a series of operations.

As a common example, there is a need to use a Windows client to connect remotely to a Linux server and view the log status above, as you would normally use:

1: Use Telnet

2: With Putty

3: With WINSCP

4: With Xmanager etc...

Now, if the demand adds another one, what do I do to download files from the server? The usual approach might be:

Install FTP on 1:linux and configure

Install Sambe on 2:linux and configure ...

You will find that the common solution will need to the remote server necessary configuration, if the remote server only one or two is good to say, if there are n units, also need to be configured by the station, or need to use code to do above, the above method is not very convenient.

The use of Paramiko can solve the above problem well, compared to the previous method, it only need to install the appropriate software (Python and Pycrypto) on-premises, there is no configuration requirements for the remote server, for connecting multiple servers, complex connection operation is particularly helpful.

Two: Installation

There are two prerequisites for installing Paramiko, Python and another module named Pycrypto.

or pip install Paramiko

Three: Using Paramiko

#设置ssh连接的远程主机地址和端口
T=paramiko. Transport ((Ip,port))
#设置登录名和密码
T.connect (Username=username,password=password)
#连接成功后打开一个channel
Chan=t.open_session ()
#设置会话超时时间
Chan.settimeout (Session_timeout)
#打开远程的terminal
Chan.get_pty ()
#激活terminal
Chan.invoke_shell ()
You can then execute commands remotely with chan.send (' command ') and CHAN.RECV (Recv_buffer) and get feedback locally.

Paramiko has two modules sshclient () and Sftpclient ()

Using Sshclient ()

1 #Coding:utf-82 ImportParamiko3 4 #To create an SSH object5SSH =Paramiko. Sshclient ()6 #allow connections to hosts that are not in the Know_hosts file7 Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())8 #connecting to a server9Ssh.connect (hostname='192.168.2.103', Port=22, Username='Root', password='123456')Ten  One #Execute Command Astdin, stdout, stderr = Ssh.exec_command ('ls') - #Get command Results -result =Stdout.read () the Print(Str (result,encoding='Utf-8')) - #Close Connection -Ssh.close ()
View Code

Sshclient () has a transport variable, which is used to get the connection, so we can also get to the transport variable separately and then perform the join operation

1 #Coding:utf-82 ImportParamiko3 4Transport = Paramiko. Transport (('192.168.2.103', 22))5Transport.connect (username='Root', password='123456')6 7SSH =Paramiko. Sshclient ()8Ssh._transport =Transport9 Tenstdin, stdout, stderr = Ssh.exec_command ('DF') One Print(Str (Stdout.read (), encoding='Utf-8')) A  -Transport.close ()
View Code

Upload download and command execution with transport:

1 #Coding:utf-82 ImportParamiko3 ImportUUID4 5 classsshconnection (object):6 7     def __init__(Self, host='192.168.2.103', Port=22, Username='Root', pwd='123456'):8Self.host =Host9Self.port =PortTenSelf.username =username OneSelf.pwd =pwd ASelf.__k=None -  -     defConnect (self): theTransport =Paramiko. Transport ((self.host,self.port)) -Transport.connect (username=self.username,password=self.pwd) -Self.__transport=Transport -  +     defClose (self): -Self.__transport. Close () +  A     defUpload (self,local_path,target_path): at         #Connect, upload -         #file_name = Self.create_file () -SFTP = Paramiko. Sftpclient.from_transport (self.__transport) -         #uploading location.py to the server/tmp/test.py - sftp.put (Local_path, Target_path) -  in     defDownload (self,remote_path,local_path): -SFTP = Paramiko. Sftpclient.from_transport (self.__transport) to sftp.get (Remote_path,local_path) +  -     defcmd (self, command): theSSH =Paramiko. Sshclient () *Ssh._transport = self.__transport $         #Execute CommandPanax Notoginsengstdin, stdout, stderr =ssh.exec_command (command) -         #Get command Results theresult =Stdout.read () +         Print(Str (result,encoding='Utf-8')) A         returnresult the  +SSH =sshconnection () - Ssh.connect () $Ssh.cmd ("ls") $Ssh.upload ('s1.py','/tmp/ks77.py') -Ssh.download ('/tmp/test.py','KKKK',) -Ssh.cmd ("DF") theSsh.close ()
View Code

Four, connect with Linux

Here are two codes for connecting to a Linux server using Paramiko

Way One:

1 ssh = Paramiko. Sshclient ()2ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())3 ssh.connect (" a certain IP address ", " the user name " " Password ")

Way two:

1 t = Paramiko. Transport ("host", "Port")2 t.connect (username = "username", password = "password")

Sftpclient () is also implemented using transport, so if there is a need to execute commands and upload files together, then you need to use the transport approach.

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")

3.1 Windows runs arbitrary commands on Linux and outputs the results

If the Linux server has 22 ports open, on the Windows side, we can use Paramiko to connect to the server remotely, execute arbitrary commands, and then print or otherwise get the result.

The code is as follows

1 #Coding:utf82 3 ImportParamiko4  5SSH =Paramiko. Sshclient ()6 Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())7Ssh.connect ("an IP address", 22,"User name","Password")8stdin, stdout, stderr = Ssh.exec_command ("your orders.")9 PrintStdout.readlines ()TenSsh.close ()
View Code

One of the "your commands" can be any Linux-supported command

3.2 Downloading files from the Linux server on the widnows side

1 Coding:utf82 3 ImportParamiko4  5t =Paramiko. Transport (("Host", "Port")6T.connect (username = "username", Password ="password")7SFTP =Paramiko. Sftpclient.from_transport (t)8Remotepath= '/var/log/System.log '9Localpath= '/tmp/System.log 'Ten Sftp.get (RemotePath, LocalPath) OneT.close ()
View Code

3.3 Uploading files to a Linux server from the widnows side

1 Import Paramiko 2 3 t = Paramiko. Transport (("Host", "Port"))4 t.connect (username = "username", password = "password")5 sftp =  Paramiko. Sftpclient.from_transport (t)6 remotepath= '/var/log/system.log '7 localpath= '/tmp/system.log '8sftp.put (localpath,remotepath)9 t.close ()
View Code

3.4 Installing the Paramiko module on Linux

Install scrapy problems encountered in this application
C/_cffi_backend.c:2:20:fatal error:python.h:no such file or directory
sudo apt-get install Python-dev
C/_cffi_backend.c:13:17:fatal error:ffi.h:no such file or directory
1 sudo apt-get install Libffi-dev
* Make sure the development packages of LIBXML2 and LIBXSLT is installed *
1 sudo apt-get install Libxslt1-dev

1. Download and install wget http://peak.telecommunity.com/dist/ez_setup.py

2.python ez_setup.py

3.easy_install Paramiko

Introduction to the Python Paramiko module

Related Article

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.