Python Module Learning-Paramiko

Source: Internet
Author: User
Tags create directory stdin ssh server

Brief introduction

SSH is a protocol, OpenSSH is one of the open source implementations, Paramiko is a library of Python, implements the SSHV2 protocol (the underlying uses cryptography).

With Paramiko, we can use the SSH protocol to perform operations on remote servers directly in Python code, rather than using SSH commands to operate on remote servers.

Because Paramiko belongs to a third-party library, you need to install it using the following command

PIP3 Install Paramiko

  

Paramiko Introduction

The Paramiko consists of two core components: Sshclient and Sftpclient.

    • The Sshclient function is similar to the SSH command for Linux, which encapsulates the SSH session, which encapsulates the method (Transport), channel, and Sftpclient (OPEN_SFTP), which is typically used to execute remote commands.
    • Sftpclient functions like the SFTP command for Linux, which is the encapsulation of the SFTP client to enable remote file operations such as file uploads, downloads, and file permissions.
# Paramiko Several basic nouns: 1, channel: is a kind of socket, a secure SSH transmission channel, 2, Transport: is an encrypted session, the use will be synchronized with the creation of an encrypted tunnels (channel), This tunnels is called channel;3, session: The object that the client keeps connected to the server, starting the session with Connect ()/start_client ()/start_server ().

  

The basic use of Paramiko sshclient commonly used methods introduced

Connect (): To realize the connection and authentication of the remote server, only hostname is required for the method.

Common parameters hostname Connection target host Port=ssh_port Specify port username=none authenticated user name Password=none authenticated user password Pkey=none private key method for authentication Key_filename= None a file name or list of files, specifying the private key file Timeout=none Optional TCP connection Timeout allow_agent=true, whether to allow connections to the SSH proxy, and by default true to allow look_for_keys=true whether ~/. SSH search for private key file, default to True allows Compress=false, whether to turn on compression

  

Set_missing_host_key_policy (): Sets the response policy when the remote server does not record in the Know_hosts file. Currently supports three strategies:

There are currently three kinds of policies when setting up a connected remote host that does not have a local host key or Hostkeys object: Autoaddpolicy automatically adds the hostname and host key to the local Hostkeys object without relying on Load_system_host_key configuration. That is, you do not need to enter Yes or no to confirm the new SSH connection warningpolicy the python warning used to record an unknown host key. and accept, functionally and autoaddpolicy similar, but will prompt is new connection rejectpolicy automatically rejects unknown hostname and key, depend on Load_system_host_key configuration. This is the default option

Exec_command (): The method of executing the Linux command on the remote server.

open_sftp (): Creates an SFTP session on the basis of the current SSH session. The method returns a Sftpclient object.

# using the Open_sftp () method of the Sshclient object, you can directly return an Sftp object based on the current connection, which can be used for uploading files and so on. SFTP = Client.open_sftp () sftp.put (' Test.txt ', ' Text.txt ')

  

Examples of commonly used methods of sshclient
Import Paramiko    # instantiates sshclient    client = Paramiko. Sshclient ()    # automatically adds the policy, saves the server's hostname and key information, and if not added, the host that is no longer logged in the local know_hosts file will not be able to connect    Client.set_missing_host_key_ Policy (Paramiko. Autoaddpolicy ())    # Connect to SSH server, authenticate with username and password    client.connect (hostname= ' 192.168.1.105 ', port=22, username= ' root ' , password= ' 123456 ')    # Open a channel and execute command    stdin, stdout, stderr = Client.exec_command (' df-h ')  # stdout for correct output , stderr is the error output, and there are 1 variables with value    # print execution result print    (Stdout.read (). Decode (' Utf-8 '))    # close Sshclient    Client.close ()

Key connection mode

# Configure private key file location private = Paramiko. Rsakey.from_private_key_file ('/users/ch/.ssh/id_rsa ') #实例化SSHClientclient = Paramiko. Sshclient () #自动添加策略, the host name and key information of the server is saved, and if not added, hosts that are not logged in the local know_hosts file will not be able to connect Client.set_missing_host_key_policy ( Paramiko. Autoaddpolicy ()) #连接SSH服务端, authenticate with username and password client.connect (hostname= ' 10.0.0.1 ', port=22,username= ' root ', pkey=private)

Sshclient Package Transport

