Você está na página 1de 3

UNIX WORKSHEET

/bin/sh Old Stuff Shell


/bin/bash Bourne Again Shell BASH
Help : 1) man 2) info 3) - -help 4)apropos
1) man command 2) info command
3) command --help 4) apropos argument
Frequently Used Commands:
1) cat cat filename : shows content of file
2) cd change direction
3) ls list directory contents
4) file file filename gives info bout file
5) logout exit
6) passwd passwd username changes it
tail -x filename shows last x lines
head -x filename shows first x lines
more filename & less filename
Short Keys:
Control + A Goes to the beginning.
Control + C Terminates a running program.
Control + D Terminates the shell.
Control + E Opposite of first.
Control + H Backspace.
Control + L Clears the screen.
.bash_history previously used commands
Shift + Page Up Scroll Up
Shift + Page Down Scroll Down
Special Characters:
1) \ Delimiter for special characters.
2) / Directory character.
3) . (In front of a filename)hidden file
(./) Current directory.
4) .. Parent directory
5) ~ home directory
6) * any combinations of characters. (cat a*)
7) ? any single character (cat a?? or cat a?)
8) [ ] range of values or chars (cat a[b-c]a
b-c means margin & b,c means or
Pipes : Week 3 Comments:
1) more more filename
2) less less filename
3) head head filename
4) tail tail filename
5) wc -l : counts lines -c : counts bytes
-m : counts chars -w : counts words
6) mkdir mkdir directoryname
mkdir -p creates parental directories
mkdir -v tells every successful events
-pv or -p -v can also be used.
7) rmdir rmdir directoryname
8) touch creates an empty file
touch path/filename
9) cp copy from file
cp filename path/cpiedfilename
if no cpiedfilename : old name will be used.
cp -r directory directory cps dir to dir
Note: ls -la lists with details.
10) rm deletes a file (no trashcan)
Warning : sudo rm -r / deletes everything
rm -r filename recursively delets insides
11) mv moves files (just like copy)
mv filename filename can be used.
Ownership/Permissions:
r read , w write, x execute
u user, g group, o thers, a all
+ adding , - remaining
1) chown chown username filename
2) chmod chmod [ugoa] [+,-] [r|w|x] f.name
ls example : -(dir) rw-(own) rw-(grp) r--(oth)
ls real app: -rw-rw-r-chmod example :
chmod u+xw, u-r, g-xw, o-xwr, g+r filename
echo string >> filename wrts str into file
Directories:
x : enter a directory
r : read the contens of a directory
w : write into a directory
nano filename same as gedit
1) adduser 2) groupadd 3) usermod adm rhts
sudo su to get the super user skills
groupadd name
sudo usermod -a -G name username
groups username
another program
^v
STDIN my program (>>) STDOUT
ID=0
v (>>)
ID = 1
STDERR
ID =2
1) Redirection : program and file(s) <, >
2) Piping : program and program |
Example:
ls 1 > myresult.txt prints ls to the file
ls >> filename append
cat filename > filename cpies to newfile
wc -l filename > filename cnts lines and
sends the results to a file.
2> filename sends error to file
rmdir -v name name nonexistantname >
filename 2> filename
rmdir -v name name nonexistantname >
output.txt 2> &1 prints err into same file.
rmdir -v name name nonexistantname 2>
output.txt 1>&2 prints err into same file.
Wc -l < output.txt prints the count of the lines
in the file on STDIN
wc -l < output.txt > newout.txt redirects the
output to another file.
Program1 | program2 output is sent to another
program
ls | head -3 prints the first 3 lines of ls
ls | head -7 | rail -3 prints the last 3 lines of
heads first 7 lines.
Ls | head -7 | tail -3 > final.txt prints the
results to the file

grep string filename prints the lines that


