Python_way DAY13 Paramiko

Source: Internet
Author: User

Paramiko

First, installation
PIP3 Install Paramiko

  

Second, use

1,sshclient

Used to connect to a remote server and execute basic commands

Import Paramiko   # SSH object created ssh = Paramiko. Sshclient () # allows connections to host Ssh.set_missing_host_key_policy (Paramiko) that are not in the Know_hosts file. Autoaddpolicy ()) # Connection Server Ssh.connect (hostname= ' c1.salt.com ', port=22, username= ' Wupeiqi ', password= ' 123 ')   # Execute command stdin, stdout, stderr = Ssh.exec_command (' ls ') # get command result = Stdout.read ()   # Close Connection ssh.close ()

Look at the code:

1, ssh = Paramiko. sshclient ()

def __init__ (self):
"""
Create a new sshclient.
"""
Self._system_host_keys = Hostkeys ()
Self._host_keys = Hostkeys ()
Self._host_keys_filename = None
Self._log_channel = None
Self._policy = Rejectpolicy ()
Self._transport = None
Self._agent = None


2, SSH. Connect (Hostname= ' c1.salt.com ', port=22, username= ' Wupeiqi ', password= ' 123 ')

326 Self._transport = Transport (sock, Gss_kex=gss_kex, gss_deleg_creds=gss_deleg_creds)

#其实SSHClient内部就是定义了transport来链接的

ImportParamiko#Create transport Specify host address and PortTransport = Paramiko. Transport (('hostname', 22))#connecting hosts using transportTransport.connect (username='Wupeiqi', password='123')#Create SSHSSH =Paramiko. Sshclient ()#Assignment TransportSsh._transport =Transportstdin, stdout, stderr= Ssh.exec_command ('DF')PrintStdout.read () transport.close ( )
The sshclient encapsulates the transport

Using Public key Links

Import Paramiko  Private_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa ')  # create ssh object ssh = Paramiko. Sshclient () # allows connections to host Ssh.set_missing_host_key_policy (Paramiko) that are not in the Know_hosts file. Autoaddpolicy ()) # Connection Server Ssh.connect (hostname= ' c1.salt.com ', port=22, username= ' Wupeiqi ', Key=private_key)  # Execute command stdin, stdout, stderr = Ssh.exec_command (' df ') # get command result = Stdout.read ()  # Close Connection ssh.close ()
ImportParamiko#defining secret key LocationsPrivate_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa')#Create TransportTransport = Paramiko. Transport (('hostname', 22))#use transport to specify the user name, specify the secret keyTransport.connect (username='Wupeiqi', pkey=Private_key)#ConnectionSSH =Paramiko. Sshclient ()#use to assign transport to a valueSsh._transport =Transport#Execute Commandstdin, stdout, stderr = Ssh.exec_command ('DF') Transport.close ()
The sshclient encapsulates the transport

  

2,sftpclient

For connecting to a remote server and performing an upload download

Upload and download based on user name password:

ImportParamiko#Create a link using transportTransport = Paramiko. Transport (('hostname', 22)) Transport.connect (username='Wupeiqi', password='123')  #and pour the transport intosftp=Paramiko. Sftpclient.from_transport (transport)#uploading location.py to the server/tmp/test.pySftp.put ('/tmp/location.py','/tmp/test.py')#download Remove_path to local Local_pathSftp.get ('Remove_path','Local_path') Transport.close () upload and download based on public key keys:

3, summary through the above SSH and SFTP can be seen that Paramiko links are used by the transport to achieve

#!/usr/bin/env python#-*-coding:utf-8-*-ImportParamikoImportUUIDclasssshconnection (object):def __init__(Self, host='172.16.103.191', Port=22, Username='Wupeiqi', pwd='123'): Self.host=host Self.port=Port Self.username=username Self.pwd=pwd self.__k=NonedefCreate_file (self): file_name=Str (UUID.UUID4 ()) with open (file_name,'W') as F:f.write ('SB')        returnfile_namedefRun (self): Self.connect () self.upload ('/home/wupeiqi/tttttttttttt.py') Self.rename ('/home/wupeiqi/tttttttttttt.py','/home/wupeiqi/ooooooooo.py)self.close ()defConnect (self): transport=Paramiko. Transport ((Self.host,self.port)) Transport.connect (username=self.username,password=self.pwd) self.__transport=TransportdefClose (self): self.__transport. Close ()defUpload (self,target_path):#Connect, uploadfile_name =self.create_file () sftp= Paramiko. Sftpclient.from_transport (self.__transport)        #uploading location.py to the server/tmp/test.pysftp.put (file_name, Target_path)defrename (self, Old_path, new_path): SSH=Paramiko. Sshclient () Ssh._transport= self.__transport        #Execute Commandcmd ="mv%s%s"%(Old_path, New_path,) stdin, stdout, stderr=Ssh.exec_command (cmd)#Get command Resultsresult =Stdout.read ()defcmd (self, command): SSH=Paramiko. Sshclient () Ssh._transport= self.__transport        #Execute Commandstdin, stdout, stderr =ssh.exec_command (command)#Get command Resultsresult =Stdout.read ()returnresult Ha=sshconnection () ha.run ( )

Python_way DAY13 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.