Import Paramiko    # Create a channel    transport = Paramiko. Transport ((' hostname '))    Transport.connect (username= ' root ', password= ' 123 ')    ssh = Paramiko. Sshclient ()    Ssh._transport = Transport    stdin, stdout, stderr = Ssh.exec_command (' df-h ')    print ( Stdout.read (). Decode (' Utf-8 '))    Transport.close ()

  

 

Introduction to common methods of sftpclient
Sftpclient is an SFTP client object that implements remote file operations, such as upload, download, permissions, status From_transport (Cls,t), based on an sftp session of the SSH transport protocol, to create a connected SFTP client channel put ( LocalPath, RemotePath, Callback=none, confirm=true) uploads the local file to the server parameter confirm: whether the stat () method is called to check the file status, returns the result of the ls-l get ( RemotePath, LocalPath, callback=none) download files from the server to local mkdir () Create directory on the server remove () Delete directory on server () Rename directory stat on server () View Server file Status Listdir () lists the files under the server directory
Examples of common methods of sftpclient
    Import Paramiko    # gets Transport instance    Tran = Paramiko. Transport (' 10.0.0.3 ',)    # Connect to SSH server, use password    tran.connect (username= "root", password= ' 123456 ')    # Or, use    # to configure the private key file location for privately    -Paramiko. Rsakey.from_private_key_file ('/users/root/.ssh/id_rsa ')    # connects to the SSH server, using Pkey to specify the private key    Tran.connect (username= " Root ", pkey=private)    # Gets an sftp instance of    sftp = Paramiko. Sftpclient.from_transport (Tran)    # Set the local/remote file path of the upload    localpath = "/users/root/downloads/1.txt"    RemotePath = "/tmp/1.txt"    # Perform upload action    sftp.put (LocalPath, RemotePath)    # Perform download action    sftp.get (RemotePath , LocalPath)    tran.close ()

  

 

Paramiko Examples of integrated use
Class Sshconnection (object): Def __init__ (self, host_dict): Self.host = host_dict[' host '] Self.port = hos t_dict[' Port '] self.username = host_dict[' username '] self.pwd = host_dict[' pwd '] self.__k = None D EF Connect (self): transport = Paramiko. Transport ((Self.host,self.port)) Transport.connect (USERNAME=SELF.USERNAME,PASSWORD=SELF.PWD) Self.__transpor T = Transport def close (self): Self.__transport.close () def run_cmd (self, Command): "" "Execution Shel        The l command returns the dictionary return {' Color ': ' Red ', ' res ': Error} or return {' Color ': ' Green ', ' res ': res}:p Aram Command: : Return: "" "SSH = Paramiko. Sshclient () Ssh._transport = self.__transport # Execute command stdin, stdout, stderr = ssh.exec_command (command # get Command Result res = UNICODE_UTILS.TO_STR (Stdout.read ()) # get error message = UNICODE_UTILS.TO_STR (std Err.read () # If there is an error message, return error # otherwise return rEs if Error.strip (): return {' Color ': ' Red ', ' res ': Error} else:return {' Color ': ' Green ' , ' res ': res} def upload (Self,local_path, Target_path): # connection, upload sftp = Paramiko. Sftpclient.from_transport (self.__transport) # upload location.py to server/tmp/test.py sftp.put (Local_path, target_p Ath, confirm=true) # Print (Os.stat (local_path). St_mode) # Add Permissions # sftp.chmod (Target_path, Os.stat (loca L_path). St_mode) Sftp.chmod (Target_path, 0o755) # Note that the permissions here are octal, octal needs to use 0o as the prefix def download (self,target_path, loc Al_path): # connection, download sftp = Paramiko. Sftpclient.from_transport (self.__transport) # download location.py to server/tmp/test.py sftp.get (Target_path, local_p     ATH) # Destroy Def __del__ (self): Self.close () #unicode_utils. Pydef to_str (BYTES_OR_STR): "" "Converts a byte type to str :p Aram Bytes_or_str:: Return: "" "If Isinstance (Bytes_or_str, bytes): value = Bytes_or_str.decode (' UTF -8') Else:value = bytes_or_str return value 

  

 

Resources

Wu Jianzi: http://www.cnblogs.com/wupeiqi/p/5699254.html

Alex Fortress Machine: http://www.cnblogs.com/alex3714/articles/5286889.html

Http://www.cnblogs.com/dachenzi/articles/7954443.html

 

Python Module Learning-Paramiko

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.