Python-----bastion Machine foreplay Paramiko module

Source: Internet
Author: User

Fortress Machine Foreplay

Before developing a bastion machine, learn the Python Paramiko module, which is an opportunity for SSH to connect to a remote server and perform related operations

Sshclient

Used to connect to a remote server and execute basic commands

Connect based on user name password:

ImportParamiko#To create an SSH objectSSH =Paramiko. Sshclient ()#allow connections to hosts that are not in the Know_hosts fileSsh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())#connecting to a serverSsh.connect (hostname='c1.salt.com', Port=22, Username='Wupeiqi', password='123')  #Execute Commandstdin, stdout, stderr = Ssh.exec_command ('DF')#Get command Resultsresult =Stdout.read ()#Close ConnectionSsh.close ()
View Code
ImportParamikotransport= Paramiko. Transport (('hostname', 22)) Transport.connect (username='Wupeiqi', password='123') SSH=Paramiko. Sshclient () Ssh._transport=Transportstdin, stdout, stderr= Ssh.exec_command ('DF')PrintStdout.read () transport.close ( )
sshclient Package Transport

Connection based on public key:

ImportParamiko Private_key= Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa') #To create an SSH objectSSH =Paramiko. Sshclient ()#allow connections to hosts that are not in the Know_hosts fileSsh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())#connecting to a serverSsh.connect (hostname='c1.salt.com', Port=22, Username='Wupeiqi', key=Private_key)#Execute Commandstdin, stdout, stderr = Ssh.exec_command ('DF')#Get command Resultsresult =Stdout.read ()#Close ConnectionSsh.close ()
View Code
ImportParamikoprivate_key= Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa') Transport= Paramiko. Transport (('hostname', 22)) Transport.connect (username='Wupeiqi', pkey=private_key) SSH=Paramiko. Sshclient () Ssh._transport=Transportstdin, stdout, stderr= Ssh.exec_command ('DF') Transport.close () Sshclient Package Transport
sshclient Package Transport
ImportParamiko fromIoImportStringiokey_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', 22)) 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) connection based on a private key string
Connect based on a private key string

Sftpclient

For connecting to a remote server and performing an upload download

Upload and download based on user name password

ImportParamiko Transport= Paramiko. Transport (('hostname', 22)) Transport.connect (username='Wupeiqi', password='123') sftp=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 ()
View Code

Upload and download based on public key keys

ImportParamiko 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)#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 ()
View Code
#!/usr/bin/env python#-*-coding:utf-8-*-ImportParamikoImportUUIDclassHaproxy (object):def __init__(self): Self.host='172.16.103.191'Self.port= 22Self.username='Wupeiqi'self.pwd='123'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 () Self.rename () 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):#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,'/home/wupeiqi/tttttttttttt.py')    defrename (self): SSH=Paramiko. Sshclient () Ssh._transport= self.__transport        #Execute Commandstdin, stdout, stderr = Ssh.exec_command ('mv/home/wupeiqi/tttttttttttt.py/home/wupeiqi/ooooooooo.py')        #Get command Resultsresult =stdout.read () Ha=Haproxy () ha.run () Demo
DemoImplementation of the Fortress machine

Bastion Machine Execution Flow:

    1. Administrator creates an account for the user on the server (place the public key on the server, or use the username password)
    2. User Login Fortress Machine, enter the Fort machine user name password, the actual current user Management Server list
    3. The user chooses the server and automatically logs in
    4. Perform actions and record user actions at the same time

Note: Configure the. BRASHRC to implement the script automatically after SSH login, such as:/usr/bin/python/home/wupeiqi/menu.py

Implementation process

Step one, realize user login

Python-----bastion Machine foreplay 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.