再接上次:http://blog.oldyang.net/archives/226
之前用paramiko的库比较简单一些,但是上周末测试了一下,如果太多的话,性能就很低下了。很装B的试用了一下twisted,效率很高。这点不是盖的。
下面的程序还是有点点小问题,先放这里,以后再完善
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from twisted.conch import error
from twisted.conch.ssh import transport, connection, keys, userauth, channel, common
from twisted.internet import defer, protocol, reactor
import ConfigParser
class ClientCommandTransport(transport.SSHClientTransport):
def __init__(self, username, password, command):
self.username = username
self.password = password
self.command = command
def verifyHostKey(self, pubKey, fingerprint):
return defer.succeed(True)
def connectionSecure(self):
self.requestService(
PasswordAuth(self.username, self.password,
ClientConnection(self.command)))
class PasswordAuth(userauth.SSHUserAuthClient):
def __init__(self, user, password, connection):
userauth.SSHUserAuthClient.__init__(self, user, connection)
self.password = password
def getPassword(self, prompt=None):
return defer.succeed(self.password)
class ClientConnection(connection.SSHConnection):
def __init__(self, cmd, *args, **kwargs):
connection.SSHConnection.__init__(self)
self.command = cmd
def serviceStarted(self):
self.openChannel(CommandChannel(self.command, conn=self))
class CommandChannel(channel.SSHChannel):
name = 'session'
def __init__(self, command, *args, **kwargs):
channel.SSHChannel.__init__(self, *args, **kwargs)
self.command = command
def channelOpen(self, data):
self.conn.sendRequest(
self, 'exec', common.NS(self.command), wantReply=True).addCallback(
self._gotResponse)
def _gotResponse(self, _):
self.conn.sendEOF(self)
def dataReceived(self, data):
print data
def closed(self):
reactor.stop()
class ClientCommandFactory(protocol.ClientFactory):
def __init__(self, username, password, command):
self.username = username
self.password = password
self.command = command
def buildProtocol(self, addr):
protocol = ClientCommandTransport(
self.username, self.password, self.command)
return protocol
def ReadConfig(file='conf/test.ini'):
ips = []
commands = []
Config = ConfigParser.ConfigParser()
Config.read(file)
username = Config.get("BASEINFO","USERNAME")
password = Config.get("BASEINFO","PASSWORD")
port = int(Config.get("BASEINFO","PORT"))
threads = int(Config.get("BASEINFO","THREADS"))
machines = Config.items("MACHINES")
cmds = Config.items("COMMANDS")
for ip in machines:
ips.append(ip[1])
for command in cmds:
commands.append(command[1])
return username, password, port, threads, ips, commands
username, password, port, threads, ips, commands = ReadConfig()
def Launcher(i, q, command):
while True:
ip = q.get()
for command in commands:
try:
factory = ClientCommandFactory(username, password, command)
reactor.connectTCP(ip, port, factory)
except:
pass
q.task_done()
for ip in ips:
for command in commands:
reactor.callInThread(target=Launcher, args=(i, command))
reactor.callLater(0.5,reactor.stop)
reactor.run()
Recent Comments