The main part of this paper is the example of the use of the Python Paramiko module, which is as follows. There are a lot of very good SSH clients, such as Putty, under

Windows. In the world of python, you can use original socket and some encryption functions to create your own SSH client or server side, but if you have ready modules, why do you need to implement them yourself? Using the PyCrypto in the Paramiko library allows you to easily use the SSH2 protocol. There are many such posts on the web installation method of

Paramiko, which is not described here. This is mainly about how to use it. The implementation of SSH2 by Paramiko is no more than two aspects: the SSH client and the server.

let us first clarify the following terms:

  • SSHClient: Channel, Transport, SFTPClient
  • packaging:

  • Channel is a Socket, a secure SSH channel;
  • :

  • Transport is an encrypted session (but such an object Session has not been established), and creating an encrypted tunnels, the tunnels
  • Session called Channel; client and Server are: keeping the connection object, using connect (/start_client) (/start_server) (start session).

please refer to the specific Paramiko library document:

, here are a few common use case:

SSH client implementation scheme, this scheme

execute remote commands directly using the SSHClient object (exec_command) command is executed on the server, the following are the specific code:

 # instantiation SSHClient client = paramiko.SSHClient (client.set_missing_host_key_policy) # automatically add strategy, save the server host name and key information (paramiko.AutoAddPolicy) (SSH) # connection server, username and password to authenticate client.connect (IP, username=user, password=passwd) # open a Channel and execute the command of stdin, stdout, stderr = client.exe C_command (command) print stdout.readlines (# print results) SSHClient client.close (

) # closed

SSH client implementation scheme of two

, remote command execution of this programme is to be the SSHClient connection object is a Transport object, the Transport object (exec_command) command is executed on the server, the following are the specific code:

 client = paramiko.SSHClient (SSHClient # instantiation) # automatically add client.set_missing_host_key_policy strategy, save the server host name and key information (paramiko.AutoAddPolicy) (SSH) # connection server, username and password to authenticate client.connect (IP, username=user, password=passwd) # instantiate Transport, and establish a session Session ssh_session = client.get_transport (.Open_session) (if) Ssh_session.exec_command (command) print ssh_session.recv (1024) client.close () 

SSH service terminal implementation

implementation SSH server must inherit ServerInterface and implement corresponding methods. The specific code is as follows:

 import socket import sys import threading import paramiko host_key = paramiko.RSAKey (filename='private_key.key') class Server (paramiko.ServerInterface): def __init__ (self): (start_server) # execution method first will trigger Event, if return to success, is_active returns self.event = threading.Event (True) # when is_active returns True into def check_auth_password certification (self, username, password): if (username = ='root') and (password = ='123456'): return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED # when authentication is successful, client will request to open a Channel def check_channel_request (self, kind, chanid): if kind = ='session': return paramiko.OPEN_SUCCEEDED # command line Port server = sys.argv[1] and receiving IP ssh_port = int (sys.argv[2]) socket try: sock # = socket.socket (socket.AF_INET, socket.SOCK_STREAM) #TCP socket sock.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, sock.bind (1) (server, ssh_port)) sock.listen (100) print'[+] Listening for connection... 'client, addr = sock.accept (except) Exception. E: print Listen failed:'[-]' + str (E) sys.exit (1) print Got a connection try:'[+]! '# sock.accept (socket) return to instantiate Transport bhSession = paramiko.Transport (client) # add a RSA key encryption session bhSession.add_server_key (host_key) server = Server (try:) bhSession.start_server (# start SSH server except paramiko.SSHException, X server=server) SSH negotiation failed'Chan'[-]: print = bhSession.accept (20) print Authenticated print chan.recv'[+]!' (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'exiting' bhSession.close (raise) Exception ('exit') except KeyboardInterrupt: bhSession.close (except) Exception, e: print Caught exception:'[-]' + str (E) try: bhSession.close (except:) pass sys.exit (1) 

 import using SFTP upload files to paramiko # tran = paramiko.Transport (Transport for example (" host_ IP ", 22)) SSH (username # connection server tran.connect =" username ", password =" password ") # get SFTP examples of SFTP = paramiko.SFTPClient.from_transport (tran) # set upload local / remote file path localpath=" /root/Desktop/python/ "remotepath=" /tmp/ "sftp.put # perform the upload (localpath, remotepath (tran.close) 

) SFTP download files using

 import paramiko SSHClient client paramiko.SSHClient # for example = (client.set_missing_host_key_policy) (paramiko.AutoAddPolicy) (SSH) # connection server client.connect (" host_ip "," username= "username, password=" password ") # tran = client.get_transport (Transport for example) # get SFTP examples of SFTP = paramiko.SFTPClient.from_transport (tran remotepath='/tmp/'localpa) Th='/root/Desktop/'sftp.get (remotepath, localpath) client.close (

the above is summarized this article on the Python Paramiko module using the actual case, we hope to help. Interested friends can continue to refer to other relevant topics of the station, if there are shortcomings, welcome the message. Thank you for the support of our friends!

This paper fixed link: | Script Home | +Copy Link

Article reprint please specify:The actual use of the Python Paramiko module | Script Home

You may also be interested in these articles!