forked from razeone/devops-lectures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinux101.Rmd
More file actions
executable file
·2572 lines (1859 loc) · 63.9 KB
/
linux101.Rmd
File metadata and controls
executable file
·2572 lines (1859 loc) · 63.9 KB
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Linux101"
author: "Jorge Raze"
date: "5 de septiembre de 2017"
output: slidy_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
# Inducción a BEEVA
# Introduction
## DevOps
DevOps es un acrónimo inglés de development (desarrollo) y operations (operaciones), que se refiere a una cultura o movimiento centrado en la comunicación, colaboración e integración entre desarrolladores de software y los profesionales en las tecnologías de la información (IT). Automatiza el proceso de entrega del software y los cambios en la infraestructura. Su objetivo es ayudar a crear un entorno donde la construcción, prueba y lanzamiento de un software pueda ser más rápido y con mayor fiabilidad.
Las empresas con entregas (releases) muy frecuentes podrían requerir conocimientos de DevOps. Flickr desarrolló un sistema DevOps para cumplir un requisito de negocio de diez despliegues al día. A este tipo de sistemas se les conoce como despliegue continuo (continuous deployment) o entrega continua (continuous delivery), y suelen estar asociados a metodologías lean startup. Grupos de trabajo, asociaciones profesionales y blogs usan el término desde 2009.
[Fuente](https://es.wikipedia.org/wiki/DevOps)
## DevOps

## Mapa

# Introduction to Linux Server
## Linux
GNU/Linux, es el término empleado para referirse a la combinación del sistema operativo GNU, desarrollado por la FSF, y el núcleo(kernel) Linux, desarrollado por Linus Torvalds y la Linux Foundation. Su desarrollo es uno de los ejemplos más prominentes de software libre; todo su código fuente puede ser utilizado, modificado y redistribuido libremente por cualquiera bajo los términos de la GPL (Licencia Pública General de GNU) y otra serie de licencias libres.
[Fuente](https://es.wikipedia.org/wiki/GNU/Linux)
## Components of a Linux System
* The Linux Kernel
* The GNU utilities
* A graphical desktop environment (not always)
* Application software
## Kernel responsabilities
* System memory management
* Software program management
* Hardware management
* Filesystem management
## The Linux system memory map

## Filesystems
* ext
* ext2
* ext3
* ext4
* NFS
* NTFS
## Core GNU Utilities
* Handling files
* Manipulating text
* Managing processes
## The Shell
```
#
$
```
* zsh
* korn
* tcsh
* ash
## On the Desktop
* The X Window system
* KDE
* GNOME
* Unity
* LXDE
* XFCE
## Distributions
* Debian/Ubuntu/Mint
* Red Hat/Fedora/CentOS
* SUSE/OpenSUSE
* Slackware
* Arch
* Knopix
* Gentoo
## Back to the Shell
Linux displays by default a console terminal if the graphical interface is not set in the boot sequence.
You can access to the virtual consoles by using `Ctrl+Alt+F1` to `F7`
TTY: Short for TeleTYpewriter
## Consoles
```
setterm --inversescreen on
```
* Final Term
* Eterm
* Konsole
* UXTerm
* xterm
* Terminator
# Basic Shell Commands
## Starting the Shell
Prompt
```
raze@linuxserver01:~$
root@linuxserver01:~#
```
## Man pages
```
man command
```
* Name
* Synopsis
* Configuration
* Description
* Options
* Exit Status
* Return Value
* Errors
* Environment
* Files
* Versions
## Navigating the filesystem
```
cd /home
cd
cd ~
pwd
cd /var/log
cd ../../
```
## Common Linux Directory Names
```
/ Root of the virtual directory, no files
/bin Binary directory, many GNU utilities stored
/boot Boot directory, boot files
/dev device directory, where Linux creates device nodes
/etc system configuration files directory
/home Home directory, where user's dirs are created
/lib Library directory, system and application library files
/media media directory, a common place for mount points (removable media)
/mnt mount directory, another common place for mount points
/opt optional directory, often used to store third party software packages
/proc process dir, current hardware and process information
/root root home directory
/sbin system binary
/run run dir, runtime data
/srv service dir, where local services store their files
/sys system dir, system hardware information files are stored
/tmp temporary dir, where temporary work files can be created
/usr user binary directory
/var variable directory, files that change frequently, logs for example
```
## Listing files
```
ls
ls -la
ls -a
# Distinguish files of directories
ls -F
# recursive
ls -F -R
# wildcards
? # one character
* # any number of characters
```
## Interacting with directories and files
```
touch my_file
ls -l my_file
touch .
cp my_file my_file_copy
ls -l my_file*
# move to rename
mv my_file original_file
rm my_file*
mv original_file ../my_file
```
## More on directories
```
mkdir my_dir
touch my_dir/file
mkdir parent_dir
cp -R my_dir parent_dir
rm -R my_dir
mv parent_dir/my_dir ./backup
```
## Linking files
There are two types of links in the Linux filesystems:
* Symbolic link
* A hard link
```
touch data_file
ln -s data_file linked_file
ls -l *_file
ls -i *_file
# Hard link
ln data_file hard_linked_file
```
## Viewing files
```
tree parent_dir
cat data_file
file data_file
# adds numbers
cat -n another.file
# numbers the lines with content
cat -b another.file
# supress tabs
cat -T another.file
```
## More on viewing files
```
more data_file
less data_file
head data_file
```
## Viewing logs
```
tail -f log_file
tail -n 2 log_file
```
## Monitoring programs
```
ps
# check a particular proces
ps aux | grep java
# for other linux/**ux
ps -efa | grep process
```
## Real time monitoring
```
top
```
## Stopping processes

One does not simply kill -9
```
Ctrl+C
kill -15 pid
kill -SIGTERM pid
killall http*
```
## Monitoring memory
```
free -m
top
```
## Monitoring Disk Space
```
df -h
du -sh /*
```
## Users
```
cat /etc/passwd
who
whoami
```
## Debian based Package System
APT is a set of core tools found inside the Debian operating system. It provides utilities for the installation and removal of software packages and dependencies on a system.
`apt-get` is the high level command line tool to manage packages on a debian based system. Some options:
`apt-cache` provides an interface to perform read-only operations on the APT package cache.
`dpkg` low level package manager for Debian
## `apt-get`
Some options
* `install` and `--reinstall`
* `remove`
* `purge` or `--purge`
* `upgrade`
* `update`
* `clean` and `autoclean`
## Managing packages
```
sudo apt-get install [package-name]
sudo apt-get remove [package-name]
# uninstall with its configuration files
sudo apt-get purge [package-name]
# update package index
sudo apt-get update
# install updates
sudo apt-get upgrade -y
# If you want to force reinstall a package
sudo apt-get --reinstall install
```
## APT cache files
Cache files are located in:
* `/var/cache/apt/archives/`
```
# cleans the apt cache
sudo apt-get clean
# remove useless files from the apt cache
sudo apt-get autoclean
```
## List all available packages
```
apt-cache pkgnames
apt-cache pkgnames | more
```
## Searching for a specific debian package
```
apt-cache search "ufw"
```
## Show debian package information
```
apt-cache show vim
```
## `dpkg`
Install a package
```
dpkg -i [debian-package_amd64.deb]
dpkg --install [debian-package_amd64.deb]
```
## Remove a package
```
dpkg --remove [package-name]
dpkg -r [package-name]
# remove with its configuration files
dpkg --purge [package-name]
```
## List available system packages
```
dpkg -l [package-name-pattern]
```
## List files in a package
```
dpkg -L [package-name]
dpkg --contents [debian-package_i386.deb]
```
## Show package information
```
dpkg -s [package-name]
```
## More info
```
man apt-get
man apt
man apt-cache
man dpkg
```
## Users
```
useradd newuser
passwd newuser
groupadd newgroup
usermod newuser -G newgroup
useradd newuser1 -G newgroup
su newuser
id
```
## Red Hat Package Manager
rpm is to dpkg as yum is to apt-get.
```
# install
rpm -i [rpm-package.rpm]
# with progress bar
rpm -ivh [rpm-package.rpm]
# debug mode
rpm -ivvvh mode
# uninstall
rpm -e [package-name]
# upgrade
rpm -U [package-name.rpm]
# list all installed packages
rpm -qa | grep foo
```
## Yellowdog Update Manager
```
yum help
yum list available
yum list installed
yum info [package-name]
yum search [package-name]
yum grouplist
yum repolist
yum install [package-name]
yum update
yum remove [package-name]
```
[More info](https://access.redhat.com/articles/yum-cheat-sheet)
## The Linux Text Editors
* Vi
* Vim
* Nano
* Gedit
* Emacs
* Pico
* ...
## Vi
The default editor that comes with the UNIX operating system is called vi (visual editor).
```
vi file
```
Shortcuts
```
G - Go to the end of a file
$ - Go to the end of a line
j - Key down
k - Key up
l - Key right
h - Key left
x - remove current character
i - Interactive mode / Insert before cursor
dd - delete current line
a - interactive mode plus one space / Insert after cursor
r - replace character
R - replace many characters
w - move to the next word
0 - move to the begining of a line
```
## Use Streams
A Linux shell, such as Bash, receives input and sends output as sequences or streams of
characters. Each character is independent of the one before it and the one after it. The characters
are not organized into structured records or fixed-size blocks. Streams are accessed using file
IO techniques, whether or not the actual stream of characters comes from or goes to a file, a
keyboard, a window on a display, or some other IO device. Linux shells use three standard I/O
streams, each of which is associated with a well-known file descriptor:
* `stdout` is the standard output stream, which displays output from commands. It has file descriptor 1.
* `stderr` is the standard error strream, which dsplays error output from commands. It has file descriptor 2.
* `stdin` is the standard input stream, which provides input to programs. It has file descriptor 0.
## Streams

## Redirects
There are two ways of redirect output to a file:
```
n>
```
Redirects output from file descriptor n to a file. You must have write authority to the file. If the file doesn't exist, it is created. If it does exist, the existing contents are usually lost without any warning.
```
n>>
```
Also redirects output from file descriptor n to a file. Again, you must have write authority to the file. If the file doesn't exist, it is created. If it does exist, the output is appended to the end of the file.
## Avoid ovwerwritting with noclobber
```
set -o noclobber
```
## Redirecting two streams to one file
```
ls an* az* &> output.txt
ls an* az* > output.txt 2>&1
```
## Ignoring output with /dev/null
```
ls an* az* > output.txt 2>/dev/null
```
## Input redirection
```
echo -e "1 apple\n2 pear\n3 banana" > text1
tr ' ' '\t'<text1
```
## Input redirection with a here-document
```
sort <<END
hello
abc
cba
bac
END
```
Another example
```
cat > out.txt <<EOF
This
is
a
very
long
text
EOF
```
## Piping with |
Input can come from parameters you supply to commands, and output can be displayed on your terminal. Many text processing commands (filters) can take input either from the standard input stream or from a file. To use the output of a command, command1, as input to a filter, command2, you connect the commands using the pipe operator (|). Listing 1 shows how to pipe the output of echo to sort a small list of words.
```
echo -e "apple\npear\nbanana"|sort
ps -A | more
dmesg | head -3 | tail -1
ls | head -3 | tail -1 > myoutput
ls -l /etc | tail -n +2 | sort
```
## Grep
grep basically searches. More precisely,
```
grep foo file
cat > file <<EOF
big
bad bug
bag
bigger
boogy
EOF
```
returns all the lines that contain a string matching the expression "foo" in the file "file".
## Wildcards and Escape
* `.` matches exactly one character
* `.*` matches with any string
```
grep "b.*g" file
grep "b.*g." file
grep "ggg*" file
```
Be careful with `*`, it means repetition, not a wildcard as you use it in Unix/POSIX. It matches zero or more times. The pattern `g*` matches the string "", "g", "gg", etc. Likewise, `gg*` matches "g", "gg", "ggg", so "ggg*" matches "gg", "ggg", "gggg", etc.
## Regexp
Escaping characters
```
# escape characters
grep 'hello\.gif' file
```
The ? character
```
# zero or more appearences of that character
bugg\?y
```
An expression surrounded by "escaped" parentheses is treated by a single character.
```
Fred\(eric\)\? Smith
```
Matching a list of characters
```
# matches with Hello and hello
[Hh]ello
```
[0-3] is equals to [0123]
[a-k] is equals to [abcdefghijk]
[A-Ca-k] is equals to [ABCabcdefghijk]
Other ways
[[:alpha:]] is the same as [a-zA-Z]
[[:upper:]] is the same as [A-Z]
[[:lower:]] is the same as [a-z]
[[:digit:]] is the same as [0-9]
[[:alnum:]] is the same as [0-9a-zA-Z]
[[:space:]] matches any white space including tabs
If you want to NOT-MATCH, then add ^ as the first character inside the square brackets.
[Source](https://www.panix.com/~elflord/unix/grep.html)
## Cut
The cut command in UNIX is a command line utility for cutting sections from each line of files and writing the result to standard output.
-b = byte position
```
echo 'baz' | cut -b 2
echo 'baz' | cut -b 1-2
echo 'baz' | cut -b 1,3
```
-c = character
```
echo '♣foobar' | cut -c 1,6
echo '♣foobar' | cut -c 1-3
```
-d = delimiter
Supose you have a file called names.csv:
```
John,Smith,34,London
Arthur,Evans,21,Newport
George,Jones,32,Truro
```
Then we can:
```
cut -d ',' -f 1 names.csv
cut -d ',' -f 1,4 names.csv
```
[Source](https://shapeshed.com/unix-cut/)
Further reading on Cut:
[10 Practical Linux Cut Command Examples to Select File Columns](http://www.thegeekstuff.com/2013/06/cut-command-examples)
[Linux cut command](https://www.computerhope.com/unix/ucut.htm)
# Linux System Management
## Quotas
In order to control the disk space used in the Linux filesystem, we must use quota, which
enables us to control the disk space and thus helps us resolve low disk space issues to a
great extent. For this, we have to enable user and group quotas on the Linux system.
In CentOS 7, the user and group quotas are not enabled by default so we have to enable
them first.
To check whether quota is enabled or noot, we issue the following command:
```
mount | grep ' / '
```
Look for `noquota`
In order to enable quotas, we need to:
* Edit `/etc/default/grub` and add `rootflags=usrquota,grpquota` to `GRUB_CMDLINE_LINUX`
* Backup the GRUB file
* Rebuild GRUB with `grub2-mkconfig -o /boot/grub2/grub.cfg`
* Reboot
* Verify that quota is enabled
```
vi /etc/default/grub
cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.original
grub2-mkconfig -o /boot/grub2/grub.cfg
reboot
mount | grep ' / '
```
Then install quota:
```
yum -y install quota
quotacheck -avugm
repquota -as
```
Then edit a user's or group's quota:
```
edquota -u username
edquota -g groupname
```
## Sudoers
```
/etc/sudoers
visudo
```
## Architecture Topics

## Managing Files in Linux
```
mv
rm
rmdir
touch
cp
```
## Finding Files In Linux
```
# which command am I using
which
# Find files with .err extension
find /home/username/ -name "*.err"
# Level 3 Optimization; -L follow symlinks, with .html extension
find -O3 -L /var/www/ -name "*.html"
# Find an empty file within the current directory
find . -type f -empty
# Find all .db files (ignoring text case) modified in the last 7 days by a user named exampleuser.
find /home -user exampleuser -mtime 7 -iname ".db"
```
## More ond Find
Optimization levels and other params.
```
Command Description
-O1 (Default) filter based on file name first.
-O2 File name first, then file-type.
-O3 Allow find to automatically re-order the search based on efficient use of resources and likelihood. of success
-maxdepth X Search current directory as well as all sub-directories X levels deep.
-iname Search without regard for text case.
-not Return only results that do not match the test case.
-type f Search for files.
-type d Search for directories.
```
## Other tricks and tips
```
find / -name "*conf" -mtime 7
find /home/exampleuser/ -name "*conf" -mtime 3
```
The first command returns a list of all files in the entire file system that end with the characters conf and have been modified in the last 7 days. The second command filters exampleuser user’s home directory for files with names that end with the characters conf and have been modified in the previous 3 days.
```
find . -type f -exec grep "example" '{}' \; -print
```
This searches every object in the current directory hierarchy (.) that is a file (-type f) and then runs the command grep "example" for every file that satisfies the conditions. The files that match are printed on the screen (-print). The curly braces ({}) are a placeholder for the find match results. The {} are enclosed in single quotes (') to avoid handing grep a malformed file name. The -exec command is terminated with a semicolon (;), which should be escaped (\;) to avoid interpretation by the shell.
```
find . -name "rc.conf" -exec chmod w+r '{}' \;
```
This filters every object in the current hierarchy (.) for files named rc.conf and runs the chmod o+r command to modify file permissions of the find results.
The commands run with the -exec are executed in the root directory of the find process. Use -execdir to execute the specified command in the directory where the match resides. This may alleviate security concerns and produce more desirable performance for some operations.
The -exec or -execdir options run without further prompts. If you prefer to be prompted before action is taken, replace -exec with -ok or -execdir with -okdir.
Find and delete with find.
```
find . -name "*.bak" -delete
```
[More Info](https://explainshell.com/explain/1/find)
Related commands:
```
locate
whereis
which
```
locate is useful for finding files when you don’t know exactly what they will be called, or where
they are stored.
## Control mounting and unmounting of filesystems
```
# Listing available devices
lsblk
# Mount /dev/sda3 into /dos
mount /dev/sda3 /dos
# Mounting with explicit filesystem
mount -t vfat /dev/sda3 /dos
# Remounting read only
mount -o remount,ro /dos
# Show mounting points
cat /etc/fstab
# Umounting
umount /dos
# Displaying swap space
swapon -s
# Other ways of displaying disks/partitions
sudo fdisk -l
# Show partitions
fdisk /dev/sda
p
# Create new partition
fdisk /dev/sda
n
w
# Create filesystem
mkfs -t ext4 /dev/sda1
# Mount it
mount /dev/sda1 /my_new_part
```
## Filesystem Integrity and Maintenance
```
# Filesystem usage
df
# Filesystem usage by nodes
df -i
# Detailed filesystem usage
du -sh
```
## Periodic filesystem hygiene
```
# Remove temporary files
find $HOME -type f -name "*~" -print
find $HOME -type f -name "*~" -print -exec rm {} \;
# Delete Kernel crashes
sudo find /var -type f -name "core" -print
# Delete old log files
sudo rm -v /var/log/*.gz
xfs_repair -f /dev/xvdf1
# Force fsck on the next reboot
shutdown -F -r now
```
## More about the shell
```
# Getting info
uname -sr
# Kernel version
uname -v
# Linux distribution
cat /etc/*-release
lsb_release -a
```
## Create Swap Space
```
sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1
```
Add this line to `/etc/fstab`
```
swap /var/swap.1 swap defaults 0 0
```
## HTTP/HTTPS, DNS, NFS
Common used web servers:
* Nginx
* Apache2/httpd
HTTP Methods
* GET
* POST
* PUT
* DELETE
* PATCH
* HEAD
HTTP Statuses