"Python module" Paramiko module and host SSH connection

Source: Internet
Author: User

Remember the socket and socketserver you did in the previous section? Wrote a lot to achieve a small function, but today's paramiko really let people have a kind of earth gun to change the feeling of cannon!

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.


This article only demonstrates the Paramiko connection to the Linux operating system.

-----------------------------------------------------

There's a total of Paramiko in the bag. Connection method (two classes): Sshclient and transport, each connection method supports password Authentication and certificate authentication .

Paramiko also has some other methods and properties. This article only describes the simple, common.

Paramiko is not a Python basic module, it needs to be based on the Pycrypto module, so you need to install Pycrypto, and then install Paramiko

PIP3 Install Pycrypto # Windows is likely to get an error due to the need to install C + + and set variables. PIP3 Install Paramiko # actually installs the Paramiko directly, automatically installs the dependent package. The PIP version I used was Pip 9.0.3# successful when prompted to install the following packages: Pycparser, Cffi, Pynacl, Bcrypt, PYASN1, Asn1crypto, cryptography, Paramiko


Sshclient: Used to execute commands remotely.

Method/Property Name
Parameters:
Description
connect ()

Implementing SSH encrypted connection

Hostname
port 
username 
password 
pkey 
timeout 
allow_agent 
Look_for _keys 
compress   

Parameter type: function

Str: Host ip       # must parameter

Int: Port          # must parameter

Str: User name      # username and Pkey key connection must exist with a

str: password

Pkey: Key

float: timeout       # optional

Boool: When flase, disable connect to SSH proxy       # optional When

Bool:flase is disabled, turn on compression when searching for key files       # optional

Bool:true in ~/.ssh.       # Optional


Exec_command ()

Remote Execute command, Popen remote version ...

"Command"

BufSize


Parameter type: function

STR: Commands that are executed remotely and need to be split by semicolons if more than one command needs to be manipulated

int: Buffer size, Default-1, Unlimited

Load_system_host_keys ()

Load local public key checksum file, default is ~/.ssh/known_hosts

FileName

Parameter type: function

STR: remote host public key record file, Linux system default path ~/.ssh/known_hosts

Set_missing_host_key_policy ()

The connection host does not have the local host secret key or the Hostkeys object when the policy, currently supports three kinds: autoaddpolicy,rejectpolicy,warningpolicy


Autoaddpolicy: Automatically add host name and master key

Rejectpolicy (default): Automatic rejection of unknown hostname and secret key

Warningpolicy: Python warning for recording an unknown host key



Example:

SSH = Paramiko. Sshclient ()

Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())

Ssh.connect (...) in the .......)


Stdin.wirte (str) Str Enter the character of the STR type to confirm the continuation. Should be similar to pause in bat

Example one: Sshclient connection with user name and password

Import paramikoparamiko.util.log_to_file ('/tmp/ssh_log ')  #  record connection information #  Connect remote def  using username password Myssh ():     cmd = input ("command to execute->>:"). Strip ()      Return cmd    ssh = paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())     #  before connect, set the parameters, automatically add the host to the Linux  host_knows file Ssh.connect ( hostname =  ' 192.168.1.100 ', port = 9999, username =  ' David ', password  =  ' wonianqing ') #也可以传形参: Ssh.connect (' 192.168.1.100 ', 9999,  ' David ', ' wonianqing ') cmd =  myssh () stdin,stdout,stderr = ssh.exec_command (cmd) if stdout.read ():     print  (Stdout.read ())             #  stdout and stderr can only have one with data, stdout normal return, stderr return error. else:    print  (Stderr.read ()) Ssh.close ()

Example two: Use certificate authentication for sshclient connections.

Import paramikossh = Paramiko. Sshclient () ssh.connect ("localhost", 9999,pkey= "") # need to create a key under Linux, Pkey is the private key address on the client, the server address default


Second, sftpclient: used to upload files to download the remote host

Method/Property Name
Role
Parameters
Example
Transport (host name, port number)
Establishing a remote host plus password pipeline object

Host Name: IP or hostname, str type

Port number: Specify ports, type int

SF = Paramiko. Transport (("192.168.1.1", 22))
Connect (Username,password)
Establish a remote connection

Username: User Name

Password: password

Sf.connect (username = "root", password= "Areyouok1")
Sftpclient.from_transport (encrypted pipeline)
Set up a client object to operate the remote file via SSH transport
Encrypted pipelines: SF objects previously created
SFTP = Paramiko. Sftpclient.from_transport (SF)
Get (remote file, local file) Download the specified file from remote to local

Remote file name

Local file name


Sftp.get (Remotepath,localpath)
Put (local file, remote file) Upload a specified file to a remote path from local

Local file name

Remote file name

Sftp.put (Localpath,remotepath)
Listdir (remote path) List folders for a remote specified path Remote path name Sftp.listdir ("..")


Import Paramiko "" "Sftpclient" "" Sftp_transport_obj = Paramiko. Transport (("192.168.1.106")) Sftp_transport_obj.connect (username= "root", password= "a2266351z") sftp = Paramiko. Sftpclient.from_transport (sftp_transport_obj) # sftp.get () # sftp.put () Ss=sftp.listdir ("...") Print (ss) print (Ss.read ()) ' Paramiko can also use the socket object to connect ' ' Import socket,paramikoaddr = ' 192.168.1.106 ' port = 22socket_ obj = Socket.socket () socket_obj.connect ((addr,port)) Sftp_transport_obj = Paramiko. Transport (socket_obj) sftp_obj = Paramiko. Sftpclient.from_transport (sftp_transport_obj) Cmd_result = Sftp_obj.listdir (' ... ') Print (Cmd_result) sftp_transport_obj.close ()





Resources:

http://python.jobbole.com/87088/

"Python module" Paramiko module and host SSH connection

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.