0% found this document useful (0 votes)
140 views39 pages

Linux Cheat Sheet

The document provides information on various Linux system commands for: [1] Shutting down, rebooting, checking system uptime and runlevels; [2] Managing processes using commands like ps, kill, jobs; [3] Scheduling tasks using crontab and at; and [4] Other system utilities like alias, ntpdate, and man.

Uploaded by

sasha zavatin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views39 pages

Linux Cheat Sheet

The document provides information on various Linux system commands for: [1] Shutting down, rebooting, checking system uptime and runlevels; [2] Managing processes using commands like ps, kill, jobs; [3] Scheduling tasks using crontab and at; and [4] Other system utilities like alias, ntpdate, and man.

Uploaded by

sasha zavatin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

cursuri-linux.

ro
System Commands

shutdown bring the system down shutdown -h now ← -h = Halt or poweroff after shutdown
shutdown -r now ← -r : Reboot after shutdown
shutdown -r -F now ← -F : Force fsck after reboot.
halt stop the system. halt
reboot reboot the system. reboot
init init 1 #change to single usermode
uptime Tell how long the system has been running. uptime
runlevel find the previous and current system runlevel. runlevel
printenv print all or part of environment printenv
env run a program in a modified environment env
hostname show or set the system's host name hostname ← show the system's host name
I recommend uname -n for check hostanme.
hostname NEWHOSTNASME ← set the system's host name
uname print system information uname -a ← print all information (=uname --all)
uname -n ← show the system's host name (=uname --nodename)
locale Get locale-specific information. locale
locale -a |grep -i ja <- -a : --all-locales

1
cursuri-linux.ro
Process Management

ps report a snapshot of the current processes. ps aux |grep httpd ← Check httpd rocess
ps aux | grep XXX | awk '{print $2}' | xargs kill -9
ps auxwf
ps auxwf |grep XXX
pgrep look up processes based on name and other attributes pgrep -f 'bash'
pgrep -lf 'bash' ← output with process name
pgrep -f 'bash' | xargs kill
pstree display a tree of processes pstree -a
pidof find the process ID of a running program pidof httpd
/bin/kill $(/sbin/pidof qmail-popup)
kill send a signal to a process kill -9 PID ← (-9 or -KILL = force-quit)
pkill signal processes based on name and other attributes pkill -f 'bash'
pkill -u user1
pkill java
pkill -f jar
killall kill processes by name killall vi
killall -i vi ← -i = Interactively
killall -HUP kterm
killproc
lsof list open files lsof -i
lsof -i -P ← no port names
lsof -i :80,443 ← Which process is using Port 80,443
Ctrl + C Stop running process
Ctrl + Z Suspend running process Move Running Process to Background
1. ctrl + z
2. jobs
3. bg
4. disown %JOBID
jobs The first form lists the active jobs. jobs -l ← List job

2
cursuri-linux.ro
fg Resume jobspec in the foreground
bg Resume each suspended job jobspec in the background
nohup run a command immune to hangups, with output to a non-tty nohup command.sh &
disown disown %jobid
nice run a program with modified scheduling priority nice -n 19 test.sh
nice -n 19 ionice -c 3 CMD
nice -n 19 ionice -c 2 -n 7 COMMAND
renice alter priority of running processes renice 19 -p PID
you can check the nice whith “top” or “ps alx”.
ionice sets or gets process io scheduling class and priority ionice -p PID ← check
ionice -c 3 -p PID
nice -n 19 ionice -c 2 -n 7 COMMAND

3
cursuri-linux.ro
Schedule

crontab maintain crontab files crontab -l ← -l = list user's crontab


crontab -u USER -l
crontab -e ← -e = edit user's crontab
crontab -u USER -e
at queue jobs for later execution echo "/sbin/shutdown -h now" |at 21:00 02/30/2009
at -t 200902302100
atq lists the user's pending jobs atq
atrm delete jobs for later execution atrm JOBID
watch execute a program periodically, showing output watch ntpq -p ← By default, the program is run every 2
fullscreen seconds
watch -n 1 ntpq -p ← 1 seconds interval
-d : highlight the differences between successive updates

4
cursuri-linux.ro
etc

