Show particular line from a file:
sed -n 5p file.txt
-----------------------------------------------
Checksum a file (SHA-1):
sha1sum myfile.ext
-----------------------------------------------
List open ports:
lsof -i -P -n | grep LISTEN
-----------------------------------------------
Copy text file after Nth line to another file:
awk 'NR>=407137' my.log > my.log.NEW
-----------------------------------------------
NTP server test command:
ntpdate -q 172.12.23.123 (Buradaki q sayesinde sadece query yapmış olur. Set vs etmez)
-----------------------------------------------
When you login with ssh you see bash-4.2$ instead of hostname and username:
just copy .bashrc file to your home directory from a working accounts home directory
If above not helps do the same for .bash_profile file
-----------------------------------------------
How to put hostname as filename
grep "looked4Str" * > "$(uname -n).txt"
-----------------------------------------------
How to truncate a log file
cat /dev/null > myfile.log
-----------------------------------------------
Cut examples
Cut according to commas and take 4th and 6th occurences and put comma between them: cut -d ',' -f 4,6 ahmets.txt
-----------------------------------------------
How to use ssh command passwordless
in the local server:
ssh-keygen (press enter for every question)
ssh-copy-id remoteuser@remoteserverip (asks password)
test new passwordless ssh command: ssh remoteuser@remoteserverip
-----------------------------------------------
Check port access via telnet
telnet 192.168.1.100 21379
to exit telnet: quit
to terminate telnet (turkish): ctrl + ü
-----------------------------------------------
Restart snmp service in Linux
service snmpd restart
-----------------------------------------------
Change extension of multiple files
rename .txt .doc *.txt (sonu txt olan dosyaları bul ve doc yap onları)
-----------------------------------------------
Copy files having one of these extensions
cp *.{txt,jpg,png} destination/
veya
rsync --ignore-existing -zvh *.{txt,jpg,png} destination/
-----------------------------------------------
List running scripts when computer starts
less /etc/rc.d/rc.local
less /etc/rc.local
ll /etc/rc.d/init.d/
ll /etc/init.d
-----------------------------------------------
Nohup example (without any log)
nohup $(zip -r myfile.zip myFolder)>/dev/null 2>&1 &
-----------------------------------------------
Finding files modified in last 2880 minutes (2 days) and compressing them (leave originals same)
tar cvf - `find . -mmin -2880 -type f` | gzip -c 1>mylogs.tgz
NOTE : use ` not 'Find files which does not ends with some extension in current folder and delete them (Not in child folders)
find . -maxdepth 1 -type f ! -name "*.inprogress" -exec rm -rf {} \;
-----------------------------------------------
List running services
service --status-all
-----------------------------------------------
Clear screen with all the buffers
clear && printf '\e[3J'
-----------------------------------------------
Give all permissions to everyone for a file
chmod ugo+rwx myfile.abc
or
chmod 777 myfile.abc
-----------------------------------------------
Get the chmod numerical value for a file
stat --format '%a' myFile.txt
-----------------------------------------------
TCPDUMP Örnekleri
Her interface'den dump al
tcpdump -i any
Port belirle:
tcpdump -i any port 80
Dosyaya yazdır
tcpdump -i any port 80 -w myFile.pcap
Source IP: tcpdump src 192.168.146.91 -i eth1
Source or destination IP: tcpdump host 192.168.146.91 -i eth1
Subnet: tcpdump net 192.168.146.91/32 -i eth1
-----------------------------------------------
How To make an SNMP request
snmpget -v 1 -c public 192.168.1.150 system.sysUpTime.0
-----------------------------------------------
Find out Linux Distribution Information (one of these commands should work)
lsb_release -a
cat /etc/*release
cat /etc/issue.net
cat /etc/debian_version
-----------------------------------------------
About Smybolic Links
-----------------------------------------------
Creating an .sh file and running
vi myScript.sh
i'ye bas ve dosya içini şuna benzet
#!/bin/bash
echo "Hello world"
chmod 755 myScript.sh
./myScript.sh
-----------------------------------------------
ls örnekleri
List only directories: ls -d */ (not: sondaki */ tuhaf bir şekilde şart)
Multiple wildcard search: ls {this*,that*}
-----------------------------------------------
How to kill a process with processId (PID)
kill pid (kinder)
or
kill -9 pid (die now)
How to find pid
ps -ef | grep processname (2nd column gives pid)
-----------------------------------------------
tcpdump örneği
tcpdump -i eth0 -w captured.pcapng
-----------------------------------------------
curl examples:
Sadece http response code'u almak için: curl -sw '%{http_code}\n' https://www.google.com/
SSL hatasını suppress etmek için: curl -k https://myserver.com
Post yapmak için: curl -X POST http://myserver.com
-----------------------------------------------
wget examples:
Print response body: wget -qO- 'http.vs.vs'
Print only response code: wget --server-response "http://google.com" 2>&1 | awk '/^ HTTP/{print $2}'
-----------------------------------------------
terminalde root olma
sudo -i veya sudo su veya sudo -s veya su
sudo -i gives you the root environment, i.e. your ~/.bashrc is ignored.
sudo -s gives you the user's environment, so your ~/.bashrc is respected.
-----------------------------------------------
tek satır komut ile şifre değiştirme (yeni şifre içinde ! olmasın)
echo -e "YourCurrentPassword\nYourNewPassword\nYourNewPassword" | passwd
-----------------------------------------------
grep örnekleri
Search for ip addresses in file, only print matching part: grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' myfile.yxy
also print 2 lines after matched line: grep -A2 "aranan string" dosyaAdi.txt
case insensitive arama: grep -i "aranan string" dosyaAdi.txt
sadece dosya ismini bas ekrana: grep -l "aranan string" dosyaAdi.txt (dikkat ufak L harfi o)
dosya ismini basma ekrana: grep -h "aranan string" dosyaAdi.txt
şu regex'i ara: grep -P 'number=\d+' dosya.txt
şu kelime kaç kere geçmiş say: grep -c "Read timed out" xyz.log
birden fazla kelime arama:
OR: grep "acm\|hazel" dosyaAdi.txt veya grep -e "kelimeBir" -e "kelimeİki" dosyaAdi.txt
AND: grep "ali" dosyaAdi.txt | grep "veli"
ekranda akıcı kelime içeren satıran: tail -f file | grep --line-buffered my_pattern
şu pattern'e uyan dosyaların içinde kelime ara: grep "aranan string" *fileNamePattern*
şu pattern'e uyan dosyaları arama: --exclude="*.abc"
şu klasördeki tüm dosyaların içinde şu kelimeyi ara: grep -r "patron Bebek" .
sadece match olan kısmı ekrana bas: grep -o "ilkKelime.*ikinciKelime" dosyaAdi.txt
şunu içerMEyen satırları bul: grep -v "beni_icerme"
şunları içerMEyen satırları bul: grep -Ev 'word1|word2'
zip'lenmiş (veya .bz vs) log dosyalarının içinde arama yapma:
(BZ uzantılılar için) bzgrep 636000470 mylog.*
(GZ ve Z uzantılılar için) zgrep -a "string to search" mylog.* (-a means: Process a binary file as if it were text) (ZIP'lerde doğru çalışmaz)
Bulunduğun klasörde ve (içindeki klasörlerde de) son 2 gün içinde modifiye olmuş dosyaların içinde kelime ara:
gz uzantılı olanları bul ve içinde kelime ara: find . -name '*.gz' -mmin -2880 -type f -exec zgrep -H "060071EAB202A3BA" {} \+
gz uzantılı olmayanları bul ve içinde kelime ara: find . -not -name '*.gz' -mmin -2880 -type f -exec grep -H "060071EAB202A3BA" {} \+
Herhangi bir türdeki dosyanın içinde kelime ara: find . -mmin -2880 -type f -exec grep -H "060071EAB202A3BA" {} \+
-----------------------------------------------
list running processes ordered by name
ps aux --sort comm
search for a running process case insensitive
ps aux | grep -i acm
-----------------------------------------------
list mounted partitions
mount
--------------------------------
List physical disks only: ll /dev/sd*[a-z]
List physical disks and their partitions: fdisk -l
--------------------------------------
# umount /dev/sdb4 (işe yaramazsa -l ile dene)
----------------------
Recursively change the owner of all files in a directory
-------------------------
mbwe'de dosyalara gerekli olan izni sağlamak kodu
# chmod -R 744 PUBLIC
---------------------------
linux'de servisleri de bekleyerek vs, yani saygılı reboot/restart için: init 6 veya reboot. Shutdown için: shutdown now
Ve eğer bu cihaz kapanmaz ve "root account is locked" derse, -h anahtarını da ekle.
-------------------------------
Aptal SCREEN kullanımı
Linux'de ssh ile bağlanınca ve putty'yi veya network'u kapatınca bağlantı koparya, kopmasın diye Screen programcığını kullanabilirsin:
- screen: yeni bir kapanmaz session aç
Veya isim vererek aç: screen -S aerden
Ve isim vererek eski ekranı geri aç: screen -xS aerden
- programını vs burada çalıştır
- putty vs kapatabilirsin artık veya To detach screen you can use ctrl+a+d command. Detaching screen means exit from screen but you can still resume the screen later.
screen -ls: var olan session'ları listele
Örnek: 10835.pts-0.linuxize-desktop (Detached)
screen -r xxxx: ile listeden bir session'ı aç (Örnek: üstteki için xxxx yerine 10835 yaz)
- screen -r: eski ekranını geri aç (yemezse: screen -r -D yap)
-------------------------------
date -s "2 OCT 2006 18:00:00"
-----------------------------------
Find file or folders examples
find . -iname 'index*' -print 2>/dev/null
Note1: Runs in current directory and recursively, case insensitive, hides permission errors
Note2: 2 means stderr.
Find this folder case insensitive: find / -type d -iname "apt"
locate xyz (searches in all places for that pattern)
locate -i (means: ignore case)
-------------------------------------
Run multiple commands (one after another)
If you want to execute each command only if the previous one succeeded, then combine them using the && operator:
cd /my_folder && rm *.jar && svn co path to repo
If you want to execute all commands regardless of whether the previous ones failed or not, separate them with semicolons:
cd /my_folder; rm *.jar; svn co path to repo
---------------------------------------
Linux user işlemleri
List users
grep -oE '^[^:]+' /etc/passwd | sort
Add user
adduser newuser
passwd newuser
Remove user
userdel -r olduser (-r means: also delete that user's home directory and mail spool)
Add user to SUDO group
usermod -aG sudo username (sudo here is the groups name, maybe it is different in your conf)
Remove user from a group
gpasswd -d username groupname
List users in a group
lid -g groupname
Show all groups in this server:
cut -d: -f1 /etc/group | sort
Show me which group I belong to:
groups
Delete this group:
groupdel groupName
Switch user: su -l username (öncesinden "sudo -s" yap ki şifre sormasın sana)
Reset password for a user: you can give a new password for a user without knowing their old password if you are root.
passwd thatUser
---------------------------------------
Aptal Vİ kullanımı
- i ile insert mode'a gir, esc ile çık
- edit mode'da değil iken:
- x ile karakter sil
- dd ile satır sil
- tüm satırları silmek için: :1,$d
- arama için: önce ikinokto üstüsteye bas ve / yaz ve aranan kelimeyi yaz. n ile next yapar
dosyanın sonuna gitme: G
dosyanın başına gitme: gg
satırın sonuna gitme: $
satırın başına gitme: 0 (rakam)
---------------------------------------
Aptal LESS kullanımı
- u: undo
- G: go to the end of file
- g: go to the start of file
- 312g: go to 312th line
- space: page down
- b: page up
- "-N": show line numbers
- "-I" (minus and big i): ignore case for searching
- /: search for a pattern which will take you to the next occurrence
- ?: search for a pattern which will take you to the previous occurrence
- n: for next match
- N: for previous match
- "-S": chop lines (ie: turn off line wrapping)
---------------------------------------
Aptal uptime kullanımı
---------------------------------------
Disk kalan miktar bakma
# df -h
---------------------------------------
İçinde bulunulan klasörün size'ını görme
# du -sh .
İçinde bulunulan klasörün içindeki klasörülerin size'ını görme
# du -sh *
---------------------------------------
To list the largest directories from the current directory in human readable format:
du -hx --max-depth=1 | sort -h
Büyük dosyaları find etmek için (permission denied'ları gizle ve ebatı da ekrana bas)
find / -type f -size +1000M -exec du -sh {} \; 2>/dev/null
Bir dosyanın boyutunu öğrenmek için
du -sh filename.xyz
---------------------------------------
Kalan RAM miktarını yüzde olarak görme (UBUNTU DA DORĞU ÇALIŞMAZ BU KOMUT)
- buffers and cache'i de USED olarak sayararak:
free | grep Mem | awk '{print $4/$2 * 100.0}'
- buffers and cache'i de FREE olarak sayararak: (DOĞRUSU BU)
free | awk 'FNR == 3 {print $4/($3+$4)*100}'
---------------------------------------
Hangi Process RAM'i sömürüyor bulmak için: (en alttaki gelen en çok sömürendir)
- ps -e -o pid,vsz,comm= | sort -n -k 2
---------------------------------------
Kullanılan CPU miktarını yüzde olarak görme
- top -b -n2 | grep "Cpu(s)"|tail -n 1 | awk '{print $2 + $4}'
---------------------------------------
CPU'yu sömüren top 10 process'i bul
- ps -eo pid,user,ppid,cmd,%cpu --sort=-%cpu | head
- ps -ef | grep 45306
---------------------------------------
İçinde bulunduğun klasörün içini tamamen ve onaysız olarak silme
rm -rf *
Bir klasörü ve içindekileri silme
rm -rf xyz
How to Delete Files Older than 30 days in Linux (RECURSIVE)
find . -type f -mtime +30 -exec rm -f {} \;
How to Delete Files older than a specific date (RECURSIVE)
find . -type f -not -newermt "2021-06-01 00:00:00" -delete
---------------------------------------
Geçerli IP adreslerini listele
ip -4 addr | grep -oP '(?<=inet\s)\d+(\.\d+){3}'
veya
hostname -I | tr [:space:] '\n'
---------------------------------------
Sıkıştırma (zip'leme, tar'lama, unzip etme vs)
Şu dosyaları/klasörleri birlikte sıkıştır
tar -czf zipped.tar.gz /home/ahmet/dosya1.txt /home/ahmet/dosya2.txt /home/ahmet/klasör1 /home/ahmet/klasör2
Şu tar dosyasını aynı isimli bir klasör oluşturup içine aç:
tar -xzvf yourfile.tar.gz --one-top-level
Şu tar.gz içindeki dosyaların isimlerini göster
tar -ztvf archive.tar.gz
Şu klasörü ziple
zip -r myfile.zip myFolder
zip -4 -r -q myfile.zip myFolder (daha hızlı ol ve ekrana outout basma)
Bulunduğum klasör içindeki dosyaları sıkıştır ( SONDAKİ NOKTAYI UNUTMA )
zip -r zipped.zip .
Şu klasör ve dosyaları hızlıca sıkıştır ama şu dosya ve klasörleri alma:
zip -4 -r -q myzip.zip /cs/NM/lib /cs/NM/out -x "/cs/NM/out/production/IConn/iconnTi.bak2/*" -x "/cs/NM/out/production/IConn/iconnTi/N_log.txt"
Şu dosyaları zip'le
zip myZippedFile.zip file1.txt file2.txt
Bulunduğum klasörde recursive olarak şu tanıma uyan dosyaları bul ve sıkıştır
find . -name *PATTERN* -print | zip files.zip -@
Bulunduğum klasördeki tüm zip uzantılı dosyaları unzip et:
unzip \*.zip
Zip dosyasının içindeki dosyaları vs göster bana:
unzip -l myzip.zip
Bulunduğum klasördeki tüm gz uzantılı dosyaları uncompress et (dikkat orjinal *.gz'ler yok olur):
gunzip *.gz
---------------------------------------
change owner of a file
chown userName:groupName /home/userName/file.txt
change owner of a folder recursively
chown -R someuser:somegroup /your/folder/here/*
---------------------------------------
Bir klasör ve altındaki klasörülerin içindeki TXT dosyalarını bir txt'de birleştirme
- find . -type f -name '*.txt' -exec cat {} + >> output.file
---------------------------------------
List cron jobs for all users
- for user in $(cut -f1 -d: /etc/passwd); do printf "\n"; echo "Crontab for user: " $user; crontab -u $user -l; printf "\n"; done
List cron jobs for a user
- crontab -l -u myUserName
List cron jobs for current user
- crontab -l
Edit cron jobs for current user
- crontab -e
Latest log file location for cron jobs
/var/log/cron
---------------------------------------
Count number of files in each sub directory and print
- for f in */; do echo "$f -> $(ls $f | wc -l)"; done
---------------------------------------
Connect to shell of a remote server over shell
---------------------------------------
Count number of files with a specific extension in current folder recursively
find . -iname '*.CDR' | wc -l
---------------------------------------
SSH User Password Expiration Policy
TO GET ->chage -l myUser
TO SET NEVER EXPIRE -> chage -I -1 -m 0 -M 99999 -E -1 myUser
---------------------------------------
Commands regarding FTP
View a file's content without downloading it: curl -u username:password sftp://hostname/path/to/file.txt
Download folder: get -r myFolder
Download multiple files at once:
sftp myUser@1.2.3.4<< EOF
get /folder/file1 /home/user/file1
get /folder/file2 /home/user/file2
EOF
---------------------------------------
Replace a string in a text file without opening
sed -i 's/originalStr/newStr/g' file.txt
-i = in-place (i.e. save back to the original file)
s = the substitute command
---------------------------------------
SCP ile:
Bir server'daki klasörün içini, remote başka bir server'a kopyalama (first is source, second is destination)
scp -r /root/aerden/myfolder root@123.45.67.89:/root/myotherfolder
Bir server'daki bir dosyayı local'ine kopyalama (first is source file which is on remote server, second is destination folder which is current server where ssh console is opened)
scp ahmet.erden@172.1.2.3:/home/ahmet.erden/zipped.tar.gz /home/ahmet.erden
---------------------------------------
Learn encoding of a text file (ascii, utf-8 etc)
file -i myfile.txt
---------------------------------------
Port tunnelling over SSH in SecureCrt
in the local server:
---------------------------------------
Bir UDP portunun açık durumda olup olmadığını anlamak için komut:
netstat -lanu
netstat -lanu | grep 4000