From 8081a5520a441b43a8a7a73f3a90c7aacfaa8e10 Mon Sep 17 00:00:00 2001 From: Timotej Lazar Date: Sun, 24 Feb 2019 21:05:27 +0100 Subject: Move everything one level up --- .../howtos/en/index.html | 18 ++ .../howtos/si/index.html | 38 +++ .../solution/solution.py | 92 ++++++ .../solution/solution.sh | 40 +++ tasks/copy_rename_20_files_tail_env/task.py | 351 +++++++++++++++++++++ 5 files changed, 539 insertions(+) create mode 100644 tasks/copy_rename_20_files_tail_env/howtos/en/index.html create mode 100644 tasks/copy_rename_20_files_tail_env/howtos/si/index.html create mode 100644 tasks/copy_rename_20_files_tail_env/solution/solution.py create mode 100644 tasks/copy_rename_20_files_tail_env/solution/solution.sh create mode 100644 tasks/copy_rename_20_files_tail_env/task.py (limited to 'tasks/copy_rename_20_files_tail_env') diff --git a/tasks/copy_rename_20_files_tail_env/howtos/en/index.html b/tasks/copy_rename_20_files_tail_env/howtos/en/index.html new file mode 100644 index 0000000..b1008cc --- /dev/null +++ b/tasks/copy_rename_20_files_tail_env/howtos/en/index.html @@ -0,0 +1,18 @@ + + +

Purpose of this exercise

+

To learn how to use a few BASH commands.

+

Quick summary

+

You will use bash commands like: mv, grep, env etc.

+

Instructions

+ +

    +
  1. Log into your system and in your home folder you will find a directory called Mapa containing 20 files.
  2. +
  3. Rename all files, by replacing all minus signs with underscores using the command: "rename 's/-/_/' *".
  4. +
  5. Remove all files from /home/user/mapa/mojimenik into /home/user/novi using command: "mkdir-p /home/user/novi && mv /home/user/mapa/mojimenik/* /home/user/novi"
  6. +
  7. Write all regular files containing a string "mama" into file "mama.txt", and all errors in file "napake.txt" by using: "find . -type f | grep mama 1> mama.txt 2> napake.txt".
  8. +
  9. Inspect /var/log/syslog for 5 seconds and in case a string"zmeda" appears in syslog, write "imam ga". Also while inspecting syslog, reduce the counter by every second using a command: "for i in 5 4 3 2 1; do echo $i; echo $(sed -n "$i p" /var/log/syslog | grep zmeda > /dev/null && echo "imam ga"); sleep 1; done".
  10. +
  11. Set a variable TEST to the same value as the variable USER + the number of environmen variables not containing string "TEST" in their names, by adding ~/.bashrc to the end of the file: "export TEST=$USER" + "$(env | grep -v TEST | wc -l)"
  12. +

+ + diff --git a/tasks/copy_rename_20_files_tail_env/howtos/si/index.html b/tasks/copy_rename_20_files_tail_env/howtos/si/index.html new file mode 100644 index 0000000..1ce8b44 --- /dev/null +++ b/tasks/copy_rename_20_files_tail_env/howtos/si/index.html @@ -0,0 +1,38 @@ + + + + + +

Namen vaje

+

Naučite se uporabe nekaj BASH ukazov.

+

Naloga na hitro

+

Uporabljali boste BASH ukaze kot so: mv, grep, env in druge.

+

Navodila