alias Alias with no arguments or with the -p option prints alias ← check all alias
the list of aliases alias ls='ls -la --color=auto'
When arguments are supplied, an alias is defined for alias grep='grep --color'
each name whose value is given.
unalias Remove each name from the list of defined aliases. unalias COMMAND
If -a is supplied, all alias definitions are removed.
ntpdate set the date and time via NTP ntpdate -b -u IP
-b : Force the time (step mode)
-u : If you are running ntpd, “-u” must be added.
chronyc command-line interface for chronyd chronyc sources
chronyc sources -v
chronyc sourcestats ← check offset
chrony makestep ← Correct the time
ntpq standard NTP query program ntpq -p
-p : Print a list of the peers known to the server
watch -n 1 ntpq -p
hwclock query and set the hardware clock (RTC) hwclock (-r) ← Read the Hardware Clock and print the
time on standard output.
hwclock -w ← Set the Hardware Clock to the current
System Time.
hwclock -s ← Set the System Time from the Hardware
Clock.
man an interface to the on-line reference manuals man COMMAND
whatis display manual page descriptions whatis KEYWORD
whatis cat
whatis vi
history GNU History Library history |less
history 5 ← lists only the last 5 lines.
HISTSIZE=1000
HISTTIMEFORMAT=“%Y/%m/%d %H:%M:%S ”

5
cursuri-linux.ro
which locate a command which ls
which -a bash ← -a : print all matching pathnames of
each argument
time time a simple command or give resource usage time sleep 5
strace trace system calls and signals strace -t php test.php
strace -t -o test.txt php test.php
-t : each line of the trace with the time of day.
ltrace A library call tracer lltrace -o test.txt wget http://example.com/
ltrace -p PID
ltrace -p 3365
script make typescript of terminal session script -afq $LOG

6
cursuri-linux.ro
File Commands

ls list directory contents ls -ltrh ← -r : reverse order while sorting


-h : with -l, print sizes in human readable format
ls -ltrh |less
cp copy files and directories cp -p SRC DES
cp -pi /etc/hosts{,.`date '+%Y%m%d'`}
cp -pr SRC/ DES/ ← -r,-R : copy directories recursively
cp -f SRC DES ← -f, --force
mv move (rename) files mv file1 file2
mv dir1 dir2
mv file1 file2 file3 DIR
rename renames multiple files rename .htm .html *.htm ← frm .htm to .html
rename "" test *.txt ← add test
rename test "" *.txt ← delete test
rm remove files or directories rm -rf TARGET ← -r,-R : remove directories
touch change file timestamps touch file1
touch -d “2017/10/20 13:00:00” file1
ln make links between files ln -s SRC DES
unlink unlink DES
wc print newline, word, and byte counts for each file wc -l ← -l, --lines = print the line counts
tree list contents of directories in a tree-like format tree -Dpuga /etc
col filter reverse line feeds from input man ifconfig | col -bfx > test.txt

7
cursuri-linux.ro
Directory Commands

pwd print name of current/working directory pwd


cd Change the current directory cd ← go to home directory
cd ~/ ← go to home directory
cd .. ← go to parent directory
pushd Adds a directory to the top of the directory stack pushd /var/log
pushd `pwd`
pushd +2 ← check pushd directory with dirs -v and go to
No.2
pushd +3 ← check pushd directory with dirs -v and go to
No.3
popd Removes entries from the directory stack. popd
dirs displays the list of currently remembered directories. dirs -v
mkdir make directories mkdir -p /tmp/test1/test2/ ← make parent directories as
needed
mkdir -m 700 /home/user01/.ssh
rmdir remove empty directories rmdir DIR
If you want to delete directory, you must use “rm -r
DIR”.

8
cursuri-linux.ro

Commands to Access File Contents

more file perusal filter for crt viewing


less opposite of more crontab -l |less
view Start in read-only mode.
cat concatenate files and print on the cat /dev/null > access.log
standard output
tail output the last part of files tail -n 50 aaa.txt ← output the last N lines
tail -f /var/log/messsages
tailf follow the growth of a log file tailf /var/log/messages
tailf -n 50 aaa.txt
head output the first part of files head -n 100 aaa.txt ← -n , --lines
<wrap hi>head * |more</wrap> ← View the beginning of the file in
the directory.
diff compare files line by line diff --suppress-common-lines --side-by-side File1 File2
diff /etc/test{,.`date '+%Y%m%d'`}
diff -r dir1 dir2 ← When comparing directories, recursively
compare
sdiff side-by-side merge of file differences sdiff -s File1 File2 ← -s : Do not print common lines.
sdiff -s -w 200 File1 File2
colordiff
vimdiff vimdiff file1 file2
vim -d file1 file2