contains the string (search method)
ls -l | grep string search in ls
sort filename sorts the file
sort filename > filename writes the sotred
lines on a file
sort < filename redirection
Bash Programming :
-scipts filename.sh .which bash this
command tells you the bash you are using.
Bash Example 1:
#!/bin/bash
MYSTRING=Hello World
echo $MYSTRING prints the string
function hello {
local MYSTRING=local variable
echo $MYSTRING
}
echo $MYSTRING Hello World
hello local variable
echo $MYSTRING Hello World
Alternative:
function hello {
local echo exit
}
echo
hello program stops after that line
echo...
Bash Example 2:
#!/bin/bash
if [ foo != hello ]; then
echo TRUE
else
echo FALSE
fi output : FALSE
Bash Example 3:
#!/bin/bash
VAR1 = foo
VAR2 = hello
VAR3 = car
if[ $VAR1 != $VAR2 ]; then
echo TRUE
else if [ $VAR1 != $VAR3 ]; then
echo OK
else
echo FALSE
fi
Error?
Bash Example 4:
#!/bin/bash
for i in $(ls); do
echo item: $i
done
for each item ls returns,
prints them on screen. When
ls -l is used, writes
everything in lines.
For i in $(ln -l | wc -w); do
echo item: $i
done
output : number of words
in ls command.
Seq num num writes a sequence of
numbers from num1 to num2
Bash Example 4:
#!/bin/bash
COUNTER=0
while[ $COUNTER -lt 10 ]; do
echo Hello $COUNTER
let COUNTER=COUNTER+1
done
output : Cntr 0 -9
Bash Example 5:
#!/bin/bash
COUNTER=7
until[ $COUNTER -lt 3 ] do
echo COUNTER $COUNTER
let COUNTER= COUNTER-1
done
output: counter from 7-3
Bash Example 6:
#!/bin/bash
function hello {
echo $1 first parameter
} (echo $2, $3)
hello 5 pass a parameter
(hello 5 8 89)
output : 5
output: (5,8,89)
Bash Example 7:
#!/bin/bash
OPTION=Hello Quit these are your optios
select opt in $OPTIONS; do
if[ $opt=Quit ]; then
echo Done
exit
elif[ $opt=Hello ]; then
echo Hello World
else
clear
echo Bad Option!
fi
done
Bash scripts can be used from terminal
without a .sh file.
Bash Example 8:
#!/bin/bash
if [ -z $1 ]; then -z checks if any prmtrs
echo Usage: $0 filename whn no pm
exit
fi
cat $1
cats the file if is a parameter
Bash Example 9:
#!/bin/bash
echo Please enter your name and surname
read NAME SURNAME equal to scanf
echo Hi $NAME $SURNAME
( echo Hi $NAME $SURNAME also works)
echo 1+1

echo $[4*$VAR+17]

echo $((1+1)) prints 2