+ +

    +
  1. Prijavite se v sistem. V domačem imeniku najdete imenik Mapa z 20 datotekami.
  2. +
  3. Preimenujete vse datoteke tako, da zamenjate minuse s podčrtaji z ukazom: "rename 's/-/_/' *".
  4. +
  5. Premaknite vse datoteke /home/user/mapa/mojimenik v /home/user/novi z ukazom: "mkdir-p /home/user/novi && mv /home/user/mapa/mojimenik/* /home/user/novi"
  6. +
  7. V datoteko "mama.txt" zapišite vse navadne datoteke v trenutnem imeniku, ki vsebujejo niz "mama", v datoteko "napake.txt" pa zapišite vse morebitne napake z ukazom: "find . -type f | grep mama 1> mama.txt 2> napake.txt".
  8. +
  9. Sledite vsebini /var/log/syslog za 5 sekund in v primeru, da se v syslogu pojavi niz "zmeda", izpišite "imam ga". Poleg tega med sledenjem syslog-u odštevajte od 5 do 1 z ukazom: "for i in 5 4 3 2 1; do echo $i; echo $(sed -n "$i p" /var/log/syslog | grep zmeda > /dev/null && echo "imam ga"); sleep 1; done".
  10. +
  11. Nastavite okoljsko spremenljivko TEST, da bo imela isto vrednost kot okoljska spremenljivka USER + število okoljskih spremenljivk, ki v imenu ali vrednosti ne vsebujejo besede TEST tako, da na koncu datoteke ~/.bashrc dodate: "export TEST=$USER" + "$(env | grep -v TEST | wc -l)"
  12. +

