批量生成SecureCRT的session文件之shell版

窗外世界 1 Comment »

上次写了一个python版:http://blog.oldyang.net/archives/241,这次再来个shell版

#!/bin/sh
def_readfile="host"
def_str="192.168.0.1"
def_ext="ini"
def_example="example.${def_ext}"
def_dir="session"
def_maclen="4"

if [ -d ${def_dir} ];
then
    rm -rf ${def_dir}
    mkdir ${def_dir}
else
    mkdir ${def_dir}
fi

while IFS=' ' read def_host def_ip
do
    def_leng=$(echo "${def_host}" |awk -F"[a-zA-Z]" '{print $NF}' | echo `wc -m`-1 | bc)
    def_group=$(echo "${def_host}" | awk -F"[0-9]" '{print $1}')
    def_machine=$(echo "${def_host}" | awk -F"[A-Za-z]" '{print $NF}')
    if [ ${def_leng} -ge "${def_maclen}" ];then
        sed "s/${def_str}/${def_ip}/g" ${def_example} > ${def_dir}/\(${def_host}\)${def_ip}.${def_ext}
    else
        def_diff=$(echo "${def_maclen}-${def_leng}" | bc)
        def_zero=$(for i in `seq 1 ${def_diff}`;do echo 0;done | xargs -n ${def_diff} | sed 's/ //g')
        def_host=$(echo "${def_group}${def_zero}${def_machine}")
        sed "s/${def_str}/${def_ip}/g" ${def_example} > ${def_dir}/\(${def_host}\)${def_ip}.${def_ext}
    fi
done < ${def_readfile}

使用python设计ssh分发工具(三)

窗外世界 No Comments »

再接上次: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()

批量生成SecureCRT的session文件

窗外世界 13 Comments »

看到罗菊长的博客,献上python版一枚,当然写得比较傻

#!/usr/bin/env python
import os
import re
try:
    if not os.path.isdir("session"):
        os.mkdir("session")
except:
    pass

file = open("host")
input = open ('example.ini','r')
s = input.read()
while True:
    line = file.readline()
    if line:
       splitline = line.split()
       hostname = splitline[0]
       ipaddress = splitline[1]
       string_1 = "%s" % (hostname)
       result_obj = re.search('[0-9]+',string_1)
       length_of_number = len( string_1 ) - result_obj.start()
       def_leter = string_1[:result_obj.start()]
       def_number = string_1[result_obj.start():]
       filename = ""
       if length_of_number == 4:
           hostname = "%s%s" %(def_leter,def_number)
           filename = "(%s)%s.ini" % (hostname, ipaddress)
           hostname = "%s%s" %(def_leter,def_number)
       elif length_of_number == 3:
           hostname = "%s0%s" %(def_leter,def_number)
           filename = "(%s)%s.ini" % (hostname, ipaddress)
       elif length_of_number == 2:
           hostname = "%s00%s" %(def_leter,def_number)
           filename = "(%s)%s.ini" % (hostname, ipaddress)
       elif length_of_number == 1:
           hostname = "%s000%s" %(def_leter,def_number)
           filename = "(%s)%s.ini" % (hostname, ipaddress)
       output = open ("session/%s" %(filename),"w" )
       output.write(s.replace("192.168.157.128","%s" %(ipaddress)))
    else:
       break
input.close()
file.close()

神奇的矩阵

窗外世界 No Comments »

很有意思的矩阵,Oh Matrix~。抽空再想想怎么样可以写成一个解魔方的方法。

#!/bin/sh
exec awk '
NR == 1 {
        n = NF
        for (i = 1; i <= NF; i++)
                row[i] = $i
        next
}
{
        if (NF > n)
                n = NF
        for (i = 1; i <= NF; i++)
            row[i] = row [i] " " $i

}
END {
        for (i = 1; i <= n; i++)
            print row[i]

}' ${1+ "$@"}

使用python设计ssh分发工具(二)

窗外世界 19 Comments »

接上次:http://blog.oldyang.net/archives/163

对部分功能进行了完善,先放这里以后接着优化

update:2010-2-28:今天下午看了点资料,对程序的线程处理上进行了部分优化,性能又提高了小小。

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

