Python Learning Path Network programming chapter (fifth)-sequel

Source: Internet
Author: User

Basic knowledge of Python Fortress machine implementation

The general fortress machine must have the following 5 basic functions:

  1, permission control  2, execute command  3, upload download file  4, Telnet  5, record operation

Permission control

Description: Assign different manageable host groups according to the different login users. (The permissions that are subdivided are the commands that can be executed on the host based on different user controls, which are generally not so restrictive)

Idea: Use a database to create user tables, table fields have ID, user name, password, owning group, and then create Host table, table field has ID, host IP, owning group. The owning group in the user table corresponds to the owning group in the host table, so that you can associate the two tables together. When the user logs in, it is possible to obtain a manageable list of hosts based on the user name.

Example: Here are just a few examples of Python connection to MySQL database

Execute command:

Description: The execution command here generally refers to the batch execution of commands, such as the need to obtain the host name of the N host.

Idea: Use the Paramiko module to implement a Telnet server and execute commands. Use multiprocessing to implement batch concurrency.

Example: (here only write the Paramiko module remote password Login server and execute the command example)

Import Paramiko Class Paramiko_manage (): Def __init__ (self,host,port,user,passwd): #初始化连接服务器所需要的参数 self.host        = Host Self.port = Port Self.user = User SELF.PASSWD = passwd #使用密码认证 def connect (self): #连接方法, used to establish a connection to the server Self.transport = Paramiko. Transport ((Self.host,self.port)) Self.transport.connect (username=self.user,password=self.passwd) print (' conn ECT ') def close (self): #关闭方法, used to close the connection to the server Self.transport.close () print (' Close ') def cmd (self, command): #执行命令的方法, receive commands that need to be executed as parameters ssh = Paramiko.        Sshclient () Ssh._transport = Self.transport stdin, stdout, stderr = Ssh.exec_command (command,timeout=3) Print (' Command resluat: ', Stdout.read ()) def run (Self,command): Self.connect () #建立连接 self.cmd (command) #执行命令 self.close () #关闭连接 p = paramiko_manage (' 192.168.100.20 ', +, ' test ', ' 123456 ') p.run (' Host Name ') # execution Result: # connect# CommanD resluat:test1# # Close 

Upload and download files:

Description: Bulk upload file is relatively simple, if it is a batch download file also need to take into account the multiple server file name problem.

You also need to consider the size of the file after uploading to confirm that the upload download was successful.

Idea: Use the Paramiko module to implement remote upload and download files. Use multiprocessing to implement batch concurrency.

Example: (here only write the Paramiko module remote key authentication login server and execute the command example)

Import Paramikoimport OS class Paramiko_manage (): Def __init__ (self,host,port,user,key): Self.host = Host Self.port = Port Self.user = User KeyFile = Os.path.expanduser (key) #使用秘钥认证 Self.key = PARAMIKO.R Sakey.from_private_key_file (keyfile) def connect (self): Self.transport = Paramiko.      Transport ((Self.host,self.port)) Self.transport.connect (username=self.user,pkey=self.key) print (' Connect ')        def close (self): Self.transport.close () print (' Close ') def trans (self,file1,file2): #传输文件的方法 SFTP = Paramiko. Sftpclient.from_transport (self.transport) file1 = '%s_%s '% (File1, self.host) #修改下载文件的保存文件名 sftp.get (file 2,file1) file1_size = Os.path.getsize (file1) #获取下载文件的大小 file2_size = Int (str (SFTP.STAT)). Split () [4] ) #获取远程文件的大小 if file1_size = = file2_size: #比较两个文件大小 print (' File trans done ') def run (Self,file1,    File2): Self.connect ()  #建立连接 Self.trans (file1,file2) #传输文件 self.close () #关闭连接 p = paramiko_manage (' 192.168.100.20 ', ', ' test2 ', ' ~/.ssh/id_rsa ') p.run ('/root/hosts ', '/etc/hosts ') # Execution Result: # connect# File Trans done# close

Remote login and logging operations:

Description: Connect to the server remotely via the bastion machine ssh and perform the same action as the terminal.

Idea: Use Paramiko to implement remote connection server functionality, use Sys.stdin and select to process user input and accept return results.

Example:

Import paramikoimport selectimport sysimport socketimport os tran = Paramiko. Transport ((host,port)) #连接服务器, host and Port Custom tran.start_client () Default_path = Os.path.join (os.environ[' HOME '), '. SSH ', ' id_rsa ') key = Paramiko. Rsakey.from_private_key_file (Default_path) tran.auth_publickey (' root ', key) Chan = Tran.open_session () # Open a channel chan.get_pty () #获取一个终端chan. Invoke_shell () #激活器 f = open (' Log.log ', ' a ') #打开一个文件用于写入执行的 Operation while True: # Monitor user input and server return data # Sys.stdin processing user Input # Chan is the channel previously created to receive server return information Readable,writeable,error = Selec            T.select ([chan,sys.stdin,],[],[],1) if Chan in readable: #接受命令的返回结果 try:x = CHAN.RECV (1024)                If Len (x) = = 0:print (' \r\n*** eof\r\n ',) f.close () #退出时关闭记录文件 Break Sys.stdout.write (x) Sys.stdout.flush () except Socket.timeout:pass if Sys . stdin in readable: #处理用户输入发送到服务器执行 INP = Sys.stdin.readlINE () f.write (INP) #记录用户输入 Chan.sendall (INP) chan.close () Tran.close () 

  

 

 

Python Learning Path Network programming chapter (fifth)-sequel

Related Article

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.