Python Paramiko module

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

Paramiko Module

1. Introduction:

Paramiko is a module for remote control, which can be used to command or file the remote server, it is worth saying that the fabric and ansible internal remote management is the use of Paramiko to reality.

2. Download and install

PIP3 Install Paramiko #在python3中
# in the Python2 PIP3 Install PYCRYPTOPIP3 install Paramiko Note: If the following error        occurred while installing pycrypto2.0.1 ' GCC ' failed with exit status 1 ... May be missing python-dev Install package causes GCC to be installed if GCC is not installed
in the Python2

3. Use

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='120.92.84.249', Port=22, Username='Root', password='XXX')#Execute Commandstdin, stdout, stderr = Ssh.exec_command ('DF')#Get command Resultsresult =Stdout.read ()Print(Result.decode ('Utf-8'))#Close ConnectionSsh.close ()
ImportParamikotransport= Paramiko. Transport (('120.92.84.249', 22)) Transport.connect (username='Root', password='XXX') SSH=Paramiko. Sshclient () Ssh._transport=Transportstdin, stdout, stderr= Ssh.exec_command ('DF') Res=Stdout.read ()Print(Res.decode ('Utf-8') ) Transport.close ()
sshclient Package Transport

Connection based on public key:

Client file name: I D_rsa

The server must have a file name: Authorized_keys (when using Ssh-keygen, must make a authorized_keys, can be made with Ssh-copy-id)

