User:Ptomusk

From ICO wiki
Revision as of 11:27, 10 January 2014 by Ptomusk (talk | contribs) (→‎Python)
Jump to navigationJump to search

Info

Erinevate ainete raames lisatud sisu

Skriptimiskeeled (I387)

Tunnis lahendatud näited

Teine

  1. Teha skript, mis küsib kasutajalt kataloogi nime ja siis väljastab kõik (tavalised) failid/kaustad, mis seal kataloogis asuvad 3p

Ptomusk 14:29, 29 September 2013 (EEST)

#!/bin/bash
_short_help="`basename $0` [DIRECTORY]"
_long_help="Output the files in the specified directory"
if [ "$1" = '--help' ]; then
        echo $_short_help
        echo $_long_help
        exit 0
elif [ -d "$1" ]; then
	find "$1/" -maxdepth 1 -type f
else
	echo "No such directory!"
	echo $_short_help
	exit 1
fi

Link originaalpostitusele: Bash_quests_2013#Teine

Quest 30

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Luua isikukoodi parser ja õigsuse kontroll.
#Sisendiks fail kus igal real on isikukood, mis võib olla õige või vale.
#Väljundiks on fail kus on õiged isikukoodid kus kontrollsumma klapib ning kuupäev on korrektne (aastas 12 kuud ning iga kuu päevade arv sobiv).
#
#NB! Kuupäeva õigsuse kontrollimiseks kasutage datetime.strptime funktsiooni ja uuesti vormindamiseks datetime.strftime funktsiooni
#
#Autor: Peeter Tomusk

#Useful sources
#Isikukoodi spetsifikatsiooni (tasuta) kirjeldus - http://et.wikipedia.org/wiki/Isikukood

##Import modules
import sys
import os
from string import rstrip
import time
#from calendar import isleap

##Some initial variables
helpmessage="Usage: %s [input_file_name] [[--debug]]" % sys.argv[0]
helplongmessage="""

Test the validity of Estonian ID-codes in a file and print properly formatted lines with the birth-date and gender on screen
"""
debug=False
input_file=""
seed={1:(1,2,3,4,5,6,7,8,9,1),2:(3,4,5,6,7,8,9,1,2,3)}

##Parse arguments
#Check that we have arguments
if len(sys.argv)==1:
	sys.stderr.write("Invalid number of arguments!\n\n%s\n" % helpmessage)
	sys.exit(4)
#Loop trough all arguments except the first one (scripts own name)
while len(sys.argv[1:])>0:
	#If the argument is help
	if sys.argv[1]=="--help":
		print helpmessage+helplongmessage
		sys.exit(0)
	#If the argument is debug
	if sys.argv[1]=="--debug":
		debug=True
		del sys.argv[1]
	#In other cases presume it's a filename 
	else:
		#Test if we already have a filename
		if len(input_file)>0:
			sys.stderr.write("Input file \"%s\" is already specified and filename \"%s\" is one too many\ncurrently only one file is supported, sorry!\n" % (input_file,sys.argv[1]))
			sys.exit(2)
		#Test if the file exists
		elif os.path.isfile(sys.argv[1]):
			input_file=sys.argv[1]
			del sys.argv[1]
		#If the doesn't exists
		else:
			sys.stderr.write("Input file \"%s\" doesn't exist!\n" % sys.argv[1])
			sys.exit(1)

##Do some actual work
#Test if we can read the file
if os.access(input_file,os.R_OK):
	#and read it's contents to a list
	f=open(input_file,"r")
	input_data=f.readlines()
	f.close 
#Or give an error
else:
	sys.stderr.write("Cannot read file \"%s\"\n" % input_file)
	sys.exit(3)

#For each line in the file
for code in input_data:
	code=rstrip(code,"\n")
	#Find the gender
	if int(code[0])%2==0:
		gender="naine"
	elif int(code[0])%2==1:
		gender="mees"
	#Find the appropriate number of hundreds for the birthyear
	cents=18+(((int(code[0])%2)+int(code[0]))/3)
	#Check if the date is a proper value
	try:
		birthdate=time.strftime("%Y.%m.%d",time.strptime("%s%s.%s.%s" % (cents,code[1:3],code[3:5],code[5:7]),"%Y.%m.%d"))
	except ValueError as error:
		if debug:
			print "%s is wrong, because %s" % (code,error)
		continue
	#Verify the code against it's checksum
	for seed_type in 1,2:
		#Initialise a variable for the seed multiplication sums
		codesum=0
		#For each non-checksum element in the code
		for index in range(10):
			#Multiply it with the current seed and add the result
			codesum=codesum+(seed[seed_type][index]*int(code[index]))
		#Calculate the checksum
		checksum=codesum%11
		#If checksum is 10
		if checksum==10:
			if seed_type==1:
				continue
			elif seed_type==2:
				checksum=0
		#If the checksum is not 10 and matches the original
		if checksum!=10 and checksum==int(code[-1]):
			print "%s - %s - %s" % (code,birthdate,gender)
			break
	else:
		if debug:
			print "%s is wrong, because the checksum is wrong" % code


