Python Paramiko module use case, pythonparamiko

Source: Internet
Author: User
Tags ssh server

Python Paramiko module use case, pythonparamiko

This article mainly describes the examples used by the Python Paramiko module. The details are as follows.

There are many very good SSH clients in Windows, such as Putty. In the world of python, you can use the original socket and some encryption functions to create your own SSH client or server. But if there is a ready-made module, why do you need to implement it yourself. Using PyCrypto in the Paramiko library allows you to easily use the SSH2 protocol.

Paramiko's installation method has many such posts on the Internet, which will not be described here. This article mainly describes how to use it. Paramiko implements SSH2 from two aspects: the SSH client and the server.

First, let's clarify the following terms:

  • SSHClient: Channel, Transport, SFTPClient
  • Channel: it is a Socket type and a Secure SSH transmission Channel;
  • Transport: an encrypted Session (but the Session of such an object is not created), and an encrypted tunnels is created. This tunnels is called a Channel;
  • Session: the object that the client and Server keep connected to. Use connect ()/start_client ()/start_server () to start the Session.

For more information, see Paramiko library documentation: http://docs.paramiko.org/en/2.0/index.html

Below are several common use cases:

SSH client implementation solution 1: execute remote commands

In this solution, exec_command () of the SSHClient object is directly used to execute commands on the server. The following is the specific code:

# Instantiate SSHClient client = paramiko. SSHClient () # automatically add a policy to save the Host Name and key information of the server client. set_missing_host_key_policy (paramiko. autoAddPolicy () # connect to the SSH server and authenticate the client with the user name and password. connect (ip, username = user, password = passwd) # Open a Channel and run stdin, stdout, stderr = client.exe c_command (command) # print the execution result print stdout. readlines () # Close SSHClient client. close ()
SSH client implementation solution 2: execute remote commands

This scheme is to get a Transport object from the object that the SSHClient establishes a connection, and exec_command () of the Transport object executes the command on the server. The specific code is as follows:

# Instantiate SSHClientclient = paramiko. SSHClient () # automatically add a policy to save the Host Name and key information of the server client. set_missing_host_key_policy (paramiko. autoAddPolicy () # connect to the SSH server and authenticate the client with the user name and password. connect (ip, username = user, password = passwd) # instantiate Transport and establish session Sessionssh_session = client. get_transport (). open_session () if ssh_session.active: ssh_session.exec_command (command) print ssh_session.recv (1024) client. close ()
Implementation of the SSH server

The implementation of the SSH server must inherit the ServerInterface and implement the corresponding methods. The Code is as follows:

Import socketimport sysimport threadingimport paramikohost_key = paramiko. RSAKey (filename = 'private _ key. key') class Server (paramiko. serverInterface): def _ init _ (self): # executing the start_server () method triggers the Event first. If the returned result is successful, is_active returns True self. event = threading. event () # When is_active returns True, it enters the authentication stage def check_auth_password (self, username, password): if (username = 'root ') and (password = '000000'): return paramiko. AUTH _ SUCCESSFUL return paramiko. AUTH_FAILED # When the authentication succeeds, the client will request to open a Channel def check_channel_request (self, kind, chanid): if kind = 'session': return paramiko. OPEN_SUCCEEDED # command line receiving ip address and portserver = sys. argv [1] ssh_port = int (sys. argv [2]) # create sockettry: sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM) # TCP socket sock. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1) sock. bind (server, ssh_port) s Ock. listen (100) print '[+] Listening for connection... 'client, addr = sock. accept () failed t Exception, e: print '[-] Listen failed:' + str (e) sys. exit (1) print '[+] Got a connection! 'Try: # use sock. the socket returned by accept () is instantiated Transport bhSession = paramiko. transport (client) # Add an RSA key to encrypt the bhSession. add_server_key (host_key) server = Server () try: # Start the SSH server bhSession. start_server (server = server) parameter t paramiko. SSHException, x: print '[-] SSH negotiation failed' chan = bhSession. accept (20) print '[+] Authenticated! 'Print chan. recv (1, 1024) chan. send ("Welcome to my ssh") while True: try: command = raw_input ("Enter command :"). strip ("\ n") if command! = 'Exit ': chan. send (command) print chan. recv (1024) + '\ n' else: chan. send ('exit ') print 'existing' bhSession. close () raise Exception ('exit ') failed t KeyboardInterrupt: bhSession. close () failed t Exception, e: print '[-] Caught exception:' + str (e) try: bhSession. close () failed T: pass sys. exit (1)
Use SFTP to upload files
Import paramiko # Get Transport instance tran = paramiko. transport ("host_ip", 22) # connect to the SSH server tran. connect (username = "username", password = "password") # obtain the SFTP instance sftp = paramiko. SFTPClient. from_transport (tran) # Set the local/remote file path to be uploaded localpath = "/root/Desktop/python/NewNC. py "remotepath ="/tmp/NewNC. py "# execute the upload action sftp. put (localpath, remotepath) tran. close ()
Use SFTP to download files
Import paramiko # obtain the SSHClient instance client = paramiko. SSHClient () client. set_missing_host_key_policy (paramiko. autoAddPolicy () # connect to the client of the SSH server. connect ("host_ip", username = "username", password = "password") # obtain Transport instance tran = client. get_transport () # obtain SFTP instance sftp = paramiko. SFTPClient. from_transport (tran) remotepath = '/tmp/NewNC. py 'localpath = '/root/Desktop/NewNC. py 'sftp. get (remotepath, localpath) client. close ()
Summary

The above is all about the use cases of the Python Paramiko module. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.