select模块

应用一:多并发服务器

 1 #!/usr/bin/env python
 2 #created by Baird
 3 
 4 import socket
 5 import select
 6 import queue
 7 
 8 server = socket.socket()
 9 server.bind(("localhost",6969))
10 server.listen()
11 
12 server.setblocking(False)       #设置为非阻塞
13 
14 inputs = [server,]
15 outputs = []
16 data_dict = {}
17 
18 while True:
19     readable,writeable,exceptional = select.select(inputs,outputs,inputs)
20     # print(readable,writeable,exceptional)
21 
22     for r in readable:
23         if r is server:     #如果事件为连接请求
24             conn,addr = server.accept()       #接收一个连接请求
25             inputs.append(conn)               #将连接描述符添加到inputs监听列表
26             print("inputs",inputs)
27             data_dict[conn] = queue.Queue()     #创建连接对应的消息队列
28         else:           #客户端事件
29             recv_data = r.recv(1024).decode()   #接收数据
30             data_dict[r].put(recv_data)         #将数据放入消息队列
31             outputs.append(r)   #将连接对象添加到输出监听队列
32 
33     for w in writeable:
34         data = data_dict[w].get()       #从消息队列获得数据
35         w.send(data.upper().encode())   #将数据发送到客户端
36         outputs.remove(w)               #移除监听连接
37 
38     for e in exceptional:           #异常连接
39         if e in outputs:
40             outputs.remove(e)
41         inputs.remove(e)
42 
43         del data_dict[e]

应用二:连接远程机,切换用户,批量执行命令

# -*- coding: utf-8 -*-
#!/usr/bin/env python
#created by Baird

import paramiko
import logging
import select

consolelogger = logging.getLogger('consolelogger')

class SSHDriver(object):

    def __init__(self,sshpara):
        self.para = sshpara
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
        self.buf = ''

    def __del__(self):
        self.ssh.close()
        print('Disconnect with %s' % self.para['host'])

    def connect(self):
        try:
            self.ssh.connect(self.para['host'],self.para['port'],self.para['username'],self.para['passwd'])
            self.shell = self.ssh.invoke_shell()        #连接
            self.shell.setblocking(False)               #非阻塞
        except Exception as e:
            consolelogger.error(str(e))
            raise e

    def writable(self,str):
        pattern = [':', '>', '$', '#', ': ', '> ', '$ ', '# ']
        keyword = ['Password', u'密码']
        for s in pattern:
            if str.endswith(s):
                return True

        for key in keyword:
            if key in str:
                return True
        return False

    def excuteCmd(self,cmds):
        inputs = [self.shell, ]
        outputs = []
        command = cmds

        command.insert(0,'su - %s\n'%self.para['Suser'])      #增加su指令
        command.insert(1,'%s\n'%self.para['Spasswd'])

        while True:
            readable, writeable, exceptional = select.select(inputs, outputs, inputs)

            for r in readable:
                recv_data = r.recv(1024).decode('utf8')
                self.buf = self.buf + recv_data
                if self.writable(recv_data):                #打开写监听
                    outputs.append(r)

            for w in writeable:                             #发送一次数据,并移除改监听句柄
                w.send(command[0].encode())
                del command[0]
                outputs.remove(w)

            for e in exceptional:
                self.buf = self.buf + str(e)
                consolelogger.error(str(e))
                break

            if command == []:
                break

    def setTimeOut(self,second):
        self.shell.settimeout(second)

if __name__ == '__main__':
    sshpara = {
        'host':'192.168.42.132',
        'port':22,
        'username':'test',
        'passwd':'123456',
        'Suser':'root',
        'Spasswd':'123456~'
    }
    new = SSHDriver(sshpara)        #初始化
    new.connect()                                           #建立连接
    cmds = ['ls\n','pwd\n','whoami\n','\n']             #创建指令集
    new.excuteCmd(cmds)                                     #执行指令
    print(new.buf)

猜你喜欢

转载自www.cnblogs.com/baird/p/9541810.html