summaryrefslogtreecommitdiff
path: root/kpov_judge/tasks/copy_rename_20_files_tail_env/task.py
blob: 504d102c94f558514d6c25d321577c0724d5df96 (plain)
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# kpov_random_helpers should be imported by add_assignment.py

# TODO (polz): 
instructions = {
    'si':u"""
Prijavi se na sistem kot uporabnik student z geslom vaje.
V domači mapi najdeš imenik {file_rename_dirname} z 20 datotekami.
  - Preimenuj vse datoteke tako, da zamenjaš minuse s podčrtaji
  - Napiši čim krajši ukaz v bash, ki vse datoteke iz imenika {mv_src_dir}
    podanega imenika premakne v imenik {mv_dst_dir}. Spravi ga v 
    /home/student/mv_ukaz. Pazi, da bodo ob testiranju v izvornem imeniku iste
    datoteke, kot so bile, ko je bila virtualka nova, ciljni imenik pa bo prazen.
  - Napiši ukaz, ki s pomočjo ukaza grep v datoteko ~/mama.txt izpiše vse
    navadne (ne skrite) datoteke v trenutnem imeniku, ki vsebujejo niz "mama",
    v datoteko ~/napake.txt pa izpiše vse morebitne napake (npr. to, da so nekateri
    objekti v trenutnem imeniku dejansko imeniki ali napačne simbolične povezave).
    Ukaz spravite v datoteko /home/student/mama_ukaz.
  - Napiši program (lahko v bash), ki bo 5s sledil vsebini /var/log/syslog. V
    primeru, da se v syslogu pojavi niz "zmeda", naj program izpiše "imam ga".
    Poleg tega naj program med sledenjem syslog-u odšteva od 5 do 1 (vsako sekundo
    naj se izpiše naslednja številka. Program naj bo v /home/student/syslog_ukaz.sh
  - Namesti paket "cowsay" in ga preizkusi :)
  - Nastavi okoljsko spremenljivko TEST, da bo imela isto vrednost kot okoljska
    spremenljivka USER + število okoljskih spremenljivk, ki v imenu ali
vrednosti ne vsebujejo besede TEST. Primer: polz37
  - S pomočjo programa cURL preštej število pojavitev niza "images" v html kodi, 
    ki jo dobiš na naslovu http://localhost/{curl_fname} na malishell in število zapiši 
    v spremenljivko $images na simpleArbiter v lupini, kjer poganjaš 
    task_check.py
  - V imeniku {wc_dirname} najdeš datoteko count.txt. Preštej število vrstic v njej
    in rezultat zapiši v novo datoteko lines.txt v istem imeniku.
""",
	'en':u"""
Log into the system as student using vaje as your password.
In your home folder you will find a directory called {file_rename_dirname} 
    containing 20 files.
  - Rename all files in that directory replacing all dashes with
    underscores
  - Find the shortest command for copying all the files located in
    {mv_src_dir} into the folder {mv_dst_dir}. 
    Create a shell script /home/student/mv_ukaz containing this commant
  - Specify the shortest command which will, using the grep command, 
    write all normal (not hidden) files containing a string "mama" located 
    in working directory (pwd) into the file ~/mama.txt while writing errors such as
    files in current directory being folders or symbolic links in the file called
    "napake.txt"
  - Write a program (which may be a shell script) that will track the contents 
    of /var/log/syslog for 5s. Every time an entry containing the string "zmeda"
    appears in the syslog, in syslog, the script should output "imam ga". 
    In addition, the script should count down from 5 to 1 with a 1 second
    interval. Store the script in /home/student/syslog_ukaz.sh .     	
  - Install the packet "cowsay" and test it :)
  - Set the variable TEST, which will have the same value as the 
    variable USER + the number of variables which do not include the name 
    TEST, for example polz37.
  - With the help of cURL count the number of "images" string occurences in the
    page accessible from malishell at http://localhost/{curl_fname}.
    On simpleArbiter within the shell where you are running test_task.py, set
    the environment variable $images to this number.
  - In the directory {wc_dirname} there is a file called count.txt. Write the
    number of lines in this file into a file in the same directory.
"""
} 