BASH

Kodune töö
#!/usr/bin/env bash
# Looge skript, mis looks uue veebkodu Kasutaja sisestab: 'loo-kodu www.minuveebisait.ee'
# Skript paigaldab apache2 serveri, kui see puudub
# Loob nimelahenduse (lihtsalt /etc/hosts failis)
# Kopeerib vaikimisi veebisaidi ja modifitseerib index.html faili sisu vastavalt loodavale lehele
#
# Autor: Peeter Tomusk
# Modifikatsioonid: skript kasutab Nginx veebiserverit ning paigaldab ka php toe

#Baseline variables
_document_root="/srv/www"
_install_packages=""
_nginx_package_name="nginx"
_php_package_name="php5-fpm"
_index_file_name="index.html"

#Functions
function f_error(){
	_message="$1"
	_exit_status="$2"
	echo $_message 1>&2
	exit $_exit_status
}

function f_name_resolution(){
	_website_name="$2"
	case $1 in
		add)
			echo -e "127.0.0.1\t$_website_name" >> /etc/hosts
			;;
		remove)
			cat /etc/hosts | grep -v $_website_name > /etc/hosts.new && rm /etc/hosts && mv /etc/hosts.new /etc/hosts
			;;
		check)
			grep $_website_name /etc/hosts 2>&1 > /dev/null
			if [ $? -eq 0 ];then
				true
			else
				false
			fi
			;;
	esac
}

#Parse input
if [ $UID -ne 0 ];then
	f_error "This script must be run as root, please use sudo!" 1
elif [ -n "$1" ] && [ -z "$2" ];then
	if [ "$1" = '--help' ];then
		echo "`basename $0` [name-of-the-vhost-to-create]"
		exit 0
	else
		if [ -d "$1" ];then
			f_error "The desired directory $_document_root/$1 already exists!" 3
		elif f_name_resolution "check" $1;then
			f_error "The desired DNS alias already exists!" 4
		elif [ -d /etc/nginx/sites-enabled ] && [ `grep root /etc/nginx/sites-enabled/* | grep "$1"` ];then
			f_error "The desired vhost \"$1\" already exists!" 5
		fi
	fi
else
	f_error "Wrong number of parameters!" 2
fi

#Assing parameters to variables
_website_name="$1"

#Check for the required packages
echo "-- Checking the environment --"
for _package in $_nginx_package_name $_php_package_name;do
echo -n "$_package: "
	if [ -n "`dpkg -l | grep ^ii | grep \"$_package\"`" ];then
		echo "Found"
	else
		echo "To be installed"
		_install_packages="$_package $_install_packages"
	fi
done
#If needed perform software installation and configuration
if [ -n "$_install_packages" ];then
	echo "Installing packages"
	apt-get install -y $_install_packages 2>&1 >> /tmp/$$_install.log
	if [ $? -eq 0 ];then
		echo "Success!" && rm /tmp/$$_install.log
	else
		cat /tmp/$$_install.log && rm /tmp/$$_install.log
		f_error "Package installation failed!" 6
	fi
	#If we're installing nginx for the first time, de-configure the default vhost and create the desired document root
	if [ -e /etc/nginx/sites-enabled/default ];then
		rm /etc/nginx/sites-enabled/default
	fi
	if [ ! -d $_document_root ];then
		mkdir $_document_root
	fi
	#Restart nginx to make sure it's up to speed
	service nginx restart
fi

#Setup the actual website
echo "-- Configuring the website --"
#Create document-root
echo "Creating the document-root directory"
mkdir $_document_root/$_website_name
if [ $? -ne 0 ];then
	f_error "Failed to create the target directory $_document_root/$_website_name" 7