+ + diff --git a/tasks/copy_rename_20_files_tail_env/solution/solution.py b/tasks/copy_rename_20_files_tail_env/solution/solution.py new file mode 100644 index 0000000..f661c4d --- /dev/null +++ b/tasks/copy_rename_20_files_tail_env/solution/solution.py @@ -0,0 +1,92 @@ +# preimenuj vse datoteke tako, da zamenjaš minuse s podčrtaji +def rename(): + import os + for filename in os.listdir('.'): + os.rename(filename, filename.replace('-', '_')) + +# Napiši čim krajši ukaz, ki vse datoteke iz /home/user/mapa/mojimenik premakne v /home/user/novi +def mv_novi(): + import os + for filename in os.listdir("/home/user/mapa/mojimenik/"): + os.rename('/home/user/mapa/mojimenik/' + filename, '/home/user/novi/' + filename) + +# Napiši ukaz, ki s pomočjo ukaza grep v datoteko "mama.txt" izpiše vse navade (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) +def mama(): + import os + import re + import mmap + mama = '' + wrong = '' + for filename in os.listdir('.'): + try: + f = open(filename, 'r+') + data = mmap.mmap(f.fileno(), 0) + if re.search('mama', data): + mama = mama + filename + "\n" + except ValueError: + wrong = wrong + filename + "\n" + open('mama.txt', 'w').write(mama) + open('napake.txt', 'w').write(wrong) + +# Napiši ukaz, 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. +def checker(): + import time + import re + import mmap + t = time.time() * 1000 + n = t + + f = open('/var/log/syslog', 'r+') + data = mmap.mmap(f.fileno(), 0) + me = re.findall('zmeda', data) + + c = len(me) + for i in range(5, 0, -1): + print(i) + n += 1000 + while n > t: + f = open('/var/log/syslog', 'r+') + data = mmap.mmap(f.fileno(), 0) + me = re.findall('zmeda', data) + if len(me) > c: + c = len(me) + print('imam ga') + t = time.time() * 1000 + +# 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 +def env(): + import os + import re + c = 0 + for i in os.environ: + if not (re.search('TEST', i) or re.search('TEST', os.environ[i])): + c = c + 1 + os.environ['TEST'] = os.environ['USER'] + repr(c) + +# S pomočjo programa cURL shrani vsebino spletne strani www.google.com v datoteko z imenom website.txt +def googl(): + import urllib.request + open('website.txt', 'w').write(urllib.request.urlopen('http://www.google.com').read()) + +# Napiši ukaz, ki bo število pojavitev značke
v datoteki website.txt dodal na konec te iste datoteke brez, da bi se ukaz zapisal v zgodovino ukazov "bash history" +def div(): + import re + import mmap + f = open('website.txt', 'r+') + data = mmap.mmap(f.fileno(), 0) + me = re.findall('<[^/<>]*div[^>]*>', data) + open('website.txt', 'a+').write(repr(len(me))) + +# Napiši ukaz brez uporabe programa cron, kateri 5 minut po izvedbi izpiše vsebino imenika v katerem se trenutno nahajaš +def sleep(): + import time + import os + time.sleep(300) + print(os.listdir('.')) + +# Napiši najkrajši ukaz, ki s pomočjo Pythona zažene preprost (integriran) HTTP strežnik kateri streže datoteke iz imenika iz katerega je bil pognan na vratih 8000 +def server(): + import http.server + import socketserver + httpd = socketserver.TCPServer(("", 8000), http.server.SimpleHTTPRequestHandler) + httpd.serve_forever() diff --git a/tasks/copy_rename_20_files_tail_env/solution/solution.sh b/tasks/copy_rename_20_files_tail_env/solution/solution.sh new file mode 100644 index 0000000..b8e2d13 --- /dev/null +++ b/tasks/copy_rename_20_files_tail_env/solution/solution.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +# preimenuj vse datoteke tako, da zamenja minuse s podrtaji +rename 'y/-/_/' * + +# Napii im kraji ukaz, ki vse datoteke iz /home/user/mapa/mojimenik premakne v /home/user/novi +mv /home/user/mapa/mojimenik/* /home/user/novi/ + +# Napii ukaz, ki s pomojo ukaza grep v datoteko "mama.txt" izpie vse navade (ne skrite) datoteke v trenutnem imeniku, ki vsebujejo niz "mama", v datoteko "napake.txt" pa izpie vse morebitne napake (npr. to, da so nekateri objekti v trenutnem imeniku dejansko imeniki ali napane simboline povezave) +grep -l 'mama' * 1>mama.txt 2>napake.txt + +# Napii ukaz, ki bo 5s sledil vsebini /var/log/syslog. V primeru, da se v syslogu pojavi niz "zmeda", naj program izpie "imam ga". Poleg tega naj program med sledenjem syslog-u odteva od 5 do 1 (vsako sekundo naj se izpie naslednja tevilka. +COUNT=$(grep 'zmeda' /var/log/syslog | wc -l ); +END=$(date +%s%N | cut -b1-13); +for i in {5..1}; do + END=$(($END + 1000)); + echo "$i"; + while [ $(date +%s%N | cut -b1-13) -lt $END ]; do + COUN1=$(grep 'zmeda' /var/log/syslog | wc -l ); + if [ $COUN1 -gt $COUNT ]; then + echo "imam ga"; + COUNT=$COUN1; + fi + done +done + +# 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 +TEST="$USER$(printenv | grep -v TEST | wc -l)"; export TEST + +# S pomojo programa cURL shrani vsebino spletne strani www.google.com v datoteko z imenom website.txt +curl http://www.google.com > website.txt + +# Napii ukaz, ki bo tevilo pojavitev znake
v datoteki website.txt dodal na konec te iste datoteke brez, da bi se ukaz zapisal v zgodovino ukazov "bash history" +grep -o "<[^/<>]*div[^>]*>" website.txt | wc -l >> website.txt; history -d $((HISTCMD-1)) + +# Napii ukaz brez uporabe programa cron, kateri 5 minut po izvedbi izpie vsebino imenika v katerem se trenutno nahaja +$(sleep 300; ls) & + +# Napii najkraji ukaz, ki s pomojo Pythona zaene preprost (integriran) HTTP strenik kateri stree datoteke iz imenika iz katerega je bil pognan na vratih 8000 +python -m SimpleHTTPServer \ No newline at end of file diff --git a/tasks/copy_rename_20_files_tail_env/task.py b/tasks/copy_rename_20_files_tail_env/task.py new file mode 100644 index 0000000..ce51c9c --- /dev/null +++ b/tasks/copy_rename_20_files_tail_env/task.py @@ -0,0 +1,351 @@ +# kpov_util should be imported by add_assignment.py + +instructions = { + 'si': '''\ +