echo $[1+1] prints 2
VAR = 21
echo $[45/$VAR+17]
bc bash calculator
Bash Example 10:
#!bin/bash
MYARRAY=(Debian Linux Redhat Linux
Ubuntu Linuz)
MYELEMENTS= ${#ARRAY[@]}
echo $MYELEMENTS
for((i=0; i<$MYELEMENTS; i++)); do
echo ${MYARRAY[${i}]}
done
Topic: Bash Scripting Special Characters
# ` @ . , ; : \ { } [ ] [[]] * =
Bash Example 11:
#!/bin/bash
cat a.txt
#this is a comment!
Echo oooo # is not a comment bc in str envir
echo oooo \# bbbb output: aaaa # bbbb
echo oooo # bbbb now it is a comment!
Echo oooo; cp a.txt b.txt single line can add
if[0]; then
(then) could also be here instead previous
echo Hi
else
echo There!
and are same
fi
for i in 4 5 6 7 8 9; do
*seq prods seqs
echo number: $i
*seq 4 9
done
for i in `seq 4 9`; do
echo number: $i
done
while[1]; do
echo hello
done
: NOP means no opeation, rets true
while :
do
echo hello
done
if[1]; then
: No operation(void)
else
echo bbbb
fi
if[ ]; then
:
else
echo bbbb
fi
Tar Commands:
tar cvjf ttt.tar.bz2 ttt filename.txt
high compression but less speed
tar xvf ttt.tar Decompresses the file
tar xzf ttt.tar.gz
tar xjf ttt.tar.bz2
tar tf ttt.tar lists the content
tar xf ttt.tar ttt/directoryname/filename
ln -s ttt.tar my-soft-link
tar xf my-soft-link ttt/directoryname/filename
ls -l | grep \->
readlink linkname reads wh inside link
ln -s fullpath/ttt.tar my-soft-link.tar
creates a soft link
ln ttt.tar my-soft-link.tar creates a hardlink
Bash Example 12:
#!/bin/bash
if [ -e aaa.txt ]; then
echo YES
else
echo NO
fi
( -s : if the file size is not 0
-f : if the file is a regular file
-d : checks directories
-e : checks if file exists
-p : file is pipe or not
-h : checks if its a link or not
-r : checks if it has read permission )
var1 = 11
var2 = 13
if [ $var1 -eq $var2 ]; then

fi
( -eq : is used integer comparison (look below)
-lt : less than
-le : less than or equal
-gt : greater than
-ge : greater than or equal
-eq : equal )
echo * is named wildcard for file names, as
special character called asterisk. It gets all file
names existant.
Echo work???ce output: workspace
$ is used for constant substituion
= dont put whitespaces before and after =
var1 = how
var1are = hello
var2 = you
var3 = $ {var1} are $ var2 =${} is used for
parameter substitution.
Echo aaa{bb,9,eee}fff={} used for expansion
output : aaabbffff aaa9fffff aaaeeefffff
i ie yaplsa bile sadece 1 expansion varm
gibi gzkecek.
File = aaa.txt
{
read line1
read line2
} < $file
redirection, sending a file
inside of curly brackets.
Echo $line1

echo $line2

*{} is used for code blocks

read areline < aaaa.txt


read anotherline < aaaa.txt just reads firstln
echo $areline
echo $anotherline
{
echo hello
echo world
} >> aaa.txt
appends hello and worrld
into aaa.txt
cat aaa.txt
myvar = helloworld!
{
read temp1
read temp2
} <<< $myvar
echo $temp1
echo $temp2
output: helloworld!

\documentclass[allpaper,11pt]{article}
\usepackage
\author{Ula Keskindikkl}
\title{Comp 217 lel}
\begin{document}
\maketitle
\tableofcontents
\section {bla bla}
...
\subsection{la la}
\begin{enumerate}
\item ...yaz \item yaz
\end{enumerate}
\end{document}

Special Things:
\begin {enumerate} sigma k=0 to 5 : k^2+1
\item yaz $$\sum{k=0}^{5} k^2+1 $$
\end {enumerate}
$ $ is called a mathematical node
$$ $$ makes it graphically nice.
Repository : GIT, CVS, SVN
Subversive:
[ ] (whtespace) are void for test
sudo apt-get update
if [ -e ooo.txt ]; then
sudo apt-get install subversion
echo Yes
svn version
else
svn mkdir -m Hello this is my first project
echo No
svn://repo.yasar/myproject username=student
fi
( [ ] nothing if your command returns nothing, svn checkout svnpath/myproject
username=student takes the file out on your
then it is false, otherwise it is true.
own computer.
[ ] [ ] true [ : ]
/s -/ myproject/
blankspace character )
svn status
var = or var =
svn add a a makes it ready to be send to sever
if [ $var ]; then
svn commit -m This is our first commit!
echo Yes
Yuppy!...
else
svn diff
echo No
svn commit -m / added a new line
fi
svn status - -show updates username=student
Larry Wall Shell Programming is a 1950a
Quiz Answers:
juke box...
[ -f checks if it is a usual file
1) ? : could not solve the problem.
[ -e checks if a file exists
2) #!/bin/bash
[ -a same but no longer used
diff -r file1 file2 > report.txt
Agenda:
1) tar c,x,f,v,j,t,z
3) [], [[]] str compars 3)#!/bin/bash
stat -c %a ege/ege.txt > accessrights.txt
2) ln
4) (()) Clike code and art cp
5) ssh into
6) scp intro
IFS=$\n
tar cvf c : stands for create
for i in cat accessrights.txt; do echo $i; done
v: successful
f: filename
chmod $i ege/ege.txt
ttt.tar name of the .tar file to be created
stat -c %a ege/ege.txt
ttt name of the folder to be archived.
4) #!/bin/bash
Example : tar cvf ttt.tar ttt
tar cvfz ttt.tar.gz ttt ( -z means compress GZIP , OPTION=STATUS COMMIT UPDATE DIFF
GUNZIP algorithm -really fast) EXIT
Bash Example 13:
select opt in $OPTION; do
var1 = hello
if [$opt = STATUS ]; then
var2 = mello
if [ $var1 == $var2 ]; then == : str cmps echo Status is modified.