"""
FileName : dispatch.py
Autor: David Young <e4twood@gmail.com>
Version:0.1.4(20100228)
A ssh based command simple dispatch tool
Using this program requires paramiko support, so that before the use of the python modules to install paramiko

Usage:
 python dispatch.py CONFIGFILE
Example:
 python dispatch.py conf/config.ini

More config options please see the config file on conf directory
"""

#导入相关模块
import Crypto
import paramiko
import os
import time
import ConfigParser
import base64
import sys
from threading import Thread
from Queue import Queue
from paramiko import AutoAddPolicy, SSHClient

queue = Queue()

#记录开始时间戳
start = int(time.time())

# 检查参数个数
if len(sys.argv) <= 1:
 print 'Error!missing parameter.'
 print 'Usage:python %s configfile' % sys.argv[0]
 print 'Example:python %s conf/config.ini' % sys.argv[0]
 exit(1)

#读取配置文件
configfile = sys.argv[1]
def readConfig(file=configfile):
 ips = []
 cmds = []
 Config = ConfigParser.ConfigParser()
 Config.read(file)
 username = Config.get("BASEINFO","USERNAME")
 password = base64.b64decode(Config.get("BASEINFO","PASSWORD"))
 port = int(Config.get("BASEINFO","PORT"))
 threads = int(Config.get("BASEINFO","THREADS"))
 log_file = Config.get("BASEINFO","LOG_FILE")
 log_level = int(Config.get("BASEINFO","LOG_LEVEL"))
 pid_file = Config.get("BASEINFO","PID_FILE")
 machines = Config.items("MACHINES")
 commands = Config.items("COMMANDS")
 for ip in machines:
 ips.append(ip[1])
 for cmd in commands:
 cmds.append(cmd[1])
 return ips, cmds, username, password, port, threads, log_file, log_level, pid_file

ips, cmds, username, password, port, threads, log_file, log_level, pid_file = readConfig()

#记录当前pid
pid = str(os.getpid())
f = file(pid_file, 'w')
f.write(pid)
f.close

#使用paramiko进行远程SSH调用
def launcher(i,q, cmd):
 while True:
 ip = q.get()
 for cmd in cmds:
 try:
 paramiko.util.log_to_file(log_file, level = log_level)
 client = paramiko.SSHClient()
 client.set_missing_host_key_policy(AutoAddPolicy())
 client.connect((ip), username=(username), password=(password), port=(port))
 stdin, stdout, stderr = client.exec_command(cmd)
 print stdout.read()
 client.close()
 except:
 pass
 print "Connect to %s  Failed!" % ip
 q.task_done()

#使用线程启动,并检测线程数量
if len(ips) < threads:
 num_threads = len(ips)
else:
 num_threads = threads

for i in range(num_threads):
 for cmd in cmds:
 worker = Thread(target=launcher, args=(i, queue, cmd))
 worker.setDaemon(True)
 worker.start()

#线程排队
for ip in ips:
 queue.put(ip)
queue.join()

#打印任务结束时间戳
end = int(time.time())

#统计任务运行时间
print "Dispatch Task Completed in %s seconds" % (end - start)

配置文件式例:

;基本的配置信息
[BASEINFO]
;远程ssh主机用户名
USERNAME = root
;远程ssh主机密码,做base64加密处理
PASSWORD = <code>MTIzMzMzMw</code><code>=</code><code>=</code>
;远程ssh主机端口
PORT = 22
;线程数量 默认为10,并非越多越好。
THREADS = 10
;日志存放路径
LOG_FILE = logs/dispatch.log
;日志等级,分别为10,20,30,40,50
LOG_LEVEL = 10
;pid文件存放路径
PID_FILE = logs/dispatch.pid
;主机列表
[MACHINES]
APP2 : 192.168.0.1
APP3 : 192.168.1.8
;命令列表
[COMMANDS]
B : echo `hostname`
[MACHINES]
TEST1 : 192.168.100.1
TEST2 : 192.168.100.2
TEST3 : 192.168.100.3
[COMMANDS]
TEST: echo `hostname;uname -r`
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS 登录

无觅相关文章插件,快速提升流量