+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 najkrajši ukaz v bash, ki vse datoteke iz imenika {{mv_src_dir}} premakne v imenik {{mv_dst_dir}}. Ukaz spravi v /home/student/mv_ukaz. Pazite, da bodo ob testiranju v izvornem imeniku iste datoteke, kot so bile, ko je bila virtualka nova, ciljni imenik pa bo prazen. To pomeni, da boste verjetno morali po vsakem testiranju datoteke premakniti nazaj. Za krajšanje ukaza lahko izkoristite imeni imenikov. + +

+Napiši ukaz, ki s pomočjo ukaza grep v datoteko ~/mama.txt izpiše imena vseh navadnih (ne skritih) datotek 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 pet sekund 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. 😊 + +

+S pomočjo programa curl preštej število pojavitev niza images v spletni strani, ki jo dobiš na naslovu http://localhost/{{curl_fname}} na malishell in število zapiši v spremenljivko $images na simpleArbiterDhcpGW v lupini, kjer poganjaš task_check.py. + +

+V imeniku {{wc_dirname}} najdeš datoteko count.txt. Preštej število prehodov v novo vrstico v count.txt in rezultat zapiši v novo datoteko lines.txt v istem imeniku. +''', + 'en': '''\ +

+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 command. Before running test_task.py, make sure {{mv_src_dir}} contains the same files as when you downloaded your virtual disk. This probably means that you will have to move the files back from {{mv_dst_dir}} to {{mv_src_dir}} after each test. + +

+Come up with a command or sequence of commands in bash which will, using grep, write the names all normal (not hidden) files which contain the string mama and are located in the 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 this command to /home/student/mama_ukaz. + +

+Write a program (which may be a shell script) that will track the contents of /var/log/syslog for five seconds. Every time an entry containing the string zmeda appears in the syslog, the script should output imam ga. In addition, the script should count down from 5 to 1 with a one-second interval. Store the script in /home/student/syslog_ukaz.sh. + +

+Install the package cowsay and test it. 😊 + +