computers = {
    'malishell': {
        'disks': [
            {   'name': 'malishell',
            },
            #{   'name': 'CDROM',
            #    'options':{'readonly': True},
            #    'parts': [],# no parts, no mounting.
            #}
        ],
        'network_interfaces': [{'network': 'net1'}],
        'flavor': 'm1.tiny',
        'config_drive': False

    },
    'SimpleArbiter': {
        'disks': [
            {   'name': 'simpleArbiterDhcp',
                # attempt automount
            },
            #{   'name': 'CDROM',
            #    'options': {'readonly': True},
            #    'parts': [{'dev': 'b1', 'path': '/cdrom'}],
            #},
        ],
        'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}],
        'flavor': 'm1.tiny',
        'config_drive': False
    }
}

networks = { 'net1': {'public': False}, 'test-net': {'public': True} }

params_meta = {
    'IP_malishell': {'descriptions': {'si': 'Naslov malishell'}, 'w': True, 'public':True, 'type': 'IP', 'generated': False},
    'file_creator_random_seed': {'descriptions': {'si': 'random file creator seed'}, 'w': False, 'public':False, 'type': None, 'generated': True},
    'file_rename_dirname': {'descriptions': {'si': 'imenik z datotekami, ki naj se jih preimenuje'}, 'w': False, 'public':True, 'type': 'dirname', 'generated': True},
    'mv_src_dir': {'descriptions': {'si': 'imenik, iz katerega premakni datoteke'}, 'w': False, 'public':True, 'type': 'dirname', 'generated': True},
    'mv_dst_dir': {'descriptions': {'si': 'imenik, v katerega premakni datoteke'}, 'w': False, 'public':True, 'type': 'dirname', 'generated': True},
    'cowsay_string': {'descriptions': {'si': 'Kaj rece krava?'}, 'w': False, 'public':True, 'type': 'short', 'generated': True},
    'syslog_n_zmeda': {'descriptions': {'si': 'st. zapisov zmeda v 5s'}, 'w': False, 'public':True, 'type': 'uint', 'generated': True},
}

def task(IP_malishell, file_rename_dirname, mv_src_dir, mv_dst_dir, cowsay_string):
    import pxssh
    # TODO: (polz) this has to be changed! Get a move on!
    #
    # sv: Z primozem lavricem sva skusala nekaj narediti    
    # Ker gen params ni narejen, sklepam da je "Mapa" na namizju,
    # imena datotek pa so: 1,1-,2,2-,3,3-,4,5,6,7,8,9,.mama1,mama2,mama3,mama4,mama5,mojimenik,novi,oce1
    # v mojimenik se nahaja mojimenikfile
    # mama2 vsebuje "mama"
    #Stirje subt-aski dodani.By Mihec.
    results = dict()
    conn = pxssh.pxssh()
    conn.login(IP_malishell, 'student', 'vaje')
    # preimenuj datoteke
    conn.sendline('/bin/ls -a1 {}'.format(file_rename_dirname))
    conn.prompt()
    results['preimenuj'] = conn.before
    # premakni datoteke s cim krajsim ukazom
    conn.sendline('/bin/ls -a1 {}'.format(mv_src_dir))
    conn.prompt()
    results['pre_mv_src'] = conn.before
    conn.sendline('/bin/ls -a1 {}'.format(mv_dst_dir))
    conn.prompt()
    results['pre_mv_dst'] = conn.before
    conn.sendline('/bin/ls -l ~/mv_ukaz')
    conn.prompt()
    results['mv_ls_size'] = conn.before
    conn.sendline('. ~/mv_ukaz')
    conn.prompt()
    conn.sendline('/bin/ls -a1 {}'.format(mv_src_dir))
    conn.prompt()
    results['post_mv_src'] = conn.before
    conn.sendline('/bin/ls -a1 {}'.format(mv_dst_dir))
    conn.prompt()
    results['post_mv_dst'] = conn.before
    # mama_ukaz
    # 
    conn.sendline('cd /home/student/grep_test_dir')
    conn.prompt()
    conn.sendline('. ~/mama_ukaz')
    conn.prompt()
    conn.sendline('cat ~/napake.txt')
    conn.prompt()
    results['grep_napake'] = conn.before
    conn.sendline('cat ~/mama.txt')
    conn.prompt()
    results['grep_mama'] = conn.before
    # sledenje syslog
    conn.sendline('date')
    conn.prompt()
    conn.sendline('/usr/local/bin/syslog_spammer &')
    conn.prompt()
    results['syslog_start_time'] = conn.before
    conn.sendline('/home/student/syslog_ukaz.sh')
    conn.prompt()
    results['syslog_result'] = conn.before
    conn.sendline('date')
    conn.prompt()
    results['syslog_end_time'] = conn.before
    conn.sendline('cowsay "{}"'.format(cowsay_string))
    conn.prompt()
    results['cowsay'] = conn.before
    conn.logout()
    #results['curl'] = subprocess.check_output(["cat","/home/student/Desktop/website.txt"])

    #results['chkimages'] = subprocess.check_output(["curl www.24ur.com >> dlg.txt && cat dlg.txt | grep -c ","images"])

    #results['count'] = subprocess.check_output(["wc","/home/student/Desktop/count.txt"])

    #results['lines'] = subprocess.check_output(["cat","/home/student/Desktop/lines.txt"])

    #results['cowsay'] = subprocess.check_output(["dpkg --get-selections | grep","cowsay"])

    #results['phttp'] = subprocess.check_output(["lsof -i  ",":8080"])
    return results
    