!= \< (alphbtc) \> (put dlmtr)


elif[ $opt = COMMIT ]; then
fi
echo Now you can commit your project
1) ssh secure shell = Desktop sharing
elif[ $opt = UPDATE ]; then
2) scp secure copy
echo Updating your project
3) svn repository
elif [ $opt = DIFF]; then
4) (())
echo Diff
client
server
else
[ virtual ] ssh [ ubuntu ]
clear echo Escaped exit
[ opensuse]
[ box ]
fi
[ box ]

[
]
done
^ install ssh service.
Sudo apt-get install ssh
BASIC COMMAND GUIDE
sudo apt-get install open-ssh-server
ls --- lists your files
sudo service ssh start
ls -l --- lists your files in 'long format',
fconfig learn ip(server)
ls -a --- lists all files,
ping ip
emacs filename --- is an editor that lets you
ssh compare@ip
logout
create and edit a file. See the emacs page.
mv filename1 filename2 --- moves a file (i.e.
scp filename username@ip:parh)client
gives it a different name, or moves it into a
scp username@ip path/filename
different directory (see below)
newname copies it with a new name
cp filename1 filename2 --- copies a file
svn://repo.yasar.edu.tr/comp217
student: 123456
rm filename --- removes a file. It is wise to use
user: 12345
the option rm -i, which will ask you for
sudo apt-get update LATEX from TeX 80 confirmation before actually deleting anything.
sudo apt-get install texlive texlive-science
books,articles,papers,reports.. diff filename1 filename2 --- compares files,
and shows where they differ
#file (latex cmpile) #file.dvi
ps pdf msword doc rtf text
wc filename --- tells you how many lines, words,
Latex Guide:
and characters there are in a file
ged hello.tex
chmod options filename --- lets you change the
\documentclass{article}
read, write, and execute permissions on your
\begin{document}
files. . For example, chmod o+r filename will
Hello World!
make the file readable for everyone, and chmod
\end{document}
o-r filename will make it unreadable for others
latex hello.tex compile latex file
again.
ls hell*
File Compression
evince hello.dvi run file (evince commond
gzip filename --- compresses files, so that they
used for executing dvi file)
take up much less space. There are other tools for
dvips hello.dvi convert dvi file to .ps file
evince hello.ps
this purpose, too (e.g. compress), but gzip
ps2pdf hello.ps -;> convert ps to pdf
usually gives the highest compression rate.
latex hello.tex && dvips hello.dvi && ps2pdf
Gunzip filename --- uncompresses files
hello.ps && evince hello.pdf makes
compressed by gzip.
everything in just one command
gzcat filename --- lets you look at a gzipped file
dvipdf hello.dvi convert dvi to pdf
% comment line in latex
without actually having to gunzip it (same as
Example1 :
gunzip -c). You can even print it directly, using
\documentclass[allpaper,11pt] {article}
gzcat filename | lpr
\usepackage[english] {babel}
lpr filename --- print. Use the -P option to
\usepackage[utf8]{inputenc} turkish chs
specify the printer name if you want to use a
\begin{document}
Hseyin Hl
printer other than your default printer. For
\end{document}
example, if you want to print double-sided, use
Example 2:
'lpr -Pvalkyr-d', or if you're at CSLI, you may