fi
#Create the index file
echo "Creating the default index file"
echo -e '<!DOCTYPE html>\n<html>\n<head>\n\t<title>'$_website_name'</title>\n\t<meta charset="utf-8">\n</head>\n<body>\n\t<h3>Teretulemast '$_website_name' kodulehele!</h3>\n</body>\n</html>' > $_document_root/$_website_name/$_index_file_name
if [ $? -ne 0 ];then
	f_error "Failed to create the default index file $_document_root/$_website_name/$_index_file_name" 8
fi
#Create the vhost
echo "Creating the vhost configuration"
echo -e "server {\n\tserver_name $_website_name;\n\troot $_document_root/$_website_name/;\n\tindex $_index_file_name;\n" > /etc/nginx/sites-available/$_website_name
echo -e "\t"'location ~ \.php$ {'"\n\t\t"'fastcgi_split_path_info ^(.+\.php)(/.+)$;'"\n\t\t"'fastcgi_pass 127.0.0.1:9000;'"\n\t\t"'fastcgi_index index.php;'"\n\t\t"'include fastcgi_params;' >> /etc/nginx/sites-available/$_website_name
echo -e "\t\t}\n}" >> /etc/nginx/sites-available/$_website_name
if [ $? -ne 0 ];then
	f_error "Failed to create the vhost file" 9
fi
ln -s /etc/nginx/sites-available/$_website_name /etc/nginx/sites-enabled/$_website_name
if [ $? -ne 0 ];then
	f_error "Failed to enable the vhost" 10
fi
#Add name resolution
echo "Adding name resolution"
f_name_resolution "add" $_website_name
if [ $? -ne 0 ];then
	f_error "Failed to add name resolution for $_website_name" 11
fi
#Reload nginx
echo "Reloading nginx configuration"
service nginx reload
if [ $? -ne 0 ];then
	f_error "Failed to reload nginx configuration" 12
fi
#If the script didn't die on any errors, tell the user we were successful
echo "-- Website creation is complete! --"
Vigade parandus
Real 117 peaks 'fastcgi_pass 127.0.0.1:9000;' asemel olema 'fastcgi_pass unix:/var/run/php5-fpm.sock;'
Arvestus 30.nov kaugõpe
#!/usr/bin/env bash
#Arvestus 30.nov kaugõpe
#
#Teha skript, mis loeb käsurealt 1..n argumenti (1..n IP aadressi)
#Kui argumente pole siis väljastab veakoodi 1 (1p)
#Skript väljastab eraldi real kõik käsurea argumendid. 2p
#Skript kontrollib, kas argumentidena antud IP aadresse saab pingida. 
#
#Aadressid, mis vastavad tuleb kirjutada faili ok.txt ja need, mis ei vast kirjuta faili nok.txt
#Kui faile pole, siis väljastada teade, et vastav X.txt fail puudub, loon faili(d). 2p
#Failide omanikuks tuleb seada student ja grupiks audio 1p
#
#Skript seab failiõigused selliselt, et omanik saab lugeda ja kirjutada, grupp saab lugeda ja kirjutada, teised kasutajad ei saa midagi teha 1p
#
#Faili ok.txt kirjutamine 4p
#Faili nok.txt kirjutamine 4p
#
#Autor: Peeter Tomusk

#Baseline variables
_default_ping_amount=3
_target_hosts=""

#Parse input
while [ $# -gt 0 ];do
	case $1 in
		--help)
			echo "`basename $0` [ip-aadress] [[ip-aadress2] ... [ip-aadressN]]"
			exit 0
			;;
		*)
			_target_hosts="$1 $_target_hosts"
			shift
			;;
	esac
done

#Test for input
if [ -n "$_target_hosts" ];then
	#Test for output files
	for _file in ok.txt nok.txt;do
		if [ -f $_file ];then
			continue
		else
			echo "Ei leia faili $_file - loon selle ise."
			touch $_file
			chown student:audio $_file
			chmod 660 $_file
		fi
	done
	#Perform the check for each host and put the result to the appropriate file
	for _host in $_target_hosts;do
		echo $_host
		ping -c $_default_ping_amount $_host 2>&1 >/dev/null
		if [ $? -eq 0 ];then
			echo $_host >> ok.txt
		else
			echo $_host >> nok.txt
		fi
	done
#Or give error
else
	echo "Sihtaadresse pole!"
	exit 1
fi

Python

Kodune töö