In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use Python remote control module Paramiko". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Python remote control module Paramiko.
Overview
Ssh is a protocol, OpenSSH is one of the open source implementations, and paramiko is a library of Python that implements the SSHv2 protocol (using cryptography at the bottom).
With Paramiko, we can use the SSH protocol to operate on the remote server directly in the Python code, rather than using the ssh command to operate on the remote server.
Paramiko introduction
Paramiko contains two core components: SSHClient and SFTPClient.
The function of SSHClient is similar to the ssh command of Linux, it is the encapsulation of SSH session, which encapsulates Transport, Channel and SFTPClient establishment method (open_sftp), and is usually used to execute remote commands.
The function of SFTPClient is similar to the sftp command of Linux, which encapsulates the SFTP client to realize remote file operations, such as file upload, download, file modification and other operations.
Several basic nouns in Paramiko:
Channel: is a kind of Socket, a secure SSH transmission channel
Transport: an encrypted session in which an encrypted Tunnels (channel) is created synchronously when used. This Tunnels is called Channel
Session: the object that client maintains a connection with Server, starting a session with connect () / start_client () / start_server ().
Basic use of Paramiko
1. Introduction of common methods of SSHClient
(1) connect (): realize the connection and authentication of the remote server. For this method, only hostname is a required parameter.
Common parameters
Target host for hostname connection
Port=SSH_PORT designated port
User name authenticated by username=None
User password authenticated by password=None
Pkey=None private key is used for authentication
Key_filename=None A file name or list of files that specifies the private key file
Timeout=None optional tcp connection timeout
Allow_agent=True, whether to allow connection to ssh proxy. Default is True to allow l
Whether ook_for_keys=True searches for private key files in ~ / .ssh. Default is True allowed.
Compress=False, whether to turn on compression
(2) set_missing_host_key_policy (): sets the response policy when the remote server is not recorded in the know_hosts file. Currently, three strategies are supported:
Set the policy when the connected remote host does not have a local host key or HostKeys object. Currently, three types of policies are supported:
AutoAddPolicy automatically adds the host name and host key to the local HostKeys object, which does not depend on the configuration of load_system_host_key. That is, there is no need to enter yes or no for confirmation when a new ssh connection is established.
WarningPolicy is used to record an python warning of an unknown host key. And accept, functionally similar to AutoAddPolicy, but will prompt for a new connection
RejectPolicy automatically rejects unknown hostnames and keys, depending on the configuration of load_system_host_key. This is the default option
(3) exec_command (): the method of executing Linux commands on a remote server.
(4) open_sftp (): creates a ssh session based on the current sftp session. This method returns a SFTPClient object.
Using the open_sftp () method of SSHClient object, you can directly return a sftp object based on the current connection, and you can upload files and other operations.
Sftp = client.open_sftp () sftp.put ('test.txt','text.txt')
Seven cases
1. Paramiko remote password connection
Import paramiko # # 1. Create a ssh object client = paramiko.SSHClient () # 2. Solve the problem: if there is no ip connected before, there will be an operation to select yes or no. # # automatically select yes client.set_missing_host_key_policy (paramiko.AutoAddPolicy ()) # 3. Connect to server client.connect (hostname='172.25.254.31', port=22, username='root', password='westos') # 4. Execute the operation stdin,stdout, stderr = client.exec_command ('hostname') # 5. Get the result of the command execution result=stdout.read (). Decode ('utf-8') print (result) # 6. Close the connection client.close ()
two。 Upload files using sftp
Import paramiko # get Transport instance tran = paramiko.Transport ("172.25.254.31", 22) # connect SSH server tran.connect (username = "root") Password = "westos") # get SFTP instance sftp = paramiko.SFTPClient.from_transport (tran) # set the uploaded local / remote file path localpath= "passwd.html" # # local file path remotepath= "/ home/kiosk/Desktop/fish" # # upload object saved file path # execute upload action sftp.put (localpath,remotepath) tran.close ()
3. Download files using sftp
Import paramiko # get SSHClient instance client = paramiko.SSHClient () client.set_missing_host_key_policy (paramiko.AutoAddPolicy ()) # Connect SSH server client.connect ("172.25.254.31", username= "root", password= "westos") # get Transport instance tran = client.get_transport () # get SFTP instance sftp = paramiko.SFTPClient.from_transport (tran) remotepath='/home/kiosk/Desktop/fish' localpath='/home/kiosk/Desktop/fish' sftp.get (remotepath Localpath) client.close ()
4. Batch remote password connection
From paramiko.ssh_exception import NoValidConnectionsError from paramiko.ssh_exception import AuthenticationException def connect (cmd,hostname,port=22,username='root',passwd='westos'): import paramiko # 1. Create a ssh object client = paramiko.SSHClient () # 2. Solve the problem: if there is no ip connected before, there will be an operation to select yes or no. # # automatically select yes client.set_missing_host_key_policy (paramiko.AutoAddPolicy ()) # 3. Connection server try: client.connect (hostnamehostname=hostname, portport=port, usernameusername=username, password=passwd) print ('connecting host% s.error% (hostname)) except NoValidConnectionsError as e: # error print ("connection failure") except AuthenticationException as t: # # password error print ("password error") else: # 4. Execute the operation stdin,stdout, stderr = client.exec_command (cmd) # 5. Get the result of the command execution result=stdout.read (). Decode ('utf-8') print (result) # 6. Close the connection finally: client.close () with open ('ip.txt') as f: # ip.txt is some user information in the local local area network for line in f: lineline = line.strip () # # remove the newline character hostname,port,username,passwd= line.split (':') print (hostname.center (50 Personality)) connect ('uname', hostname,port,username,passwd)
5. Paramiko connects based on public key
Import paramiko from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException def connect (cmd, hostname, port=22, user='root'): client = paramiko.SSHClient () private_key = paramiko.RSAKey.from_private_key_file ('id_rsa') # id_rsa is the local LAN key file client.set_missing_host_key_policy (paramiko.AutoAddPolicy ()) try: client.connect (hostnamehostname=hostname, portport=port, userusername=user, pkey=private_key) stdin, stdout Stderr = client.exec_command (cmd) except NoValidConnectionsError as e: print ("connection failure") except AuthenticationException as e: print ("password error") else: result = stdout.read (). Decode ('utf-8') print (result) finally: client.close () for count in range (254): host =' 172.25.254% s'% (count+1) print (host.center (50,'*') connect ('uname', host))
6. Key-based upload and download
Import paramiko private_key = paramiko.RSAKey.from_private_key_file ('id_rsa') tran = paramiko.Transport (' 172.25.254.31) tran.connect (username='root',password='westos') # get SFTP instance sftp = paramiko.SFTPClient.from_transport (tran) remotepath='/home/kiosk/Desktop/fish8' localpath='/home/kiosk/Desktop/fish2' sftp.put (localpath,remotepath) sftp.get (remotepath, localpath)
7. Repackaging of paramiko
Import os import paramiko from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException, SSHException class SshRemoteHost (object): def _ init__ (self, hostname, port, user, passwd, cmd): self.hostname = hostname self.port = port self.user = user self.passwd = passwd self.cmd = cmd def run (self): "# cmd hostname # put # get cmd_str = self.cmd.split () [0] # cmd # class reflection Determine whether the operation if hasattr (self, 'do_'+cmd_str): # do_cmd getattr (self,' do_'+cmd_str) () else: print ("not supported currently") def do_cmd (self): client = paramiko.SSHClient () client.set_missing_host_key_policy (paramiko.AutoAddPolicy ()) try: client.connect (hostname=self.hostname, port=self.port, username=self.user) Password=self.passwd) print ("connecting% s."% (self.hostname)) except NoValidConnectionsError as e: print ("connection failed") except AuthenticationException as e: print ("password error") else: # 4. Execute the operation cmd ='. Join (self.cmd.split () [1:]) # # take out the latter part of the input as stdin, stdout, stderr = client.exec_command (cmd) # 5. Get the result of command execution result = stdout.read () .decode ('utf-8') print (result) finally: # 6. Close the connection client.close () def do_put (self): # put / tmp/passwd # upload the local / tmp/passwd to the remote / tmp/passwd print ('uploading...') Try: # get Transport instance tran = paramiko.Transport (self.hostname,int (self.port)) # # because the port is shaping What we get with the split method is the str # connection to the SSH server tran.connect (username = self.user Password = self.passwd) except SSHException as e: print ('connection failed') else: # get SFTP instance sftp = paramiko.SFTPClient.from_transport (tran) newCmd = self.cmd.split () [1:] if len (newCmd) = 2: # set local / remote text path for upload localpath=newCmd [0] remotepath=newCmd [1] # perform upload action sftp.put (localpath Remotepath) print (% s file uploaded to% s host successfully'% (localpath,self.hostname,remotepath)) else: print ('upload file information error') tran.close () def do_get (self): print ('downloading...') Try: # get Transport instance tran = paramiko.Transport (self.hostname, int (self.port)) # # because the port is shaping What we get with the split method is that str # connects the SSH server tran.connect (username=self.user Password=self.passwd) except SSHException as e: print ('connection failed') else: # get SFTP instance sftp = paramiko.SFTPClient.from_transport (tran) newCmd = self.cmd.split () [1:] if len (newCmd) = 2: # set the local / remote text path for download localpath = newCmd [1] remotepath = newCmd [0] # perform the upload action sftp.get (remotepath Localpath) print (% s file downloaded to% s file successfully'% (self.hostname,remotepath,localpath)) else: print ('upload file information error') tran.close () import paramiko import os # 1. Select the host group for operation: eg:mysql,web,ftp groups= [file.rstrip ('.conf') for file in os.listdir ('conf')] print ("host group display:" .center (50 units) for group in groups: print ('\ tmachine group) choiceGroup = input ("select host group for batch operation (eg:mysql):") # # 2. Depending on the host group selected, the included host IP/ hostname # 1) is displayed. Open the file conf/choiceGroup.conf # 2). Read each line of the file in turn # 3). Just take out the print ("hosts included in the host group:" .center (50 grammatical hosts) with open ('conf/%s.conf'% (choiceGroup)) as f: for line inf: print (line.split (':) [0]) f.seek (0Pol 0) # # move the pointer to the beginning of the file hostinfos = [line.strip () for line in f.readlines ()] # 3. Let the user confirm the information and select the commands that need to be executed in batch # #-cmd shell command # #-put local file remote file # #-get remote file local file print ("batch execution script" .center (50, "*")) while True: cmd = input ('> >:'). Strip () if cmd: if cmd = = 'exit' or cmd = = "quit": print ("execution completed Break for info in hostinfos: host,port,user,passwd = info.split (':') clientObj = SshRemoteHost (host,port,user,passwd,cmd) clientObj.run () so far, I believe you have a deeper understanding of "how to use the Python remote control module Paramiko". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.