def gen_params(user_id, params_meta):
    import random
    import subprocess
    params = dict()
    homedir = '/home/student/'
    r = random.Random(user_id)
    params['file_creator_random_seed'] = str(r.random())
    params['file_rename_dirname'] = homedir + kpov_random_helpers.default_generators['dirname'](r)
    params['mv_src_dir'] = homedir + "".join([r.choice("abcdefgh") for i in xrange(6)])
    params['mv_dst_dir'] = homedir + "".join([r.choice("ijklmnop") for i in xrange(6)])
    params['syslog_n_zmeda'] = str(r.randint(5, 15))
    params['cowsay_string'] = kpov_random_helpers.default_generators['short_text'](r)
    #params['phttp'] = "8080"
    #params['images'] = subprocess.check_output(["echo","$images"])
    return params

def task_check(results, params):
    import re
    import random
    score = 0
    r = random.Random(params['file_creator_random_seed'])
    fnames = []
    for i in xrange(20):
        fnames.append("".join([ r.choice("_abcdefghijk") for j in xrange(8)]))
    #TO FINISH SCORING WE REQUIRE DICT KEYS AND FUNCTIONS gen_params AND task TO BE FINISHED
    #POINTS FOR EACH TASK MAY BE ADJUSTED IN THE FUTURE
    #TASK 1
    # print( results['preimenuj'])
    lines = results['preimenuj'].split("\n")
    task1_ok = len(lines) == len(fnames) + 4
    task1_ok = task1_ok and lines[0].find(params['file_rename_dirname']) >= 0
    task1_ok = task1_ok and lines[1].strip() == "."
    task1_ok = task1_ok and lines[2].strip() == ".."
    # print task1_ok
    for fname in fnames:
        # print task1_ok, fname, results['preimenuj'].find(fname)
        task1_ok = task1_ok and results['preimenuj'].find(fname) > 0
    if task1_ok:
        score += 2
    # premakni datoteke s cim krajsim ukazom
    fnames = []
    for i in xrange(40):
        fnames.append("".join([ r.choice("123456789abcdefghijk") for j in xrange(8)]))
    task2_re = re.search(
        r"-rw[x-][r-][w-][x-][r-][w-][x-] \d* student student (\d*) .*mv_ukaz",
        results['mv_ls_size'])
    mv_ls_size = int(task2_re.group(1))
    task2_ok = mv_ls_size < 15 and mv_ls_size > 2
    pre_src = set([i.strip() for i in results['pre_mv_src'].split('\n')[3:-1]])
    pre_dst = set([i.strip() for i in results['pre_mv_dst'].split('\n')[3:-1]])
    task2_ok = task2_ok and pre_src == set(fnames)
    task2_ok = task2_ok and len(pre_dst) < 2
    post_src = set([i.strip() for i in results['post_mv_src'].split('\n')[3:-1]])
    post_dst = set([i.strip() for i in results['post_mv_dst'].split('\n')[3:-1]])
    task2_ok = task2_ok and post_dst == set(fnames)
    task2_ok = task2_ok and len(post_src) < 2
    if task2_ok:
        score += 2
    # mama_ukaz
    # 
    task3_ok = True
    mama_fnames = []
    for i in xrange(20):
        mama_fnames.append("".join([ r.choice("123456789abcdefghijk") for j in xrange(8)]))
    papa_fnames = []
    for i in xrange(20):
        papa_fnames.append("".join([ r.choice("123456789abcdefghijk") for j in xrange(8)]))
    dirnames = []
    for i in xrange(20):
        dirnames.append("".join([ r.choice("123456789abcdefghijk") for j in xrange(8)]))
    linknames = []
    for i in xrange(20):
        linknames.append("".join([ r.choice("123456789abcdefghijk") for j in xrange(8)]))
    print( results['grep_mama'])
    print( results['grep_napake'])
    for i in dirnames + linknames + papa_fnames:
        if (i not in papa_fnames) and results['grep_napake'].find(i) < 0:
            task3_ok = False
        if results['grep_mama'].find(i) >= 0:
            task3_ok = False
    for i in papa_fnames:
        if results['grep_napake'].find(i) >= 0:
            task3_ok = False
        if results['grep_mama'].find(i) >= 0:
            task3_ok = False
    for i in mama_fnames:
        if results['grep_mama'].find(i) < 0:
            task3_ok = False
    if task3_ok:
        score += 2
    # sledenje syslog
    print( results['syslog_start_time'])
    print( results['syslog_result'])
    print( results['syslog_end_time'])
    return score