9
cursuri-linux.ro

Searching

grep print lines matching a pattern grep WORD FILE |less


grep -Ev "^#|^$" xxx.txt
grep -Ev "^$|^#|^\s*#" file.txt
grep . ifcfg-eth* ← check filename and contents
grep "" ifcfg-eth* ← check filename and contents
grep -r PATTERN --include="*.txt" DIRECTORY ← -r : recursive
egrep egrep is the same as grep -E egrep "aaa|bbb" file
find , xargs search for files in a directory hierarchy find . -name "*txt*"
find /dir -type f -name "*.log*" -mtime +7 -exec rm -rf {} \;
← “-mtime +7” is 7 days ago

10
cursuri-linux.ro

File Compression

tar The GNU version of the tar archiving utility tar zcvf test.tar.gz Dir ← Create, Verbose, File
tar warn the order of target and destination. tar ztvf test.tar.gz ← Test, Verbose, File
tar zxvf test.tar.gz ← eXtract, Verbose, File
tar jcvf test.tar.bz2 DIR ← Create, Verbose, File
tar jxvf test.tar.bz2
tar zcvf /tmp/user01.tar.gz user01
tar zxvf user01.tar.gz -C /home
gzip compress or expand files gzip file1
gunzip gunzip file1.gz
gzip access_log.2011-[0][5-8]*.txt ←wild card
compress package and compress (archive) files compress file1
uncompress uncompress file1.Z
bzip2 a block-sorting file compressor bzip2 file1
bunzip2 bunzip2 file1.gz2
bz2cat bz2cat file1.gz2
zip package and compress (archive) files zip file.zip file1 file2
unzip zip -l file.zip ← -l = list for check
unzip file.zip
unzip -t file.zip ← -t = test
lha lha a file.lzh file1 file2
lha t file.lzh
lha x file.lzh
gzcat gzcat file.gz
gzcat file.Z
zcat zcat file.Z
zless file perusal filter for crt viewing of compressed text zless file.gz
zgrep search possibly compressed files for a regular expression zgrep PATTERN file.gz
zegrep search possibly compressed files for a regular expression zegrep “new” test.txt.gz

11
cursuri-linux.ro
zdiff compare compressed files zdiff file1.gz file2.gz
Character

lv a Powerful Multilingual File Viewer / Grep


qkc
nkf Network Kanji Filter [to utf8] nkf -w -Lu --overwrite test.txt
[to euc] nkf -e -Lu --overwrite test.txt
[to sjis] nkf -s -Lw --overwrite test.txt
find . -type f -name "*sh*" -print0 | xargs -0 nkf --
overwrite -w -Lu
iconv Convert encoding of given files from one encoding to iconv -f utf-8 -t sjis test.utf8 > test.sjis
another

12
cursuri-linux.ro

User

useradd create a new user or update default new user Adminuser on RHEL
information useradd -G wheel USER1
Adminiuser on Ubuntu
useradd -m -s /bin/bash -G sudo USER2
useradd -u UID -g GROUP -G GROUP1,GROUP2 -s /bin/bash -d
HOME_DIR LOGIN
useradd -D ← check Default Parameter
adduser add a user to the system
whoami print effective userid whoami
w Show who is logged on and what they are doing. w
who show who is logged on who
who --all
userdel delete a user account and related files userdel -r USER
← (-r, --remove : Files in the user's home directory will
be removed)
vipw edit the password, group, shadow-password or vipw ← edit /etc/passwd
shadow-group file vipw -s ← edit /etc/shadow
passwd change user password passwd
passwd user1
echo "password01" | passwd --stdin user01
passwd -S user1 ← check about the status of the password
passwd -l user01 ← Lock the user
passwd -u user01 ← Unlock
passwd -d user01 ← delete password
chpasswd update passwords in batch mode echo user01:password | chpasswd
echo 'USER:PASS' > tmp.txt ; chpasswd < tmp.txt ; rm -f
tmp.txt
mkpasswd