want to use 'lpr -Pcord115-d'. See 'help printers'


for more information about printers and their
locations.
lpq --- check out the printer queue, e.g. to get
the number needed for removal, or to see how
many other files will be printed before yours
will come out
lprm jobnumber --- remove something from
the printer queue. You can find the job number
by using lpq. Theoretically you also have to
specify a printer name, but this isn't necessary
as long as you use your default printer in the
department.
genscript --- converts plain text files into
postscript for printing, and gives you some
options for formatting. Consider making an
alias like alias ecop 'genscript -2 -r \!* | lpr -h
-Pvalkyr' to print two pages on one piece of
paper.
dvips filename --- print .dvi files (i.e. files
produced by LaTeX). You can use dviselect to
print only selected pages. See the LaTeX page
for more information about how to save paper
when printing drafts.
mkdir dirname --- make a new directory
cd dirname --- change directory. You basically
'go' to another directory, and you will see the
files in that directory when you do 'ls'. You
always start out in your 'home directory', and
you can get back there by typing 'cd' without
arguments. 'cd ..' will get you one level up from
your current position. You don't have to walk
along step by step - you can make big leaps or
avoid walking around by specifying pathnames.
pwd --- tells you where you currently are.
ff --- find files anywhere on the system. This
can be extremely useful if you've forgotten in
which directory you put a file, but do remember
the name. In fact, if you use ff -p you don't
even need the full name, just the beginning.
grep string filename(s) --- looks for the string
in the files. This can be useful a lot of purposes,
named "mix" : Task 2 :Please provide the set of
commands for:
Display File Contents
mkdir
the student list, sort all and then dump to a file
dirname
and write it to another file and find out the
Display data in paginated
more: number of characters from a to e from that
file
form.
Move (Rename) a oldname to
mv answers: //task1newname.
cat names|head -10 >headsandtails
Print current working
gcc d.c -o d.out mkdir executables
cd executables ./a.out > a.txt
./b.out > b.txt ./d.out > d.txt mkdir result
compress
Compress files
mv a.txt result mv b.txt result mv d.txt result
gunzip
Uncompress gzipped files
//task3
cd ../ cd ../ grep -o free Licenses | wc -l >
GNU alternative
gzip
compression method count.txt
//task4
uncompress
Uncompress files
List, test and extract nano code1.c nano code2.c
nano code3.c
nano code4.c nano code5.c
unzip
compressed files in a ZIP
archive
rm -v code1.c code2.c code3.c code4.c code5.c
zcat
Cat a compressed file code6.c code7.c code8.c
code9.c code10.c
2>error.txt
zcmp
Compare compressed >success.txt
files
//task5
zdiff
Compare compressed files
cat names | head -5 > somelines.txt
File perusal filter for crt
cat names | tail -7 >> somelines.txt
zmore
viewing of compressed
sort somelines.txt > sortedlines.txt