def prepare_disks(templates, params):
#    d = templates['simpleArbiterDhcp']
    import random
    print "Haha!"
    print params
    print templates
    d = templates['malishell']
    r = random.Random(params['file_creator_random_seed'])
    # rename
    d.mkdir(params['file_rename_dirname'])
    d.chown("student", "student", params['file_rename_dirname'])
    for i in xrange(20):
        fname = params['file_rename_dirname'] + '/' + "".join(
            [r.choice("-abcdefghijk") for j in xrange(8)])
        d.touch(fname)
        d.chown("student", "student", fname)
    # mv ukaz
    d.mkdir(params['mv_src_dir'])
    d.chown("student", "student", params['mv_src_dir'])
    for i in xrange(40):
        fname = params['mv_src_dir'] + '/' +"".join(
            [r.choice("123456789abcdefghijk") for j in xrange(8)])
        d.touch(fname)
        d.chown("student", "student", fname)
    d.mkdir(params['mv_dst_dir'])
    d.chown("student", 'student', params['mv_dst_dir'])
    # grep mama
    # mama fnames
    d.mkdir('/home/student/grep_test_dir')
    for i in xrange(20):
        d.write("/home/student/grep_test_dir/" + "".join(
            [ r.choice("123456789abcdefghijk") for j in xrange(8)]),
            "mama")
    # papa fnames
    for i in xrange(20):
        d.write("/home/student/grep_test_dir/" + "".join(
            [ r.choice("123456789abcdefghijk") for j in xrange(8)]),
            "papa")
    # dirnames
    for i in xrange(20):
        d.mkdir("/home/student/grep_test_dir/" + "".join(
            [ r.choice("123456789abcdefghijk") for j in xrange(8)]))
    # linknames
    for i in xrange(20):
        d.ln_sf("mali zeleni", "/home/student/grep_test_dir/" + "".join(
            [ r.choice("123456789abcdefghijk") for j in xrange(8)]))
    # sledenje syslog
    spammer_source = "#!/bin/sh\n" + int(params['syslog_n_zmeda']) * "logger zmeda\n"
    d.write("/usr/local/bin/syslog_spammer", spammer_source)
    d.chmod("0775", "/usr/local/bin/syslog_spammer")