Python Learning record-paramiko module

Source: Internet
Author: User

Python Learning record-paramiko module

[TOC]

The Paramiko module is based on SSH for connecting to a remote server and performing related operations.

1. SSHClient

Used to connect to a remote server and execute basic commands

Connect based on user name password:

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

Sshclient Package Transport

import paramikotransport = paramiko.Transport((‘192.168.0.2‘, 22))transport.connect(username=‘root‘, password=‘test‘)ssh = paramiko.SSHClient()ssh._transport = transportstdin, stdout, stderr = ssh.exec_command(‘df‘)print(stdout.read().decode())transport.close()

Connection based on public key:

import paramikoprivate_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=‘192.168.0.2‘, port=22, username=‘root‘, 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‘, 22))transport.connect(username=‘root‘, pkey=private_key)ssh = paramiko.SSHClient()ssh._transport = transportstdin, stdout, stderr = ssh.exec_command(‘df‘)transport.close()

Connect 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= ' root ', pkey=private_key) ssh = Paramiko. Sshclient () Ssh._transport = Transportstdin, stdout, stderr = Ssh.exec_command (' df ') result = Stdout.read () Transport.close () Print (Result) 
2. SFTPClient

For connecting to a remote server and performing an upload download

Upload and download based on user name password

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

Upload and download based on public key keys

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

Demo

#!/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 = ' root ' self.pwd = ' 123 ' Self.__k = None def create_file (self): file_name = str (UUID.UUID4 ()) with open (file_name, ' W ') as F:F.WR        ITE (' 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/ro ot/tttttttttttt.py ') def rename (self):        SSH = Paramiko. Sshclient () Ssh._transport = self.__transport # Execute command stdin, stdout, stderr = Ssh.exec_command (' Mv/ho me/root/tttttttttttt.py/home/root/ooooooooo.py ') # gets the command result = Stdout.read () ha = Haproxy () ha.run ()

Python learning record-paramiko module

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.