text
grep [A-E] sortedlines.txt >
Executable shell : $ chmod a+rx first.sh
foundfrom_a_to_b.txt
C Programming Commandables:
grep -o [A-E] sortedlines.txt | wc -l >>
#include <stdio.h>
foundfrom_a_to_b.txt
#include <stdlib.h>
Bash Line Reading: #!/bin/bash
int input(char *s,int length);
while IFS='' read -r line || [[ -n "$line" ]]; do
int main(){
mkdir -p "./repository/$line"
char *buffer;
done < "$1"
char cmdbuf[256];
terminalden arrken "./script.sh students.txt"
size_t bufsize = 0;
Bash Repo: #!/bin/bash
ssize_t characters
while read line
FILE *p;
do
p = fopen("students.txt", "r");
mkdir -p "./repository/$line"
system("mkdir repository");
done <students.txt
while((characters =
Bash Nested:#!/bin/bash
getline(&buffer,&bufsize,p)) != -1)
while IFS='' read -r line || [[ -n "$line" ]]; do
{strcpy(cmdbuf, "mkdir ./repository/");
while IFS='' read -r line2 || [[ -n "$line2" ]]; do
strcat(cmdbuf, buffer);
mkdir -p "./repository/$line/$line2"
strcat(cmdbuf, "/");
done < "$2"
system(cmdbuf);
done < "$1"
printf("%s were read.\n", cmdbuf)}
Bash useful txt manipulations:
return(0);}
#!/bin/bash
Lab 4 - Grep, Pipes and RedireBct
Task 1: From the first labwork, find the list of
linecount=`wc -l anthem.txt`
echo Number of Line: $linecount
students and write it to a file
-List the first and last 10 entries in the file and
#!/bin/bash
wordcount=`wc -w anthem.txt`
create a new file named "first and last"
-Create a new file from the list of students that
echo Number of words:$wordcount#!/bin/bash
charcount=`wc -m anthem.txt`
has the name "ahmet"
echo Number of characters:$charcount
-Merge these two files into one single file
e.g. finding the right file among many, figuring
out which is the right version of something, and
even doing serious corpus work. grep comes in
several varieties (grep, egrep, and fgrep) and
has a lot of very flexible options. Check out the
man pages if this sounds good to you.
#!/bin/bash
bytecount=`wc -c anthem.txt`
echo Numbe r of bytes:$bytecount
#!/bin/bash
echo "Now lines of anthem.txt will be sorted
according to alphabetical order."
cat anthem.txt|grep '.'|sort>sorted.txt
echo "Sorting completed. Output has been
created as a file named sorted.txt"
#!/bin/bash
echo "Now words of anthem.txt will be sorted
according to alphabetical order."
r ' ' '\n' < anthem.txt|sort -u > sortbyword.txt
echo "Sorting completed. Output has been
created as a file named sortbyword.txt"
#!/bin/bash
echo "Now characters of anthem.txt will be
sorted according to alphabetical order."
fold -w1 anthem.txt|sort -u > sortbycharacter.txt
echo "Sorting completed. Output has been
created as a file named sortbycharacter.txt"
svn checkout/co
svn add : adds a new file to system.
svn propset : svn propset svn:keywords "Date
LastChangedBy" /path/to/filename.xml
svn delete : deletes the file
svn status : shows current status
svn update/up : updates the situation / syncs
svn commit/ci : recursively sends changes 2srv
svn diff
svn move

< sign means : do something in the next given


