forked from spirit986/AdminScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linux.Cheat.Sheet.notes
1837 lines (1402 loc) · 59.3 KB
/
Linux.Cheat.Sheet.notes
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
###############################################################################
##
## Linux Cheatsheet Notes
##
## This is a sublimetext .notes file
###############################################################################
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- General --- Linux All ---
-------------------------------------------------------------------------------
## Fix webserver permissions
sudo chown -R www-data:dev-mysitenamehere .
sudo find . -type f -exec chmod 644 {} \;
sudo find . -type d -exec chmod 755 {} \;
## Get the ip address
ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'
## Get the ip address, alternative
ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'
## Update /etc/hosts with the IP/HOSTNAME of the server
IPADDR=`ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'`
## Add new line character at the end of file in bash
echo "" >> file.txt
sed -i '' -e '$a\' file.txt
## The ultimate grep
# -r Recusive, -n Display line number, -w Whole words, -i Ignore case,
# -I Ignore binary
grep -rnwiI /path/to/dir -e "StrIng to Search"
## Filter out the comments from a file with grep
# -o: prints only matched part of the line
# first ^: beginning of the line
# [^#]*: any character except # repeated zero or more times
grep -o '^[^#]*' file
## Show listening ports and processes
netstat -tulnp
## Show the routing table
netstat -nr
## Netstat filter out the uniques
# https://www.blackmoreops.com/2014/09/25/find-number-of-unique-ips-active-connections-to-web-server/
netstat -antu | grep ':80\|:443' | grep -v LISTEN | awk '{print $5}' | cut -d: -f1 | sort | uniq -c
netstat -antu | grep ':80\|:443' | grep -v LISTEN | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn
netstat -antu | grep -v LISTEN | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn
## Filtering with awk
cat /var/log/toptal/access.log | awk -F \" '{print $6}' | sort -n | uniq -c | grep -v - | sort -rn | head
## Check top outgoung connecitons
netstat -nputw | awk '{print $5}' | cut -d: -f1 | sort | uniq -c
## DU (check disc usage)
# Current Directory
du -schx
# Inspect
du -ch --max-depth=1 /
# NCDU - a smarter way to check disk usage
ncdu -rx /
## Convert ssh public key into .pub format
ssh-keygen -f kstamenow.pem -i
## Rsync
# Copy a single file over SSH that listens on port 9022 on the remote machine
# also show a progress bar
rsync -Wzvh --progress -e "ssh -p 9022" [email protected]:/media/shared/xvda.vmdk /mnt/d/VMs/
# Copy recursively (the -a flag)
rsync -Wazvh -progress -e "ssh -p 9022" [email protected]:/media/ /destination
# Copy files localy
rsync
## Count number of processes per service
pidof httpd | wc -w #Will return the number of httpd processes running
.. or
pgrep -c 'httpd|apache2'#This version is going to work on redhat/centos/suse AND ubuntu/debian systems
## Linux list services on a SystemD host
ls /etc/systemd/system/multi-user.target.wants/*.service
## Get the key based on a fingerprint
ssh-keygen -lf pub.key
## Resize an XFS root partition on CentOS on the fly
#https://stackoverflow.com/questions/38160794/how-to-resize-root-partition-online-on-xfs-filesystem
1. Increase the disk size from the cloud platform
2. Install cloud-utils-growpart if not present already
$ yum install cloud-utils-growpart
3. Use growpart to incease the partition size:
$ growpart /dev/xdva 1 #Where 1 is the partition number
4. Use xfs_growfs to rezise the partition
$ xfs_growfs -d /dev/xvda1
## How to use nc (netcat) instead of telnet
#Success
[bash]
$ nc -zv server.com 5000
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to 10.65.1.85:5000.
Ncat: 0 bytes sent, 0 bytes received in 0.01 seconds.
#Failed
$ nc -z server.com 5001
[root@worker01 ~]# nc -v server.com 5001
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connection refused.
[end]
## List network interfaces alternative way
cat /proc/net/dev
## Get the linux verion / release
cat /etc/*release*
## Bring up the interface using ifconfig and assign IP from a DHCP
# Very usefull on simple systems that do not have ifup command
ifconfig eth0 0.0.0.0 0.0.0.0 && dhclient
## Simulate load
fulload() { dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null & }; fulload; read; killall dd
## Find and list all files in a directory on a giben date
## https://www.cyberciti.biz/faq/unix-linux-list-all-files-modified-on-given-date/
find /storage/log/vmware -newermt 2018-09-06 ! -newermt 2018-09-07 -ls
## Apache2 list modules
apachectl -t -D DUMP_MODULES
apache2ctl -M
## Regenerate a new initrd
## Take backup of the old first
mkinitrd /boot/initrd-latest.img $(uname -r)
## MTR
### Cool way to check for packet loss between hops
mtr -rwc 100 -i 0.5 -rw www.google.com
mtr -rwc 100 -i 0.5 -rw 10.69.11.8
## Systemd | List services that depend on another service
## In this example the services that depend by network-online.target
$ systemctl show -p WantedBy network-online.target
## PS1 Prompt
# Normal user
export PS1="\[\033[38;5;10m\]\n[\$?] \u@\h\[$(tput sgr0)\]\[\033[38;5;15m\]\n\w \\$ \[$(tput sgr0)\]"
# Rooot user
export PS1="\[\033[38;5;9m\]\n[\$?] \u@\h\[$(tput sgr0)\]\[\033[38;5;15m\]\n\w \\$ \[$(tput sgr0)\]"
## Get octal file permissions
## Replace * with the relevant directory or the exact filename that you want to examine.
stat -c "%a %n" *
## Delete foldes/folders older than X days
# the basic format - for files
$ find /tmp/*/* -mtime +7 -type f -exec rmdir {} \;
# the basic format - for folders
find /tmp/*/* -mtime +7 -type d -exec rmdir {} \;
## Secure linux history
## The bellow options will make the linux history with a timestamp, will immediately log the history and will log the history to syslog
[bash]
cat >>/etc/profile.d/history.sh <<'EOF'
export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) [$$] [$PWD] : $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"; history -a; history -c; history -r;'
export HISTTIMEFORMAT="%F %T "
export HISTFILESIZE="5000"
EOF
cat >>/etc/rsyslog.d/commands.conf <<EOF
local6.* /var/log/commands.log
EOF
[end]
## Cool way to keep your SSH session open
# Can be used in case there is an auto-session-terminate-logout implemented in the system
ping 127.0.0.1 >/dev/null 2>&1 &
## Generate password for htpasswd with openssl
# This will ask for password to be entered for the specified $USERNAME and set the hashed password in /etc/nginx/htpasswd.users
echo "$USERNAME:`openssl passwd -apr1`" | sudo tee -a /etc/nginx/htpasswd.users
## Systemcd | Systemctl list all services
systemctl list-units --type=service
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- GIT
-------------------------------------------------------------------------------
## Example of how to use Git branches
## https://stackoverflow.com/questions/4515644/git-checkout-does-not-change-anything
[bash]
$ git branch
* master
organize
$ git branch networking
$ git checkout networking
$ git branch
master
* networking
organize
## Now Master has been updated many times since anyone has done anything on networking
$ git pull origin networking
[end]
## Git fetch all branches before checkout
# Clone
git clone [email protected]:greenplum-db/gpdb.git
# Update
git fetch --all
git checkout -b [BRANCH_NAME]
git pull --rebase origin master
git checkout -b BRANCH-NAME
## Git switch to a branch but set to track the changes from the same remote branch
## I.E. Fix the DETACHED HEAD when checking out to a new branch
## Example:
[bash]
$ git clone https://github.com/phpipam/phpipam.git
$ git status
# On branch master
$ git checkout 1.4
Note: checking out '1.4'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
HEAD is now at 29babcf... Removed minimized js.css
$ git pull
You are not currently on a branch. Please specify which
branch you want to merge with. See git-pull(1) for details.
git pull <remote> <branch>
$ git branch
* (detached from 1.4)
master
$ git checkout -b 1.4 origin/1.4
Branch 1.4 set up to track remote branch 1.4 from origin.
Switched to a new branch '1.4'
[end]
## Git see your recent commits
git log origin/master..HEAD
## Git see changes from the recent commits
git diff origin/master..HEAD
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- TAR
-------------------------------------------------------------------------------
# -c : Create a new archive
# -x : Extract the contents of an archive
# -t : Lists the contents of an archive
# -z : Filter the archive through gzip
# -j : Filter the archive through bzip2
# -v : Verbose output
# -f file.tar.gz : Use archive file
# Exclude directories/files with:
# --exclude='dir1'
## CREATING ARCHIVES
# Creating a GZip archive
tar -czvf file.tar.gz /path/to/dir/
# Creating a BZip archive
tar -cjvf file.tar.bz2 /path/to/dir/
# Compress a filename
tar -czvf file.tar.gz /path/to/dir/filename
## EXTRACTING ARCHIVES
# For GZip
tar -xzvf file.tar.gz -C /path/to/destination/dir
# For BZip
tar -xjvf file.tar.bz2 -C /path/to/destination/dir
## LISTING ARCHIVES
# For GZip
tar -tzvf file.tar.gz
# For BZip
tar -tjvf file.tar.bz2
-------------------------------------------------------------------------------
--- Cool timestamp function example for use in scripts #date
--- https://www.linode.com/docs/tools-reference/tools/use-the-date-command-in-linux/
-------------------------------------------------------------------------------
[bash]
function db_filename () {
DATE=$(date +%H-%M-%S)
BACKUP=db-$DATE.sql
echo $BACKUP
}
BACKUP_PATH=/tmp/$(db_filename)
[end]
Another example:
$(date "+%FT%T")
# Use this when renaming
{,.$(date "+%FT%T")}
example: mv file{,.$(date "+%FT%T")}
-------------------------------------------------------------------------------
--- GENERATE UUID for device
-------------------------------------------------------------------------------
## When an interface is new and apropriate configuration files need to be
# created in /etc/sysconfig/network-scripts/
## Generate interface UUID (examole if the new interface is enp0s8)
uuidgen enp0s8
c347febc-b549-456b-b415-477fa4b392e2
## Configure the new interace
vim /etc/sysconfig/network-scripts/ifcfg-enp0s8
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=none
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=enp0s3
UUID=c347febc-b549-456b-b415-477fa4b392e2
DEVICE=enp0s8
ONBOOT=yes
IPADDR=
NETMASK=
GATEWAY=
DNS1=
DNS2
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- Create user, give access and give access and give it All
-------------------------------------------------------------------------------
## You still need to add password in the end
[bash]
sudo su -
FULLNAME="Fname Lname"
USERNAME=flanme
PUBLIC_KEY="ssh-rsa your-public-key [email protected]"
useradd -c "$FULLNAME" -m -s /bin/bash $USERNAME && \
mkdir -p /home/$USERNAME/.ssh/ && \
echo "$PUBLIC_KEY" > /home/$USERNAME/.ssh/authorized_keys && \
chown -R $USERNAME:$USERNAME /home/$USERNAME/.ssh/ && \
echo "$USERNAME ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/$USERNAME && \
chmod 0440 /etc/sudoers.d/$USERNAME
## Use this if you plan to give the same key to root
cp -R /home/$USERNAME/.ssh .
passwd $USERNAME
[end]
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- Virtual Hardware HOT-ADD scripts
-------------------------------------------------------------------------------
## RAM hot add script
[bash]
root@server:~# cat hot_add_mem.sh
#!/bin/bash
# Bring all new Memory online
for RAM in $(grep line /sys/devices/system/memory/*/state)
do
echo "Found ram: ${RAM} ..."
if [[ "${RAM}" == *":offline" ]]; then
echo "Bringing online"
echo $RAM | sed "s/:offline$//"|sed "s/^/echo online > /"|source /dev/stdin
else
echo "Already online"
fi
done
[end]
## CPU hot add script
[bash]
root@server:~# cat hot_cpu_add.sh
#!/bin/bash
# Bring CPUs online
for CPU_DIR in /sys/devices/system/cpu/cpu[0-9]*
do
CPU=${CPU_DIR##*/}
echo "Found cpu: '${CPU_DIR}' ..."
CPU_STATE_FILE="${CPU_DIR}/online"
if [ -f "${CPU_STATE_FILE}" ]; then
if grep -qx 1 "${CPU_STATE_FILE}"; then
echo -e "\t${CPU} already online"
else
echo -e "\t${CPU} is new cpu, onlining cpu ..."
echo 1 > "${CPU_STATE_FILE}"
fi
else
echo -e "\t${CPU} already configured prior to hot-add"
fi
done
root@server:~#
[end]
## Disk hot add script
[bash]
root@librenms:~# cat rescan.sh
#/bin/bash
# ReScan all SCSI/SATA Hosts
for SHOST in /sys/class/scsi_host/host*; do
echo -n "Scanning ${SHOST##*/}..."
echo "- - -" > ${SHOST}/scan
echo Done
done
[end]
-------------------------------------------------------------------------------
--- VIM
-------------------------------------------------------------------------------
# Traversing text in inser mode
# https://stackoverflow.com/questions/1737163/traversing-text-in-insert-mode
# Save the file when you eddit without sudo
[bash]
$ :w !sudo tee %
[end]
# VIM useful delete examples
`diw` to delete the current word and ciw to cut the current word.
`de` is like `diw`, however it opens the opportunity to delete every next word just by pressing dot(.).
`di(` delete within the current parents.
`di"` to delete the text between the quotes.
`dab` delete around brackets.
`daB` delete around curly brackets.
# VIM useful cut examples
`ciw` to cut the current word.
`ci"` cut the word inside the quotes.
`ci(` cut the word in the parents.
`C` cut the rest of the line and enter INSERT MODE. This is very useful for cut and paste.
# VIM Miscellaneous useful commands
`zz` Scroll down the screen to make the current line appear in the middle. Very useful to put some chunk of code in focus.
`%` finds and moves the cursor to the matching parentheses.
`:%TOhtml` Creates HTML version of the current document. (Try it, it is very useful).
`vim http://site.com/` Vim can also open up URLs assuming they go directly to static HTML files.
# VIM Search and replace
In its basic form, it is the `:substitute` command or :s for short that searches a text pattern and replaces it with a string. The command has many options and these are the most commonly used ones.
`:%s/something/something_else/g` Find the word something and replace it with something_else in the entire document.
`:s/something/something_else/g` Similarly like the before command. This one just replaces in the current line only.
`:%s/something/something_else/gc` Note the c. It replaces everything but asks for confirmation first.
`:%s/\<something\>/something_else/gc` Changes whole words exactly matching something with something_else but ask for confirmation first.
`:%s/SomeThing/something_else/gic` Here the i flag is used for case insensitive search. And the c flag for confirmation.
# VIM Comment out blocks of code
Enter Blockwise visual mode with CTRL+V and mark the block you wish to comment.
Press capital I and enter the comment string at the beginning of the line (# for bash, or // for C++ etc..)
Press ESC twice and all the lines will be commented out.
## VIM comments
#abe6f2
## http://www.color-hex.com/
You can do it manually with this command:
:hi Comment guifg=#ABCDEF
Where ABCDEF is an appropriate color hex code.
To make it permanent, you will need to add these lines to your ~/.vimrc file (using green as an example):
syntax on
:highlight Comment ctermfg=darkcyan
:highlight Comment ctermfg=lightblue
:highlight Comment ctermfg=#00f7ff
# Example
-------------------------------------------------------------------------------
mkdir -p ~/.vim/colors/myscheme.vim
---
hi clear
if exists("syntax_on")
syntax reset
endif
let colors_name = "myscheme"
hi Comment guifg=#80a0ff ctermfg=darkred
---
cd ~
vim .vimrc
---
syntax on
colorscheme myscheme
---
# Script that fixes vim comments dark blue color on any system
[bash]
cat >lightcomment.sh <<ENDTR
#!/bin/bash
mkdir -p ~/.vim/colors
touch ~/.vim/colors/lightcomment.vim
cat >~/.vim/colors/lightcomment.vim <<EOF
hi clear
if exists("syntax_on")
syntax reset
endif
let colors_name = "lightcomment"
hi Comment ctermfg=lightblue
EOF
if [ ! -f ~/.vimrc ]
then
cat >>~/.vimrc <<EOF
syntax on
colorscheme lightcomment
EOF
else
echo ".vimrc has been detected. Edit the file manually and add the following lines:"
echo
echo "syntax on"
echo "colorscheme lightcomment"
fi
ENDTR
chmod +x lightcomment.sh
[end]
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- Netstat - How-To filter out unique entries from a netstat file ---
-------------------------------------------------------------------------------
The netstat file looked like this:
...
...
TCP 10.137.0.41:61376 10.69.11.238:1433 ESTABLISHED
TCP 10.137.0.41:61881 10.137.6.230:1433 ESTABLISHED
TCP 10.137.0.41:61888 10.137.6.230:49154 ESTABLISHED
...
...
awk '{print $3}' 10.137.0.41.ip.log | egrep -o '^[^:]+' | sort -nr | uniq -c
awk '{print $3}' 10.137.0.41.ip.log # Print the 3rd row 10.69.11.238:1433
... | egrep -o '^[^:]+' # pipe through grep filter out the IP untill the collon
... | sort -nr | uniq -c # Speaks for itself
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- Apt-Get --- Debian, Ubuntu, Mint etc.. ---
-------------------------------------------------------------------------------
# https://www.tecmint.com/useful-basic-commands-of-apt-get-and-apt-cache-for-package-management/
## List All Available Packages
apt-cache pkgnames
## List Installed Packages
apt list --installed
## Search package and related packages
apt-cache search vsftpd
## Check package information
apt-cache show vsftpd
## Show package dependences
apt-cache showpkg vsftpd
## Search for all possible versions of a specific package (example docker-ce)
$ apt-cache madison docker-ce
docker-ce | 5:18.09.5~3-0~ubuntu-bionic | https://download.docker.com/linux/ubuntu bionic/stable amd64 Packages
docker-ce | 5:18.09.4~3-0~ubuntu-bionic | https://download.docker.com/linux/ubuntu bionic/stable amd64 Packages
docker-ce | 18.06.0~ce~3-0~ubuntu | https://download.docker.com/linux/ubuntu bionic/stable amd64 Packages
docker-ce | 18.03.1~ce~3-0~ubuntu | https://download.docker.com/linux/ubuntu bionic/stable amd64 Packages
## Prevent a package from upgrading when apt-get upgrade is run (example docker-ce)
$ apt-mark hold docker-ce
## Remove the hold
apt-mark unhold <package-name>
## Show packages on hold
apt-mark showhold
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- DPKG ---
-------------------------------------------------------------------------------
## List Installed on older debian distros
dpkg --get-selections
dpkg --get-selections | grep -v deinstall
## To get a list of a specific package installed:
dpkg --get-selections | grep postgres
## List packeges
dpkg -l
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- NMAP ---
-------------------------------------------------------------------------------
# Something that REALLY works
# https://security.stackexchange.com/questions/36198/how-to-find-live-hosts-on-my-network
nmap -sP -PS22,3389 target #custom TCP SYN scan
nmap -sP -PA21,22,25,3389 target #21 is used by ftp
sudo nmap -sP -PU161 192.168.2.1/24 #custom UDP scan
#### FIREWALLS
## Test these against a firewall
nmap –v –sA –n www.yourorg.com –oA firewallaudit.log
## Test with fragmented traffic
nmap –sF –g 25 –oN firewallreport.log www.yourorg.com
## Another example
nmap –sS --scan-delay 500 –f –rH firewallreport.txt www.yourorg.com
# https://highon.coffee/blog/nmap-cheat-sheet/
## Ping scans the network, listing machines that respond to ping.
nmap -sP 10.0.0.0/24
## Full TCP port scan using with service version detection
## usually my first scan, I find T4 more accurate than T5 and still
## pretty quick.
nmap -p 1-1024 -sV -sS -T4 domain.me
## Prints verbose output, runs stealth syn scan, T4 timing, OS and version
## detection + traceroute and scripts against target services.
nmap -v -sS -A -T4 target
## Prints verbose output, runs stealth syn scan, T5 timing, OS and version
## detection + traceroute and scripts against target services.
nmap -v -sS -A -T5 target
## Prints verbose output, runs stealth syn scan, T5 timing, OS and
## version detection.
nmap -v -sV -O -sS -T5 target
## Prints verbose output, runs stealth syn scan, T4 timing, OS and version
## detection + full port range scan.
nmap -v -p 1-65535 -sV -O -sS -T4 target
## Prints verbose output, runs stealth syn scan, T5 timing, OS and
# version detection + full port range scan.
nmap -v -p 1-65535 -sV -O -sS -T5 target
## Disk size in MB ordered from most usage to less usage
du -sm * | sort -rn
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- CURL ---
-------------------------------------------------------------------------------
[bash]
curl -LI google.com #Follow redirects and get the header only
curl -o website https://google.com #Save output to file
curl -O https://domain.com/file.zip #Download files
[end]
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- Move a folder to a separate partition ---
-------------------------------------------------------------------------------
# In the example bellow we will move /var/log on a JIRA server to a separate
# partition.
[bash]
# Fin all processes using files in /var/log and stop them
lsof | grep /var/log
pkill auditd
pkill rsyslogd
service mysqld stop
pkill superviso
pkill puthon
service httpd stop
service docker stop
# Mount the partition /dev/nvme2n1 to a temp place
mount /dev/nvme2n1 /temptmp
rsync -avz --progress /var/log/ /temptmp
# Move away the old /var/log and create a new one
mv -i /var/log /var/log.old
mkdir /var/log
# Mount the partition into /var/log
umount /dev/nvme2n1
mount /dev/nvme2n1 /var/log
# Check /etc/mtab and copy the mount point into /etc/fstab
cat /etc/mtab
vim /etc/fstab
/dev/nvme2n1 /var/log ext4 rw,relatime,data=ordered 0 0
# reboot
reboot
[end]
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- Remove Cloud Init cloudinit ---
-------------------------------------------------------------------------------
[bash]
$ echo 'datasource_list: [ None ]' | tee /etc/cloud/cloud.cfg.d/90_dpkg.cfg
$ apt-get purge cloud-init -y
$ rm -rf /etc/cloud/; rm -rf /var/lib/cloud/
[end]
## Alternative
$ service cloud-init stop
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- LVM ---
-------------------------------------------------------------------------------
## Resize LVM with xfs
996 pvs
997 lvs
998 vgs
999 cat /etc/fstab
1000 lvextend -l +50%FREE /dev/mapper/centos-var
1001 vgs
1002 xfs_growfs /var
1003 df -h
1004 vgcfgbackup
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- Test Disk Read and Write speed ---
-------------------------------------------------------------------------------
## Disk Read/Write speed test with `dd`
$ sync; dd if=/dev/zero of=/root/testspeed bs=1M count=1024; sync
$ /sbin/sysctl -w vm.drop_caches=3 ## This cleans the cache from memory
$ dd if=/root/testspeed of=/dev/null bs=1M count=1024
$ sync; dd if=/dev/zero of=/efs-infer/bench_infer bs=1M count=1024; sync
$ /sbin/sysctl -w vm.drop_caches=3
$ dd if=/efs-infer/bench_infer of=/dev/null bs=1M count=1024
/bin/sync; /bin/dd if=/dev/zero of=/nfs/bulk_benchmark bs=1M count=3072; /bin/sync
/sbin/sysctl -w vm.drop_caches=3
/bin/dd if=/nfs/bulk_benchmark of=/dev/null bs=1M count=3072
sync; dd if=/dev/zero of=/efs bs=1M count=4096000; sync
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
--- How to disable root login the friendly way ---
-------------------------------------------------------------------------------
no-port-forwarding,no-agent-forwarding,no-X11-forwarding,command="echo 'Please login as the user \"ubuntu\" rather than the user \"root\".';echo;sleep 10" ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2Jyv9T14/XraaCUeFZ1xrQsTge9PydO+ypkSdQI4qrnPFJBBBoX0UtxvQYNOaqrxEHQ7wxVrIj7Uwop7D8/DJgJpZHmmHU0PW5uHl7z4m0ofdOdzlx+UyD/n1yh//73E+OhN4x4y+Ann/dkRFqc095kqA6sVZNSbgJPX+iUpB06WjIQXjOYD3Pvy9lXQzghszRt2hWbN8cfYnJ6CLacPfkeGOS/p2wKJ4hkjSr9vfm4MCKDgKIopizMC78tfNxQNkWrxgv78Mg+qgescM83O8CM7uJpflTT+HySutnmR0R+tst4BCdFTV8KsB4ZjNTCkoC5RLRF7FWEt+FmjuPtX/ [email protected]
===============================================================================
===============================================================================
...............................................................................
...............................................................................
...............................................................................
===============================================================================
## Ubuntu specific ---
===============================================================================
## Things to do and to install after a fresh Ubuntu install
[bash]
apt update && apt upgrade -y
apt install htop nmon nethogs screen vim mc tcpdump net-tools bash-completion
apt install bash-completion
[end]
## Remove cloud-init from Ubuntu18
## https://nucco.org/2018/05/ubuntu-18-04-chronicles-removing-cloud-init.html
$ dpkg-reconfigure cloud-init // Deselect everything except None
// Remove/purge cloud-init
$ apt-get purge cloud-init
// Remove the configuration files
$ mv /etc/cloud/ ~/; sudo mv /var/lib/cloud/ ~/cloud-lib
// Disable the service that might hang afterwards
$ systemctl show -p WantedBy network-online.target
===============================================================================
...............................................................................
...............................................................................
...............................................................................
===============================================================================
## CentOS specific ---
===============================================================================
## Things to do and to install after a fresh CentOS install
# In case there is no networking
[bash]
yum install -y epel-release
yum makecache
yum install vim nano curl wget tcpdump git net-tools bash-completion openssl-devel bind-utils httpd-tools screen nethogs
[end]
[bash]
vi /etc/susconfig/network-scripts/ifcfg-enp0s3
ONBOOT=yes
yum update -y
yum install -y epel-release
yum install vim nano curl wget tcpdump git net-tools bash-completion openssl-devel bind-utils httpd-tools screen nethogs
yum install -y openssh
systemctl start sshd.service
systemctl enable sshd.service
[end]
## CentOS7 Static IP
$ vim /etc/sysconfig/network-scripts/ifcfg-IFNAME
IPADDR=192.168.1.200
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=1.0.0.1
DNS2=1.1.1.1
DNS3=8.8.4.4
$ systemctl restart network
## CentOS7 Static Route
$ vim /etc/sysconfig/network-scripts/route-IFNAME
#SOURCE GW OPTIONAL
15.15.0.0/24 via 10.1.1.110 dev enp0s3
$ systemctl restart network
===============================================================================
...............................................................................
...............................................................................
...............................................................................
===============================================================================
### Convert Amazon AMI to VMware image
===============================================================================
## https://serverfault.com/questions/319949/convert-amazon-ami-to-vmware-image
If you still have access to the instance, I believe the simplest way would be using "dd" to copy it off to a raw file (possibly just directly piping over SSH to the destination system like in ssh your.ec2-syst.em 'dd if=/dev/sdh bs=1M | gzip' | gunzip | dd of=/tmp/ec2-image.raw) and then using something like qemu-img to convert the raw image to a VMDK file.
qemu-img convert -f raw -O vmdk /tmp/ec2-image.raw /tmp/ec2-image.vmdk. Maybe the QEMU wikibook could be of some further help, if you still are having problems.
[bash]
ssh your.ec2-syst.em 'dd if=/dev/sdh bs=1M | gzip' | gunzip | dd of=/tmp/ec2-image.raw
qemu-img convert -f raw -O vmdk /tmp/ec2-image.raw /tmp/ec2-image.vmdk
[end]
## https://serverfault.com/questions/364470/how-to-download-private-ubuntu-aws-ec2-ami-for-local-use
## https://preda.wordpress.com/2012/08/29/downloading-an-amazon-ec2-ami-to-local-drive/
## To filetransfer the VM named Nomad
# /dev/xvda
ssh -i privkey.pem [email protected] 'sudo dd if=/dev/xvda bs=1M | gzip' | gunzip | dd of=xvda.raw
# /dev/xvdb
ssh -i privkey.pem [email protected] 'sudo dd if=/dev/xvdb bs=1M | gzip' | gunzip | dd of=xvdb.raw
# QEMU confert the raw images of Nomad
qemu-img convert -f raw -O vmdk xvda.raw xvda.vmdk
===============================================================================
...............................................................................
...............................................................................
...............................................................................
===============================================================================
### DOCKER ---
===============================================================================
# Get basic servce information
service docker status
/etc/init.d/docker status
systemctl status docker
# Start stop restart the service
service docker start
/etc/init.d/docker start
systemctl start docker
# Get container IP
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
# Get docker information
docker info #localy
docker -H 10.76.16.136 info #remotely
# List containers
docker -H 10.76.16.136 ps -a