Python Paramiko module + Fortress machine

Source: Internet
Author: User
Tags begin rsa private key key string stdin haproxy

Paremiko

Sshclient

Used to connect to a remote server and execute basic commands

Connect based on user name password:

importparamiko
  # 创建SSH对象 ssh  = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname = ‘c1.salt.com‘ , port = 22 , username = ‘wupeiqi‘ , password = ‘123‘ )   # 执行命令 stdin, stdout, stderr  = ssh.exec_command( ‘df‘ ) # 获取命令结果 result  = stdout.read()   # 关闭连接 ssh.close()

Sshclient Package Transport

The concept of encapsulation forgot ...

Import Paramikotransport = Paramiko. Transport (' hostname ', ()) Transport.connect (username= ' Wupeiqi ', password= ' 123 ') ssh = Paramiko. Sshclient () Ssh._transport = Transportstdin, stdout, stderr = Ssh.exec_command (' df ') print stdout.read () transport.close ()

Connection based on public key

importparamiko
private_key  = paramiko.RSAKey.from_private_key_file( ‘/home/auto/.ssh/id_rsa‘ ) # 创建SSH对象 ssh  = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname = ‘c1.salt.com‘ , port = 22 , username = ‘wupeiqi‘ , key = private_key) # 执行命令 stdin, stdout, stderr  = ssh.exec_command( ‘df‘ ) # 获取命令结果 result  = stdout.read() # 关闭连接 ssh.close()

Sshclient Package Transport

Import Paramikoprivate_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa ') transport = Paramiko. Transport (' hostname ', ()) Transport.connect (username= ' Wupeiqi ', pkey=private_key) ssh = Paramiko. Sshclient () Ssh._transport = Transportstdin, stdout, stderr = Ssh.exec_command (' df ') transport.close ()

Link based on a private key string

Import paramikofrom io Import stringiokey_str = ""-----BEGIN RSA PRIVATE KEY-----miiepqibaakcaqeaq7glsqyarafco02/ 55igng0r7nxotem3qxpb/dabj5uyky/8nehhfiq7dehiriutw5zb0kd6h6ebbvlumbmwjrc2oszyslu1w+znfh0pe6w6fansh80whhuc/ygp+ fjio+vr/gfcqib8rll5ufyzf5h8uuondeixgcvgyhqsmt8if1+e7hn1mvo1lrm9fco8abi7dyv8/ Zewosfh2c9rgyga58lt1fkbrkoepbhd43xnfayctflvz6lermnwdow4snmewwawv1fstb35pam5cazfkzmam9n5iqxhmuncnvmaztvpc4f4g59mdsawntnay9 6ujofx83om86gmdkkcnwidaqabaoibaqcndbgfjuv8aa7azkble+gn815jtoyye7lis1n2i7en3oimouwnajeywwj8+lmjxmwdctakr0xwbvy+ c+nskpetkjb3sau6i148rmwwsgncsrquajrljoypaw9ds+go4ujjz3/ lw1lrxsuhiqvc0e7kyrw8kp3qcanbwarytehrezffp6xmtkmtxaea3sajyilxaaxlykori4k8s2/k8aw3zmr4tdcofb4o47jaeia/e185rk3a+ mln9xtdhtdzqtqpv17/yrpcgmwzzu30fhvxqt/sui0so+bzco4ygoewobx718awhdljfofq1b7k2zezxtatjexqewm601ndu/ Jhaasdfasdasdfasdfa3eraszxqwefasdfadasdffsfifasjqb4hdkmhucoejrjod+ cyvdeeqjjnnf6abhyyhieckj0qq1kefloesqzd5ndbtkkbte6m1trbjlhtj2yb8w6o/q/6sbj7wf/cw3liyedevcjscozvcq9r83ea05j+ Qoar4naogbamaquzljflnwz5qosmir2ohstflzpxspax/ln7dlwlw4wpb4yjalsvovf2buo8hr8x65lnpie41m+g0z7icexifydbfdctzx0x/ rmaboklathrfti81ucx4gqplasvnmlvqa539gsubsro4lphrngg/ Wez6eqqoxvhvkukm2bddjaogatytfnxen6gtc0zt3srqmwyfasdf3xbtuykmnluiofasd2sfmjnljkt7khghmghdassdfgqfgafokfaawoyehc2xasvusvvib n8kpslsvbpx4jufqma6h8hsajevahxn1u9e0nyj0sydqfumts2t8rt57+wk/0onwtwhdu+knajecgyeaid/ta8lqc3p82inazkpwlgdsd2yb/ 8rh8nqg9tjeryfwrbmtfx9qn+8srx06b796u3ojifstjjqnmvi0qnlsjpqk8fpwvxrxbjs/ pmbnicrf3sua4szgdoffkeuslgach4cviozdxlr59z8y3coiw0uobegvmdifenaj98pl3zkcgyeaj/ ucsni0dwx4pnknpm6lugis7qvigm3h9piyt8aipquzbi5lukwwdlqc4zb73nhgdretqyyxtu7p27bl0gizz1sw2esgxfu8eth+ ucfvwoxkaxku5sei+mbubfuyq4if2n/bxn47+/ecf3a4kgb37le5sbldddwcnxglbzbpba0=-----END RSA PRIVATE KEY-----"" "Private_ Key = Paramiko. Rsakey (File_obj=stringio (KEY_STR)) transport = Paramiko. Transport (' 10.0.1.40 ', ()) Transport.connect (username= ' Wupeiqi ', pkey=private_key) ssh = Paramiko. Sshclient () Ssh._transport = Transportstdin, stdout, stderr = Ssh.exec_command (' df ') result = Stdout.read () transport.cloSE () print (result) 