13
cursuri-linux.ro
chage change user password expiry information chage -l USER ← check
chage -M 90 USER ← the password expires day set 90days
change -d 0 USER ← force a user to change their password
at next login
usermod modify a user account usermod -g GROUP USER
usermod -g GROUP -G SUBGROUP USER
usermod -G SUBGROUP USER
usermod -aG SUBGROUP USER ← add Group
usermod -G SUBGROUP1,SUBGROUP2 USER
usermod -G "" USER
usermod -l USER_NAME_NEW USERNAME_OLD ← change username
usermod -d HOME_DIR_NEW USER_NAME ← change home directory
usermod -u UID USER ← change UID
gpasswd gpasswd -a USER sudo ← add USER to GROUP
gpasswd -r USER sudo ← remove USER from GROUP
chsh change login shell chsh -l ← = cat /etc/shells
chsh -s /bin/bash ← changing shell
chsh -s /bin/bash user01
getent get entries from Name Service Switch libraries getent passwd ← you can check LDAP Users
getent group
getent shadow
pam_tally2 The login counter (tallying) module pam_tally2 -u USER ← check
pam_tally2 -u USER --reset ← reset

14
cursuri-linux.ro

Group

groups print the groups a user is in groups


groups USERNAME
groupadd create a new group groupadd -g GID GROUP
groupadd -g 1100 dev
addgroup add group to the system addgroup [--gid ID] group
groupdel delete a group groupdel GROUP
groupmod change USER's GID groupmod -g GID GROUP
groupmod -g 1501 testgroup1
find / -gid OLDGID -print ← Check the OLD GID
Reference
usermod -aG SUBGROUP USER ← add Group
chgrp change the Group of the file chgrp -R GROUP FILE
vigr edit the password, group, shadow-password or shadow-group file

15
cursuri-linux.ro

File Permissions

chmod change file mode bits chmod 777 TARGET


chmod u+s PROGRAM ← add SSUID(Set User ID)
chown change file owner and group chown USER FILE
chown USER:GROUP FILE
chown -R USER:GROUP DIR ← -R : operate on files and directories recursively

16
cursuri-linux.ro

Etc

finger user information lookup program finger


finger user01
finger -l user01
su change user ID or become superuser su - ← change root user
sudo su - USER -s /bin/bash
su - user1 -c "ssh [email protected] ls -lh /tmp" >>
aaa.txt
sudo execute a command as another user sudo su -
sudo -i
sudo -u USER COMMAND
sudo sh -c 'echo "test" >> /tmp/test.txt'
id print real and effective user and group IDs id USERNAME
last show listing of last logged in users last
last -5 ← last 5 logged in users
last USER
lastlog reports the most recent login of all users or of a lastlog
given user
umask set file mode creation mask umask ← check
umask 022 ← default 666-022=644(rw-r–r–)
umask 002 ← 666-002=664(rw-rw-r–)
umask 000 ← 666-000=666(rw-rw-rw-)

17
cursuri-linux.ro

Network

ip show / manipulate routing, devices, policy routing and ip a ← print ip address


tunnels ip addr ← print ip address
ip r ← Show IP Routing
ip route ← Show IP Routing
ss another utility to investigate sockets ss -lt ← List all Listening TCP Connections
ss -ua ← List all UDP Connections
ss -ltp ← Process Name with Listening TCP
ss -anu
ifconfig configure a network interface ifconfig ← check ip
ifconfig -a ← -a : display all interfaces
ifconfig eth0 up
ifconfig eth0 down
ifdown take a network interface down ifdown eth0
ifdown eth0 && ifup eth0
ifup bring a network interface up ifup eth0
ifdown eth0 && ifup eth0
route show / manipulate the IP routing table route ← show the IP routing table
route -n ← show the IP routing table
route add -net 192.168.10.0 netmask 255.255.255.0 gw
10.50.0.1
route add -host 192.168.0.100 gw 192.168.1.100
route del -net 192.168.10.0 netmask 255.255.255.0
ethtool Display or change ethernet card settings ethtool eth0
ethtool -s eth0 speed 100 duplex full autoneg off
ethtool -s eth0 autoneg on
mii-tool view, manipulate media-independent interface status mii-tool eth0
mii-tool -vv eth0
arp manipulate the system ARP cache arp -n
arp -an ← (-a : Shows the entries of the specified

18
cursuri-linux.ro
hosts.)
arp -d 192.168.xx.xx ← delete arp
nmcli line tool for controlling NetworkManager nmcli d #d=device
nmcli d show ← defail
nmcli c #c=con=connection
nmcli c down eno1
nmcli c up eno1
nmtui
tcpdump dump traffic on a network tcpdump -n port 80 -i any
tcpdump -n not arp and not port 123 and not port 22
tcpdump host 192.168.0.10 -n -w /tmp/20110615.pcap
tcpdump -r /tmp/20110615.pcap ← -r : Read packets from
file
tcpdump -D # NIC LIST