ImportParamikoprivate_key= Paramiko. Rsakey.from_private_key_file ('/tmp/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='120.92.84.249', Port=22, Username='Root', pkey=Private_key)#Execute Commandstdin, stdout, stderr = Ssh.exec_command ('DF')#Get command Resultsresult =Stdout.read ()Print(Result.decode ('Utf-8'))#Close ConnectionSsh.close ()
View Code
ImportParamikoprivate_key= Paramiko. Rsakey.from_private_key_file ('/tmp/id_rsa') Transport= Paramiko. Transport (('120.92.84.249', 22)) Transport.connect (username='Root', pkey=private_key) SSH=Paramiko. Sshclient () Ssh._transport=Transportstdin, stdout, stderr= Ssh.exec_command ('DF') Result=Stdout.read ()Print(Result.decode ('Utf-8') ) Transport.close ()
sshclient Package Transport
ImportParamiko fromIoImportStringiokey_str="""-----BEGIN RSA PRIVATE KEY-----Miieoqibaakcaqeasjmflrsecumjvga0gl5o5wvovwmiy2mpqiyqpi5j87dg89a4da9fczjog7qosbrwhfoqochnphslp5kphgsf6rjewkiw9h1uk v4dcoyl/ 4hoakadrkrsedmrj9jlzf2gttzsntgvqwcvbs2rkb4em2r9aj11xv6x2hk4ydltexiweabbh2tukw0iyji8pruylkkf2x16u9tbwfotrogyginfhqvhsqppbe bi49nf2xkckfmi8/7tljf95ine/vuuq56jqfzyhwdphou+waxbwtvggxn3sz+kkuev6r2qdz06upzvfczrrpdhzor8uh/ ueztgzb8z7fb6ejxuixjikqibiwkcaqbbmbugyff1bk+bgg7h9yse81ecqvsjtx4acflvrgscwg4rbqkivxs5an6xu/ vdngqnx0ryvbkvdvuzrrc8j8bd4kb0cfttgjuavigkoqp02hewx1hsa17+tlwd0c4kfbvwywi+ Dyq83s64x8gzeoalx9bpfenqorpud8r7gjekvpvc6ztpeorpuh7u9xayp0eop8qkxzza9xh3fovjqo4ixoyndn57cirx5pfslddggpmr8ftrf4naxmfq8lhsp 05ivzx/ku1snhdamwzo7va8tisxdli5m0egzovobvohibwlxi6kfmamrh6eas2jnsc4clzmsr4jbwt0lhlv/slnaogbanaeuf/jptab9g/ xd9w2tw/636i3glptpy9kptccaxqstnet6rawz5hflkjg+nkpu3pi45ldawvts0i+ Aczk2xakewizwqcmxm31jspdqtamge7h0vomuaxxncdpbvdvhmbffugei15ikfuafgrkas9oikntxegrc+3wboi0gbx3aogbanlagxaftk7ydr +q1+6/ujs6e8wsxt8hzma/1khcvsbrf1mgacvzpsssrdpvwadtsjlri4albb0l0rfu+/0camihilscujdz9fdd9ux4pjroza3tf5cfhvp7pszaoxoo+yqjg4zr996gg/aav4m8lqj2rdfk/dgn5y/ aaaun1om3aogagiqmoopyjy4qkhnsre9lyol4pzfqilkn8x5tlc8wtc4gcgjghx7nq9wq/j1eq/ykdfmznh+ ok6yjhkglglsruxhwgdcdcwuzbucwh76lhc1eytucknloa3qy8jfjwnmlhgrd3ftdilrc+ c7p1vj2favmqvz0moitpiopl8twp9mcgyeain49q3eyzfywxwdpu7/sjuvq750ozq0wvriuinsia6ir14oovbqkhb94fhsy12zgt/n9uosq22h +anms6cicoqicv4fnbhdfi3hche9ipgeh50gtjhua6xk34v2s/kp5kpthazv6qcw+ qubkqexh660sedslvocfpkmci1ejtukcgyazky1nz2bjjyyo/dfnvmq+etul/9esi+40gugyj7szcazrn9z+ do0yl39g7ft9nmic2dsmnjqmagbcdl0ajo1o3b/wqlrnvnbgkanxn2htn5ajfo+ lbu7yhacv7w4x5hlarxie1mj0lxfkjhdvfqu53kuqjxbqr6lsmqzsdpwlmjg==-----END RSA PRIVATE KEY-----"""Private_key= Paramiko. Rsakey (file_obj=Stringio (KEY_STR)) Transport= Paramiko. Transport (('120.92.84.249', 22)) Transport.connect (username='Root', pkey=private_key) SSH=Paramiko. Sshclient () Ssh._transport=Transportstdin, stdout, stderr= Ssh.exec_command ('DF') Result=Stdout.read ()Print(Result.decode ('Utf-8') ) Transport.close ()Print(Result)
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 (('120.92.84.249', 22)) Transport.connect (username='Root', password='XXX') sftp=Paramiko. Sftpclient.from_transport (transport)#uploading location.py to the server/tmp/test.pySftp.put ('/tmp/id_rsa','/etc/test.rsa')#download Remove_path to local Local_pathSftp.get ('Remove_path','Local_path') Transport.close ()
View Code

Upload and download based on public key keys

ImportParamikoprivate_key= Paramiko. Rsakey.from_private_key_file ('/tmp/id_rsa') Transport= Paramiko. Transport (('120.92.84.249', 22)) Transport.connect (username='Root', pkey=private_key) sftp=Paramiko. Sftpclient.from_transport (transport)#uploading location.py to the server/tmp/test.pySftp.put ('/tmp/id_rsa','/tmp/a.txt')#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='Root'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/root/tttttttttttt.py')    defrename (self): SSH=Paramiko. Sshclient () Ssh._transport= self.__transport        #Execute Commandstdin, stdout, stderr = Ssh.exec_command ('mv/home/root/tttttttttttt.py/home/root/ooooooooo.py')        #Get command Resultsresult =stdout.read () Ha=Haproxy () ha.run ( )
Demo Seven jobs

Title: Simple Mainframe Bulk management tool

Demand:

    1. Host grouping
    2. Host information configuration file with Configparser parsing
    3. Can execute the command in batch, send the file, the result returns in real time, the execution format is as follows
      1. Batch_run-h h1,h2,h3-g web_clusters,db_servers-cmd "Df-h"
      2. Batch_scp-h h1,h2,h3-g web_clusters,db_servers-action put-local test.py-remote/tmp/
    4. Host user name password, port can be different
    5. Execute remote command using Paramiko module
    6. Bulk commands need to use multiprocessing concurrency

Python 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.