file like sort operations: sort < ege.txt
> sign means : redirect and create a file
contains given operations.
wc -l < barry.txt > myoutput
>> sign means: overwrite into the created file.
| sign means: pipe: this controlls multiple
commands:
ls | head -3 cat | head -10
ls | head -3 | tail -1
ls | head -3 | tail -1 > myoutput
> Save output to a file.
>> Append output to a file.
< Read input from a file.
2> Redirect error messages.
| Send the output from one program as input to
another program.
svn add filename
svn add directory
svn blame filename shw w/revs
svn blame -r RevisionNumber filename
svn cat filename
svn commit filename
svn copy source destination_clone
svn delete filename
svn diff filename
Tar examples
tar cvzf MyImages-14-09-12.tar.gz
/home/MyImages
tar cvzf MyImages-14-09-12.tgz
/home/MyImages
# tar -xvf public_html-14-09-12.tar untar
tar -xvf public_html-14-09-12.tar -C
/home/public_html/videos/
tar -xvf thumbnails-14-09-12.tar.gz uncmp
tar -xvf videos-14-09-12.tar.bz2
tar -tvf uploadprogress.tar list contents
tar -tvf staging.tecmint.com.tar.gz
tar -tvf Phpfiles-org.tar.bz2
tar --extract --file=cleanfiles.sh.tar
cleanfiles.sh untar single file
tar -rvf tecmint-14-09-12.tar xyz.txt add file
tar -czf - tecmint-14-09-12.tar | wc -c ch siz
c create a archive file.
x extract a archive file. v show the progress
of archive file. f filename of archive file. t
viewing content of archive file. j filter
archive through bzip2. z filter archive through
gzip. r append or update files or directories
toexisting archive file.
LaTeX : Text designing tool
gedit hello.tex %Comment Sign
\documentclass{article}
\begin{document}
Hello World!
\end{document}
latex hello.tex Compile the latex file.
Evince hello.dvi Runs the dvi file
dvips hello.dvi Convert dvi to ps file
evince hello.ps
ps2pdf hello.ps Convert ps to pdf file.
Dvipdf hello.dvi From dvi to pdf
\documentclass{article}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\begin{document} sadfsdfdf! \end{document}
\documentclass[a4paper, 11pt{article}
\usepackage
\author{Ege Dursun}
\title{Comp 344} \begin{document}
\maketitle \tableofcontents \section{sdfdf}
\subsection{fddsf} \end{document}
\begin{enumerate}
\item .\end{enumerate}
OPENSSL
touch number.txt
echo "123456789" > number.txt
openssl enc -base64 -in number.txt
openssl enc -base64 -in number.txt -out
encodednumber.txt
cat encodednumber.txt
touch plain.txt
echo "I love OpenSSL!" > plain.txt
openssl enc -aes-256-cbc -in plain.txt -out
encrypted.bin
openssl enc -aes-256-cbc -d -in encrypted.bin
-pass pass:123
#Generate key pair
openssl genrsa 2048
openssl genrsa -out key.pem 2048
cat key.pem
#Read the key in human readbale form.
openssl rsa -in key.pem -text -noout
#Get public associated with the private key
openssl rsa -in key.pem -pubout -out pub.pem
openssl rsa -in pub.pem -pubin -text -noout
#SKIP THIS ONE
#encrypt private key
openssl rsa -in key.pem -des3 -out enc-key.pem

#and get public key out


openssl rsa -in key.pem -pubout -out pubkey.pem
#ENCRYPT
echo "test test test" > file.txt
openssl rsautl -encrypt -inkey pub.pem -pubin -in
file.txt -out file.bin
#DECRYPT
openssl rsautl -decrypt -inkey key.pem -in
file.bin
#SIGN
#Hash the message first
openssl dgst -sha256 -out hash.txt text.txt
#Sign the hash
#openssl rsautl -sign -in <digest> -out
<signature> -inkey <key>
openssl rsautl -sign -in hash.txt -out sign.bin
-inkey key.pem
#VERIFY
#openssl rsautl -verify -in <signature> -out
<digest> -inkey <key> -pubin
openssl rsautl -verify -in sign.bin -inkey pub.pem
-pubin
openssl dgst -sha256 text.txt
#EXTRAS
openssl speed
openssl speed rsa
openssl speed rsa -multi 2
openssl s_server -cert mycert.pem -www
openssl prime 119054759245460753
openssl prime -generate -bits 64
openssl prime -generate -bits 64 -hex
# write 128 random bytes of base64-encoded
data to stdout
openssl rand -base64 128
# write 1024 bytes of binary random data to a file
openssl rand -out random-data.bin 1024
PYTHON
Python IDLE Syntactic Rules
print(String) Prints the string
name = Hello World
print(name) ** Power Sign
x = set([1,2,3,4,5]) x.add(13) x.subset(y)
x.difference(y) x.remove(13)
x.union(y) a = [1,2,3,4] a.append(a string)
a.append(set([1,2,3])) a.insert(0, string)
f = open(filename,w) w or r
f.write(string) f.close() def function(a,b)
return a+b print(function(5,3))
line=f.readline() filename.py
Detailed Python Guide
True Cross-Platform, runs equally well on
Windows, Linux and Mac. Easy to use.
Easy to learn. Lots of documentation
available. Lots of Fortran Scientific Libraries
have interfaced into Python Language.
Print(Hello World) Name = input(what is
your name?) Print(Name)
s = hello world python print s[0] Strings are
immutable objects. Strings can be surrounded
by
>>> word = Help
>>> word[:2] # The first two characters 'He'
>>> word[2:] # Everything except the first two
characters 'lp
>>> word[:2] + word[2:] # returns s >>>
word[1:100]
>>> word[10:]
>>> word[2:1]
>>> word[-1] # The last character 'A'
>>> word[-2]
>>> word[-2:] # The last two characters lp'
>>> word[:-2] # Everything except the last two
characters
x = x.y z.t k.g x.split() x.split(.)
x.replace(x, y)
A set in Python is an unordered collection of
objects, used in situations where membership and
uniqueness in the set are the main things you
need to know about that object.
>>>x = set([1,2,3,1,5,3,2,4,1])
>>>print(x)
>>>1 in x Methods of sets: issubset(), union(),
intersection(), difference(), copy(), add(),
remove(), discard()
A list can contain a mixture of other types as its
elements, including strings, tuples, lists,
dictionaries, functions, file objects, and any type
of number.
>>>[]
>>>[1]
>>>[1, 2, 3, 4, 5, 6, 7, 8, 12]
>>>[1, "two", 3L, 4.0, ["a", "b"], (5,6)]
-------------x = [first, second, third, fourth]
>>> x[0] 'first'
>>> x[2] 'third'
>>> x[-1] 'fourth'
>>> x[-2] 'third'
Some built-in functions : (len, max, and min)
(in, +, and *) the del statement the list
methods (append, count, extend, index, insert,
pop, remove, reverse, and sort) will operate on
lists.
Tuples are similar to lists but are immutable
that is, they cant be modified after they have
been created. (1, "two", 3L, 4.0, ["a", "b"], (5,
6)) Functions are: (in, +, and *) len, max,
min index, count Tuples can be converted to
lists using function list()

Key:value pairs x = {1:"a", 2:"b", 3:"c",


4:"d"} (len, del, clear, copy, get, has_key,
items, keys, update, and values)
--f = open("myfile", "w")
>>> f.write("First line with necessary newline
character\n") 44
>>> f.write("Second line to write to the file\n")
33
>>> f.close()
>>> f = open("myfile", "r")
>>> line1 = f.readline()
>>> line2 = f.readline()
>>> f.close()
>>> print(line1, line2)
--x = 5
if x < 5:
y = -1
z=5
elif x > 5:
y=1
z = 11
else:
y=0
z = 10
print(x, y, z)
--u, v, x, y = 0, 0, 100, 30
while x > y:
u=u+y
x=x-y
if x < y + 2:
v=v+x
x=0
else:
v=v+y+2
x=x-y-2
print(u, v)
--var1, var2 = 3, 5
var2, var1 = var1, var2
NOTES ON DATA SECURITY
1- Symmetric Enctyption /Asymmetric Enc.
2- Digital Signatures for learning the person
3- Certification Analysis etc.
PTHREADING PARALLEL PROGRAMMIN
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define NUM_THREADS 5
void* perform_work(void* argument){
int passed_in_value;
passed_in_value = *((int*) argument);
printf("Hello World! It's me, thread with
argument %d!\n", passed_in_value);
/* optionally: insert more useful stuff here */
return NULL;
}
int main(int argc, char** argv){
pthread_t threads[NUM_THREADS];
int thread_args[NUM_THREADS];
int result_code;
unsigned index;
//create all threads one by one
for(index = 0; index < NUM_THREADS; +
+index){
thread_args[index] = index;
printf("In main: creating thread %d\n",
index);
result_code = pthread_create(threads +
index, NULL, perform_work, thread_args +
index);
assert(!result_code);
}
// wait for each thread to complete
for(index = 0; index < NUM_THREADS; +
+index){
// block until thread 'index' completes
result_code =
pthread_join(threads[index], NULL);
assert(!result_code);
printf("In main: thread %d has
completed\n", index);
}
printf("In main: All threads completed
successfully\n");
exit( EXIT_SUCCESS);
}
----------------#!/bin/bash
# Bash Menu Script Example
PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option 3"
"Quit")
select opt in "${options[@]}"
do
case $opt in
"Option 1")
echo "you chose choice 1"
;;
"Option 2")
echo "you chose choice 2"
;;
"Option 3")
echo "you chose choice 3"
;;
"Quit")
break
;;
*) echo invalid option;;
esac
done

Você também pode gostar