Sftpclient

Used to link a remote server and perform an upload download.

Upload and download based on user name:

Import Paramiko
transport  = paramiko.Transport(( ‘hostname‘ , 22 )) transport.connect(username = ‘wupeiqi‘ ,password = ‘123‘ ) sftp  = paramiko.SFTPClient.from_transport(transport) # 将location.py 上传至服务器 /tmp/test.py sftp.put( ‘/tmp/location.py‘ ‘/tmp/test.py‘ ) # 将remove_path 下载到本地 local_path sftp.get( ‘remove_path‘ ‘local_path‘ ) transport.close()

Upload and download based on public key keys


private_key  = paramiko.RSAKey.from_private_key_file( ‘/home/auto/.ssh/id_rsa‘ ) transport  = paramiko.Transport(( ‘hostname‘ 22 )) transport.connect(username = ‘wupeiqi‘ , pkey = private_key ) sftp  = paramiko.SFTPClient.from_transport(transport) # 将location.py 上传至服务器 /tmp/test.py sftp.put( ‘/tmp/location.py‘ ‘/tmp/test.py‘ ) # 将remove_path 下载到本地 local_path sftp.get( ‘remove_path‘ ‘local_path‘ ) transport.close()

Summary: If you execute a command remotely, both sshclient and transport can, if uploading a file can only transport

Based on object-oriented Damo:

#!/usr/bin/env python#-*-coding:utf-8-*-import paramikoimport uuidclass Haproxy (object): Def __init__ (self): Self.host = ' 172.16.103.191 ' self.port = self.username = ' Wupeiqi ' self.pwd = ' 123 ' self.__ K = None def create_file (self): file_name = str (UUID.UUID4 ()) with open (file_name, ' W ') as F:f        . Write (' SB ') return file_name def run (self): Self.connect () self.upload () Self.rename () Self.close () def 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 upload (self): # connection, upload file_name = s Elf.create_file () sftp = Paramiko. Sftpclient.from_transport (self.__transport) # upload location.py to server/tmp/test.py sftp.put (file_name, '/home/wu peiqi/tttttttttttt.py ') def rename (Self): SSH = Paramiko. Sshclient () Ssh._transport = self.__transport # Execute command stdin, stdout, stderr = Ssh.exec_command (' Mv/ho me/wupeiqi/tttttttttttt.py/home/wupeiqi/ooooooooo.py ') # gets the command result = Stdout.read () ha = Haproxy () ha.run ( )

Python Paramiko module + Fortress machine

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.