19
cursuri-linux.ro

Check Network Connection

ping send ICMP ECHO_REQUEST to network hosts ping -c 5 -s 1500 192.168.0.1


ping -i 0.5 192.168.0.1 # -i : interval
traceroute print the route packets trace to network host traceroute -n 192.168.0.10
traceroute -T -p 80 192.168.0.10 ← (-T = TCP)
traceroute -U -p 53 192.168.0.10 ← DNS (-U = UDP)
tracepath traces path to a network host discovering MTU along tracepath -n 192.168.0.10 ← UDP
this path *tracepath don't use TCP.
mtr a network diagnostic tool mtr --tcp -P 80 xxxxxx
mtr --udp -P 53 xxxxxx
mtr -rwb xx.xx.xx.xx -c 10 -T -P 443
nmap Network exploration tool and security / port scanner nmap google.com ← Check TCP
nmap -sT -sU -Pn x.x.x.x ← check TPC and UDP
nmap -Pn -sT -p 22 xx.xx.xx.xx ← check Firewall
nmap -Pn -sT -p 22 xx.xx.xx.xx/24 ← check Firewall
nmap -sU -p 161 xxxxxx ← Check UDP
nmap -Pn -p 22 HOST
nmap -p 443 www.google.com
nc Concatenate and redirect sockets nc 192.168.0.10 80 22 ← check TCP
netcat nc -u 192.168.0.100 53 ← check UDP
nc -vz 192.168.0.10 1-1023 ← portscan
nc -v x.x.x.x 22 < /dev/null > /dev/null 2>&1 ||
echo NG
nping nping --tcp -p PORT HOST
nping -c 1 --tcp -p PORT HOST
httping measure the latency and throughput of a webserver
http_ping
hping ,
hping3

20
cursuri-linux.ro
fping fping -g 192.168.0.0/24

21
cursuri-linux.ro

DNS

dig DNS lookup utility dig -h ←help


dig [@global-server] [domain] [q-type]
dig @8.8.8.8 google.com any
dig @8.8.8.8 -x 74.125.235.101
dig google.com mx
dig +trace google.com
dig +trace -x 173.252.120.6
nslookup query Internet name servers interactively nslookup -type=any google.com 8.8.8.8
nslookup google.com 8.8.8.8
nslookup -type=txt google.com
host DNS lookup utility host ← help
host [-t type] [server]
host gmail.com
host x.x.x.x
host -t any google.com 8.8.8.8
host -t mx gmail.com 8.8.8.8
host -t soa gmail.com
-t = specifies the query type
whois client for the whois service whois google.com
nscd name service cache daemon nscd --help
nscd -i hosts ← chache clear
nscd -g ← Print current configuration statistics

22
cursuri-linux.ro

Connection

telnet user interface to the TELNET protocol telnet IP PORT


ssh popular OpenSSH SSH client (remote login program) ssh USER@IP
ssh xx.xx.xx.xx "hostname; netstat -rn |grep 10.110.0"
ssh xx.xx.xx.xx sudo /sbin/reboot
ssh -o "StrictHostKeyChecking no" xx.xx.xx.xx
scp secure copy (remote file copy program) scp test.tar.gz [email protected]:/tmp
the link file copyed as the real file. scp -rp /home/user1 [email protected]:/home
scp -rp /tmp/test1/ [email protected]:/tmp/test2/
rsync popular a fast, versatile, remote (and local) file-copying tool
the link file copyed as the link file.