+Using the curl command count the number of occurences of the string images on the web page accessible from malishell at http://localhost/{{curl_fname}}. On simpleArbiterDhcpGW 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 newlines in this file into the file lines.txt 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 + + }, + 'SimpleArbiterDhcpGW': { + 'disks': [ + { 'name': 'simpleArbiterDhcpGW', + # attempt automount + }, + #{ 'name': 'CDROM', + # 'options': {'readonly': True}, + # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], + #}, + ], + 'network_interfaces': [{'network': 'test-net'}, {'network': 'net1'}], + '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}, + 'curl_fname': {'descriptions': {'si': 'ime datoteke, dostopne prek http'}, 'w': False, 'public':True, 'type': 'filename', 'generated': True}, + 'curl_n_images': {'descriptions': {'si': 'n pojavitev niza images'}, 'w': False, 'public':False, 'type': 'integer', 'generated': True}, + 'wc_dirname': {'descriptions': {'si': 'imenik, v katerem je datoteka count.txt'}, 'w': False, 'public':True, 'type': 'dirname', 'generated': True}, + 'wc_n_lines': {'descriptions': {'si': 'n vrstic v count.txt'}, 'w': False, 'public':False, 'type': 'integer', 'generated': True}, +} + +def task(IP_malishell, file_rename_dirname, mv_src_dir, mv_dst_dir, cowsay_string, curl_fname, wc_dirname): + import collections + import os + + # TOD: (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 = kpov_util.ssh_test(IP_malishell, 'student', 'vaje', ( + ('preimenuj', '/bin/ls -a1 {}'.format(file_rename_dirname)), + ('pre_mv_src', '/bin/ls -a1 {}'.format(mv_src_dir)), + ('pre_mv_dst', '/bin/ls -a1 {}'.format(mv_dst_dir)), + ('mv_ls_size', '/bin/ls -l ~/mv_ukaz'), + (None, '. ~/mv_ukaz'), + ('post_mv_src', '/bin/ls -a1 {}'.format(mv_src_dir)), + ('post_mv_dst', '/bin/ls -a1 {}'.format(mv_dst_dir)), + + # mama_ukaz + (None, 'cd /home/student/grep_test_dir'), + (None, '. ~/mama_ukaz'), + ('grep_napake', 'cat ~/napake.txt'), + ('grep_mama', 'cat ~/mama.txt'), + + # sledenje syslog + (None, 'date'), + ('syslog_start_time', '/usr/local/bin/syslog_spammer &'), + ('syslog_result', '/home/student/syslog_ukaz.sh'), + ('syslog_end_time', 'date'), + + ('cowsay', 'cowsay "{}"'.format(cowsay_string)), + ('wc_origfile', 'cat {}/count.txt'.format(wc_dirname)), + ('wc_lines', 'cat {}/lines.txt'.format(wc_dirname)), + )) + + try: + results['curl_env'] = os.environ['images'] + except: + results['curl_env'] = '' + + #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"]) + + 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_util.default_generators['dirname'](r) + params['mv_src_dir'] = homedir + "".join([r.choice("abcdefgh") for i in range(6)]) + params['mv_dst_dir'] = homedir + "".join([r.choice("ijklmnop") for i in range(6)]) + params['syslog_n_zmeda'] = str(r.randint(5, 15)) + params['cowsay_string'] = kpov_util.default_generators['short_text'](r) + params['curl_fname'] = kpov_util.default_generators['filename'](r) + params['curl_n_images'] = str(r.randint(30,100)) + params['wc_dirname'] = homedir + "".join([r.choice("rstuvxz") for i in range(8)]) + params['wc_n_lines'] = str(r.randint(200, 600)) + #params['images'] = subprocess.check_output(["echo","$images"]) + return params + +def task_check(results, params): + import re + import random + score = 0 + hints = [] + r = random.Random(params['file_creator_random_seed']) + fnames = [] + for i in range(20): + fnames.append("".join([ r.choice("_abcdefghijk") for j in range(8)])) + #TO FINISH SCORING WE REQUIRE DICT KEYS AND FUNCTIONS gen_params AND task TO BE FINISHED + + # preimenuj 1 + task1_ok = True + for fname in fnames: + task1_ok = task1_ok and results['preimenuj'].find(fname) > 0 + if task1_ok: + score += 2 + else: + hints += ["wrong dash rename"] + + # premakni datoteke s cim krajsim ukazom + fnames = [] + try: + for i in range(40): + fnames.append("".join([ r.choice("123456789abcdefghijk") for j in range(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 <= 17 and mv_ls_size > 2 + except: + task2_ok = False + if task2_ok: + score += 1 + else: + hints += ["wrong mv_command size or owner"] + + # rename files + pre_src = set([i.strip() for i in results['pre_mv_src'].splitlines()[2:]]) + pre_dst = set([i.strip() for i in results['pre_mv_dst'].splitlines()[2:]]) + print(set(fnames)) + print(pre_src) + task2_ok = task2_ok and pre_src == set(fnames) + task2_ok = task2_ok and len(pre_dst) < 3 + post_src = set([i.strip() for i in results['post_mv_src'].splitlines()[2:]]) + post_dst = set([i.strip() for i in results['post_mv_dst'].splitlines()[2:]]) + task2_ok = task2_ok and post_dst == set(fnames) + task2_ok = task2_ok and len(post_src) < 3 + if task2_ok: + score += 1 + else: + hints += ["wrong rename files"] + + # mama_ukaz + task3_ok = True + mama_fnames = [] + for i in range(20): + mama_fnames.append("".join([ r.choice("123456789abcdefghijk") for j in range(8)])) + papa_fnames = [] + for i in range(20): + papa_fnames.append("".join([ r.choice("123456789abcdefghijk") for j in range(8)])) + dirnames = [] + for i in range(20): + dirnames.append("".join([ r.choice("123456789abcdefghijk") for j in range(8)])) + linknames = [] + for i in range(20): + linknames.append("".join([ r.choice("123456789abcdefghijk") for j in range(8)])) + 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 + else: + hints += ["mama cries"] + + # sledenje syslog + #print( results['syslog_start_time']) + #print( results['syslog_result']) + #print( results['syslog_end_time']) + # syslog count + # TODO: check syslog + task4_ok = True + if task4_ok: + score += 1 + else: + hints += ["wrong syslog count"] + + task5_ok = True + try: + assert int(results['curl_env'].strip()) == int(params['curl_n_images']) + except: + task5_ok = False + if task5_ok: + score += 2 + else: + hints += ["wrong image count"] + task6_ok = True + try: + assert int(results['wc_lines'].strip()) == int(params['wc_n_lines']) + except: + task6_ok = False + if task6_ok: + score += 1 + else: + hints += ["wrong line count"] + return score, hints + +def prepare_disks(templates, task_params, global_params): + import random + d = templates['malishell'] + r = random.Random(task_params['file_creator_random_seed']) + # rename + d.mkdir(task_params['file_rename_dirname']) + d.chown(1000, 1000, task_params['file_rename_dirname']) + for i in range(20): + fname = task_params['file_rename_dirname'] + '/' + "".join( + [r.choice("-abcdefghijk") for j in range(8)]) + d.touch(fname) + d.chown(1000, 1000, fname) + # mv ukaz + d.mkdir(task_params['mv_src_dir']) + d.chown(1000, 1000, task_params['mv_src_dir']) + for i in range(40): + fname = task_params['mv_src_dir'] + '/' +"".join( + [r.choice("123456789abcdefghijk") for j in range(8)]) + d.touch(fname) + d.chown(1000, 1000, fname) + d.mkdir(task_params['mv_dst_dir']) + d.chown(1000, 1000, task_params['mv_dst_dir']) + # grep mama + # mama fnames + d.mkdir('/home/student/grep_test_dir') + for i in range(20): + d.write("/home/student/grep_test_dir/" + "".join( + [ r.choice("123456789abcdefghijk") for j in range(8)]), + "mama") + # papa fnames + for i in range(20): + d.write("/home/student/grep_test_dir/" + "".join( + [ r.choice("123456789abcdefghijk") for j in range(8)]), + "papa") + # dirnames + for i in range(20): + d.mkdir("/home/student/grep_test_dir/" + "".join( + [ r.choice("123456789abcdefghijk") for j in range(8)])) + # linknames + for i in range(20): + d.ln_sf("mali zeleni", "/home/student/grep_test_dir/" + "".join( + [ r.choice("123456789abcdefghijk") for j in range(8)])) + # sledenje syslog + spammer_source = "#!/bin/sh\n" + int(task_params['syslog_n_zmeda']) * "logger zmeda\n" + d.write("/usr/local/bin/syslog_spammer", spammer_source) + d.chmod(0o775, "/usr/local/bin/syslog_spammer") + # curl + l1 = ['images'] * int(task_params['curl_n_images']) + l2 = ['imeges'] * r.randint(30, 100) + lx = l1 + l2 + r.shuffle(lx) + d.write("/var/www/html/{}".format(task_params['curl_fname']), ''.join(lx)) + # wc + lx = ['\n']*int(task_params['wc_n_lines']) + lx += ['a', 'b', 'c', 'repa', 'in', 'krompir', + 'raus', 'e', 'patacis'] * r.randint(50, 150) + r.shuffle(lx) + d.mkdir(task_params['wc_dirname']) + d.chown(1000, 1000, task_params['wc_dirname']) + d.write("{}".format(os.path.join(task_params['wc_dirname'], 'count.txt')), "".join(lx)) + + write_default_config(templates['simpleArbiterDhcpGW'], global_params) -- cgit v1.2.1