rsync -avzh --stats --delete /home/user1/ /tmp/user1.bk/


← rsync “/” is very important.
rsync -e ssh -avzh --stats --delete /home/user1/ [email protected]:/home/backup/server1/home/user1/
rsync -e ssh -avzh --stats –-bwlimit=1250 FILE [email protected]:/DIR/ # 1Mbps = 125KBps
ssh-keygen authentication key generation, management and ssh-keygen -t rsa ← generate rsa key pair
conversion ssh-keygen -t rsa -b 4096 -C "" -N "" -f id_rsa
ssh-keygen -R HOST
← Removes all keys belonging to hostname from a
known_hosts file.
sshpass sshpass -p “XXXXXX” ssh x.x.x.x
ssh-copy-id use locally available keys to authorise logins on a remote machine
ssh-copy-id [email protected]
ssh-copy-id -i xxxxx [email protected]
Other method
cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys"

23
cursuri-linux.ro

HTTP

curl popular transfer a URL curl -O http://example.com/images/test.jpg


curl -I http://www.example.com/ ← Only Header
curl -i http://www.example.com/ ← Header and Body
curl --proxy http://proxy.example.com:8080 http://example.com/
wget The non-interactive network downloader. wget http://google.com/
wget -e http_proxy=xx.xx.xx.xx:8080 http://example.com/
wget -e https_proxy=xx.xx.xx.xx:8080 https://example.com/
wget -S --spider http://example.com/ ← Only Header

24
cursuri-linux.ro

FTP

ftp ARPANET file transfer program


lftp Sophisticated file transfer program

25
cursuri-linux.ro

SNMP

snmpwalk retrieve a subtree of management values using SNMP snmpwalk -v 2c -c public localhost sysname
GETNEXT requests snmpwalk -v 2c -c public localhost .1.3.6.1.2.1
snmpget communicates with a network entity using SNMP GET snmpget -v 2c 192.168.0.10 -c public
requests .1.3.6.1.4.1.2021.11.50.0
snmptranslate translate MIB OID names between numeric and textual forms snmptranslate -Tp | less
snmpnetstat display networking status and configuration information snmpnetstat -v 2c -c public -Can localhost
from a network entity via SNMP snmpnetstat -v 2c -c public -Ci localhost
snmpnetstat -v 2c -c public -Cs localhost

26
cursuri-linux.ro

Shell

date print or set the system date and time date --date '10day ago' +"%Y%m%d" → 20061030
date +"%Y%m%d" → 20061030
date +"%H:%M" → 12:47
cp -p FILE FILE.`date +%Y%m%d`
cp -p FILE FILE.`date -d '1day ago' +%Y%m%d`
tr translate or delete characters
cut remove sections from each line of files echo abcdef |cut -c 3-
echo abcdef |cut -c 2-4
sort sort lines of text files sort -t: +1 -n sample.txt
uniq report or omit repeated lines cat access_log.1 | awk {'print $4'} |awk -F: {'print $1$2$3'} |
sort |uniq -c
logger a shell command interface to the syslog(3) logger "test test"
system log module
tee read from standard input and write to xxxx.sh | tee xxxx.log
standard output and files xxxx.sh | tee -a xxxx.log
xxx.sh 2>&1 | tee xxxx.log ← Save standard output and standard
error output to file
basename strip directory and suffix from filenames SHELLNAME=`/usr/bin/basename $0`
SHELLNAME=`/usr/bin/basename $0 .sh`
dirname strip last component from file name DIR=`dirname ${0}`
paste merge lines of files paste -d, test1.txt test2.txt
awk echo "1 2 3 4 5" | awk '{ print $1 "," $3 }'
echo "1 2 : 3 4 : 5" | awk -F: '{ print $2 }'
sed sed -e 's/xxx/XXX/g' input.txt > output.txt
sed -i "s/IPADDR=192.168.0.10/IPADDR=192.168.0.11/g" ifcfg-eth0

27
cursuri-linux.ro
mail send and receive Internet mail
mailx echo test | mail -s "test" -S "smtp=smtp://xx.xx.xx.xx:25" [email protected]
cat test.txt | mail -s "test" -S "smtp=smtp://xx.xx.xx.xx:25" [email protected]
echo "`hostname` `date`" | mail -s "attach test" -a tmp.txt -S smtp=smtp://x.x.xx:25 -r [email protected]
[email protected]
while while : ; do uptime ; sleep 1 ; done
while : ; do uptime >> /tmp/tmp.txt ; sleep 1 ; done
while : ; do ps aux |grep httpd |wc -l ; sleep 1 ; done
for for i in 127.0.0.1 192.168.10.1; do ping -c 2 $i; done
sleep sleep 1
usleep sleep some number of microseconds usleep 1000000 ← 1,000,000 = 1sec
usleep 100000 ← 100,000 = 0.1sec
usleep 10000 ← 10,000 = 0.01sec

28
cursuri-linux.ro
Hardware

dmesg print or control the kernel ring buffer dmesg


dmesg -H -P -T
(-H = --human)(-P = --nopager)(-T = --ctime)
The dmesg time is incorrect.
Timestamps are slowed down because the time the kernel was asleep
is lost.
lsusb List USB devices lsusb
lspci list all PCI devices lspci
nproc print the number of processing units nproc
available grep -c processor /proc/cpuinfo
getconf _NPROCESSORS_ONLN
inxi Display info about all hardware inxi -Fxz
hwinfo Display info about all hardware hwinfo
hwinfo --short
lshw Display info about all hardware lshw -short
“lshw” stands for “List Hardware”. lshw -C cpu <- Display all CPU info
lshw -short -C memory
lshw -short -C disk
lshw -C network
lscpu Display all CPU info lscpu
dmidecode dmidecode -t memory | grep -i size
dmidecode -t memory | grep -i max <- Show maximum memory for the
hardware
dmidecode -t bios <- Display UEFI/BIOS info

29
cursuri-linux.ro

Module

lsmod show the status of modules in the Linux Kernel lsmod


modinfo show information about a Linux Kernel module modinfo MODULENAME
modinfo bnx2
insmod insert a module into the Linux Kernel
rmmod remove a module from the Linux Kernel
modprobe add and remove modules from the Linux Kernel

30
cursuri-linux.ro
HDD

du estimate file space usage du -sh *


du -sh dir/
du -h --max-depth=1
fuser identify processes using files or sockets fuser -mv /mnt/test ← check
fuser -mvk /mnt/test ←(-k : Kill processes)
chroot run command or interactive shell with special root directory
hdparm get/set hard disk parameters
dumpe2fs dump ext2/ext3/ext4 filesystem information
badblocks search a device for bad blocks

31
cursuri-linux.ro
Partition

df report file system disk space usage df -h ← (-h : print sizes in human readable format)
df -BG ← Bigabyte Unite
df -BM ← Megabyte Unite
sfdisk partition table manipulator for Linux sfdisk -l ←(-l : List the partitions of a device.)
fdisk manipulate disk partition table fdisk -l ← ( -l : List the partition tables)
fdisk -l /dev/sdb
fdisk -l -o +UUID
gdisk Interactive GUID partition table (GPT) manipulator
parted a partition manipulation program parted -l ← check partitions
parted /dev/mapper/mpath0
lsblk list block devices lsblk
e2label Change the label on an ext2/ext3/ext4 filesystem

32
cursuri-linux.ro
Swap

mkswap set up a Linux swap area


swapon enable devices and files for paging and swapping swapon -s ← Check
swapon -a
swapon /dev/xvda3
swapoff disable devices and files for paging and swapping swapoff -a

33
cursuri-linux.ro

File Systems

mkfs build a Linux filesystem mkfs -t xfs /dev/sdb1


#you must umount the device before mkfs. mkfs -t ext3 /dev/sdb1
mkfs -t ext4 /dev/sdb1
mkfs.xfs #you must umount the device before mkfs. mkfs.ext4 /dev/sdb1
mkfs.ext4 mkfs.ext3 /dev/sdb1
mkfs.ext3
mkfs2fs create an ext2/ext3/ext4 filesyste mke2fs /dev/sdb1 ← ext2
#you must umount the device before mkfs. mke2fs -j /dev/sdb1 ← ext3
xfs_info xfs_info /dev/sda1
tune2fs adjust tunable filesystem parameters on ext2/ext3/ext4 tune2fs -l /dev/mapper/mpath0
filesystems ← -l : List the contents of the filesystem
superblock.
tune2fs -l /dev/mapper/mpath0 |egrep
"count|interval"
tune2fs -i 0 -c 0 /dev/mapper/mpath0
← -i : interval, -c : mount count
fsck check and repair a Linux filesystem fsck -p /dev/sda1
you must umount the device before fsck. ← -p : Automatically repair (“preen”) the file
for example single usermode and umount. system.
'shutdown -r -F now' is force fsck after reboot.
fsck.ext4 check and repair a Linux filesystem
e2fsck check a Linux ext2/ext3/ext4 file system
resize2fs ext2/ext3/ext4 file system resizer resize2fs /dev/testvg/lvol0

34
cursuri-linux.ro
Data

dd convert and copy a file dd if=/dev/zero of=test_10M bs=1M count=10


dd if=/dev/zero of=test_100M bs=1M count=100
dd if=/dev/zero of=test_1G bs=1M count=1000
dd if=/dev/zero of=temp.bin bs=1 count=0 seek=1G ←
sparse file
sync flush file system buffers
shred overwrite a file to hide its contents, and optionally
delete it

35
cursuri-linux.ro

mount

mount mount a filesystem mount


mount | column -t
mount /mnt/test /dev/sda1
mount -o remount /dev/sda1
mount -t cifs //xx.xx.xx.xx/test /mnt/test -o username=guest,password=
umount unmount file systems umount /mnt/test
umount -f /mnt/test
(-f : Force unmount(in case of an unreachable NFS system))
umount -l /mnt/test
(-l : Lazy unmount.Detach the filesystem from the filesystem hierarchy now )

36
cursuri-linux.ro

Performance

top display Linux processes top -b -n 4 -d 5 ← interval 5sec , 4


times
sar Collect, report, or save system activity information. sar -f /var/log/sa/sa16
sar (cpu,io)
sar -r (memory)
sar -q (Loadaverage)
vmstat LIKE Report virtual memory statistics vmstat 1 ← interval 1sec (cpu, io,
memory, swap)
vmstat 1 5 ← interval 1sec, 5 times (cpu,
io, memory, swap)
iostat Report Central Processing Unit (CPU) statistics and input/output iostat -xtk 1 (cpu, io) ← interval 1sec
statistics for devices and partitions.
mpstat Report processors related statistics. mpstat -P ALL
uptime Tell how long the system has been running. while : ; do uptime ; sleep 1 ; done
while : ; do uptime » /tmp/tmp.txt ;
sleep 1 ; done
w Show who is logged on and what they are doing.
free Display amount of free and used memory in the system free -m ← show output in MB
netstat Print network connections, routing tables, interface statistics, netstat -anp (-a : Show both listening
masquerade connections, and multicast memberships and non-listening sockets.)
netstat -rn (-r : Display the kernel
routing tables.)
iotop simple top-like I/O monitor iotop -b -n 4 -d 15 ← interval 15sec , 4
times
dstat LIKE versatile tool for generating system resource statistics dstat -taf

37
cursuri-linux.ro

Software

make GNU make utility to maintain groups of programs


patch apply a diff file to an original patch -p1 -N < ../xxx.patch
ldd print shared library dependencies ldd BINARY
yum popular an interactive, rpm based, package manager yum repolist ← check enabled repository
yum search STRINGS
yum info PACKAGE ← check rpm version etc
yum install PACKAGE
yum --disablerepo=* --enablerepo=test-repo
repolist
rpm RPM Package Manager rpm -ivh PACKAGE.rpm ← install
rpm -e PACAGE.rpm ← uninstall
rpm -qa --last
apt apt provides a high-level commandline interface for the apt list --installed ← check installed
package management system. package
dpkg dpkg -l ← check installed package
alien alien -d package-x.x.x.rpm
alien -r package-x.x.x.deb
update- update-alternatives --config mta
alternatives
rhn_register rhn_register --nox --
proxy=http://192.168.0.10:9999

38
cursuri-linux.ro

X Window System

startx initialize an X session startx


xhost server access control program for X xhost + ← Access is granted to everyone
xauth X authority file utility

39

You might also like