Command lines in Linux
Monday, August 5, 2019
Documents:
- Type "passwd" : change current password.
- Type "passwd <user_name>: change password of user name.
- Type "passwd -S <user_name>": check account lock or unlock.
- Type "passwd -l <user_name>": lock user.
- Type "passwd -u <user_name>": unlock user.
or
- Type "cat /etc/shadow | grep -i <username"
Result:
username:$1$.... :unlocked.
username:!!$1$..... : locked.
2. "Chage" command line.
- Type "chage -l <username>": view account information.
Output:
Last password change : Jan 10, 2012
Password expires : never
Password inactive : never
Account expires : never
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7
-- change expire password, expire account...
#chage <account>
=> this command will be ask one by one for setting
or
#chage -I -1 -m 0 -M 99999 -E -1 <account>
=> this command will auto setting by parameter
3. "ping" command line.
- ping <destination> : sent packet to destination server with endless times.
- ping -i <interval_count> <destination>: sent packet to destination server with interval time.
- ping -s <size_packet> <destination> : sent packet to destination server with size packet (bytes).
- ping -c <number_packet> <destination> : sent packet to destination server with number packet.
- ping -D <destination> : show timeslap each line.
4. SVN command line
Before type command below, please cd to svn working space.
-- start svn service
#svnserve -d -r <repository_location>
-- kill svnserve
#ps auxww | fgrep svnserve
#kill <process id>
--Check out
#svn checout --username <username> --password <password>
--Update
#svn update --username <username> --password <password>
--check info
#svn info
-- Create repoz
#svnadmin create /repos_path
-- Change repoz information
/respo/passwd: set password for user
/respo/authz: add/remove/edit user
Note:
If you got when sync or update,... with "svn: Can't find a temporary directory: Internal error" . Check write permission in "/tmp" dir of your server.
Ref: http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.checkout.html
5. Set JAVA_HOME variable
export JAVA_HOME=jdk-install-dir
export PATH=$JAVA_HOME/bin:$PATH
6. Start/stop oracle db
// check ORACLE_HOME
#echo $ORACLE_HOME
// if ORACLE_HOME variable not set, please set it
#export ORACLE_BASE=/home/oracle/app/oracle
#export ORACLE_HOME=$ORACLE_BASE/product/11.2.0/dbhome_1
#export PATH=$PATH:$ORACLE_HOME/bin
#export ORACLE_SID= 'SID NAME';
# go to oracle install dicrectory
cd /home/oracle/app/oracle/product/11.2.0/dbhome_1/bin
-- start listener
# lsnrctl start
--start db
#dbstart
-- stop listener
# lsnrctl stop
--stop db
#dbshut
--check status
#lsnrctl status
#sqlplus / AS SYSDBA
-- change the maximum dump file size
Ref: http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.checkout.html
5. Set JAVA_HOME variable
export JAVA_HOME=jdk-install-dir
export PATH=$JAVA_HOME/bin:$PATH
6. Start/stop oracle db
// check ORACLE_HOME
#echo $ORACLE_HOME
// if ORACLE_HOME variable not set, please set it
#export ORACLE_BASE=/home/oracle/app/oracle
#export ORACLE_HOME=$ORACLE_BASE/product/11.2.0/dbhome_1
#export PATH=$PATH:$ORACLE_HOME/bin
#export ORACLE_SID= 'SID NAME';
# go to oracle install dicrectory
cd /home/oracle/app/oracle/product/11.2.0/dbhome_1/bin
-- start listener
# lsnrctl start
--start db
#dbstart
-- stop listener
# lsnrctl stop
--stop db
#dbshut
--check status
#lsnrctl status
#sqlplus / AS SYSDBA
-- change the maximum dump file size
Ref: https://docs.oracle.com/cd/B19306_01/server.102/b14237/initparams116.htm#REFRN10103
SQL > alter system set MAX_DUMP_FILE_SIZE='200m';
7. head command line
"head" is print a number of data of given output.
-- print first 10 line
#head test.txt
--print the first N lines.
#head -n 100 test.txt
--print the first N bytes.
#head -c 256 test.txt
-- print line from 2 files
#head -q test1.txt test2.txt
--print line from N to M.
head -n 20 | tail -10
8. Grep
#grep "keywork" "file"
-- don't distinct UPPER CASE and lower case
#grep -i "keyword" "file"
-- find with case sensitive
#grep -w "keyword" "file"
-- find and show line before/after your search.
#grep - <A,B or C> n "keyword" "file"
A: after lines
B: before lines
C: around of the match line.
n: number of the line is show.
-- find a keyword on sub folder.
#grep -r "keywordd" "file"
--find all result not contain keyword.
#grep -v "keyword" "file"
--count results.
#grep -c "keyword" "file"
--just show file name in result.
#grep -l "keyword" "file"
--show the line number in result
#grep -n "keyword" "file"
--find PID of a program
#grep -ef | egrep 'keyword1|keyword2|keyword3'
7. head command line
"head" is print a number of data of given output.
-- print first 10 line
#head test.txt
--print the first N lines.
#head -n 100 test.txt
--print the first N bytes.
#head -c 256 test.txt
-- print line from 2 files
#head -q test1.txt test2.txt
--print line from N to M.
head -n 20 | tail -10
8. Grep
#grep "keywork" "file"
-- don't distinct UPPER CASE and lower case
#grep -i "keyword" "file"
-- find with case sensitive
#grep -w "keyword" "file"
-- find and show line before/after your search.
#grep - <A,B or C> n "keyword" "file"
A: after lines
B: before lines
C: around of the match line.
n: number of the line is show.
-- find a keyword on sub folder.
#grep -r "keywordd" "file"
--find all result not contain keyword.
#grep -v "keyword" "file"
--count results.
#grep -c "keyword" "file"
--just show file name in result.
#grep -l "keyword" "file"
--show the line number in result
#grep -n "keyword" "file"
--find PID of a program
#grep -ef | grep java
--Find and delete N files
$find . -name '*.aud' -print0 | xargs -n1000 -0 rm -f
9. Check Java Memory
-- go to JDK folder
cd <jdk>/bin
-- find PID of Java
ps -ef | grep java
-- check JAVA heap
jmap -heap <PID>
10. Check phycial memory, swap
-- check memory
# grep MemTotal /proc/meminfo
-- check swap
# grep SwapTotal /proc/swaps
11. Check file system information (df - disk filesystem)
-- display all disk filesystem
#df
-- display all file system
#df -a
-- display stored used of system.
#df -h
--display stored used of a folder.
#df -h /tmp
-h: show Gb.
-m: show Mb
-k: show Kb:
12.Check/config IP address
On Redhat 7
-- show IP info
#ip addr show
-- show network interface
#nmcli -p dev
-- set IP address
#vi /etc/sysconfig/network-scripts/ifcfg-<interface_name>
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTTPROTO=DHCP
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=enp0s3
ONBOOT=yes //yes if you want to connect Internet.
IPADDR=x.x.x.x
PREFIX=32
GATEWAY=x.x.x.x
DNS1=x.x.x.x
DNS2=x.x.x.x
//CentOS 6
9. Check Java Memory
-- go to JDK folder
cd <jdk>/bin
-- find PID of Java
ps -ef | grep java
-- check JAVA heap
jmap -heap <PID>
10. Check phycial memory, swap
-- check memory
# grep MemTotal /proc/meminfo
-- check swap
# grep SwapTotal /proc/swaps
11. Check file system information (df - disk filesystem)
-- display all disk filesystem
#df
-- display all file system
#df -a
-- display stored used of system.
#df -h
--display stored used of a folder.
#df -h /tmp
-h: show Gb.
-m: show Mb
-k: show Kb:
12.Check/config IP address
On Redhat 7
-- show IP info
#ip addr show
-- show network interface
#nmcli -p dev
-- set IP address
#vi /etc/sysconfig/network-scripts/ifcfg-<interface_name>
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTTPROTO=DHCP
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=enp0s3
ONBOOT=yes //yes if you want to connect Internet.
IPADDR=x.x.x.x
PREFIX=32
GATEWAY=x.x.x.x
DNS1=x.x.x.x
DNS2=x.x.x.x
//CentOS 6
DEVICE="p4p1" HWADDR="00:22:19:09:4D:3C" NM_CONTROLLED="yes" ONBOOT="yes" # Interface enabled BOOTPROTO="static" #Assigning in static mode IPADDR=192.168.1.11 #IP address NETMASK=255.255.255.0 # Subnet Mask GATEWAY=192.168.1.1 # Default Gateway DNS1=8.8.8.8 #Primary DNS DNS2=4.2.2.2 #Secondary DNS
and then restart network
//on Redhat
#systemctl restart network
//on Centos
#systemctl start NetworkManager.service#systemctl stop NetworkManager.service
#systemctl restart NetworkManager.service
//using nmcli
#nmcli networking off
#nmcli networking on
#nmcli networking on
Note:
Oracle VMwareMap network interface
1. Device > Setting > Network:
Adapter 1 > Attach to: Host only adapter. > select VM Network Interface.
13. Enable SSH
on REDHAT7
-- check SSH
#systemctl status sshd
#systemctl enable sshd
#firewall-cmd --zone=public --permanent --add-service=ssh
-- restart ssh service
#
service sshd restart
14. Remove file/directory
--remove dir with confirm prompt
#rm -r <directory_name>
-- remove dir without confirm prompt
#rm -rf <directory_name>
15. Create/Modify for user, group.
/etc/shadow: show the password of user, user group
/etc/group: show all group
# ls -l file
-rw-r--r-- 1 root root 0 Nov 19 23:49 file
type of file | owner(rw-) | group (r--) | other (r--)
Option:
+ : add more permission
- : remove permission
= : change permisson
-- change file permission
#chmod 640 <file_name>;
--change owner file
#chown <user> <file_name>;
options: -r : change owner for files and sub folder.
-- add execute permission to file owner.
#chmod u+x file_name;
--add read/write to group
chmod g+rw file_name
--remove write permission to other.
chmod o-w file_name
-- we change usr owner, group and other.
chmod u=rwx,g=rx,o= file_name
--create user
#useradd <user_name> <options>
# ls -l file
-rw-r--r-- 1 root root 0 Nov 19 23:49 file
type of file | owner(rw-) | group (r--) | other (r--)
Option:
+ : add more permission
- : remove permission
= : change permisson
-- change file permission
#chmod 640 <file_name>;
--change owner file
#chown <user> <file_name>;
options: -r : change owner for files and sub folder.
-- add execute permission to file owner.
#chmod u+x file_name;
--add read/write to group
chmod g+rw file_name
--remove write permission to other.
chmod o-w file_name
-- we change usr owner, group and other.
chmod u=rwx,g=rx,o= file_name
--create user
#useradd <user_name> <options>
// Create user with default home/<username>
# useradd -m USERNAME
// Create user with specific home
#useradd -m USERNAME -d /Path
Option:
-p <password>
-- Modify user
-add group
#usermod -a -G <group> <user>
# useradd -m USERNAME
// Create user with specific home
#useradd -m USERNAME -d /Path
Option:
-p <password>
-- Modify user
-add group
#usermod -a -G <group> <user>
-- modify primary group
#usermod -g <user> <group>
-- delete user
#userdel -r <user_name>
Option:
-r : remove also user's home directory
-f: removal in case the user is logged
-- change group owner ship of file.
-- Make a user to ADMIN user
#usermod -g <user> <group>
-- delete user
#userdel -r <user_name>
Option:
-r : remove also user's home directory
-f: removal in case the user is logged
-- change group owner ship of file.
#chgrp <group_name> <file_name>
-- add User Group, Group Id, Change Group, Del Group
#groupadd <group_name>
#groupmod -g 601 <group_name>
#usermod -G <group1, group2,...> <user_id>
#groupdel <group>
-- Change home directory
#usermod -d /home/<user_home> <user_id>
-- Change Shell
#usermod -s /bin/bash <user_id>
#usermod -s /bin/nologin <user_id>
$usermod -aG wheel <user_name>
-- Change script of a user (User Login)
$ usermod -s /sbin/nologin <username>
--Make a use
16. Check System information
====Redhat 7=======
--show kernel
#uname -a
-- show name and version of distribution
#head -n1 /etc/issue
--Make a use
16. Check System information
====Redhat 7=======
--show kernel
#uname -a
-- show name and version of distribution
#head -n1 /etc/issue
-- check centos version
#hostnamectl
--show all partition that registered on system
#cat /proc/partitions
--show Total memory
#grep MemTotal /proc/meminfo
--show CPU
#grep "model name" /proc/cpuinfo
-- show info about disk
#hdparm -i /dev/sda
====Redhat 7=======
17. Set session timeout
/etc/ssh/ssh_config
ClientAliveInterval 120
ClientAliveCountMax 720
18. Secure log
-- these log for accessing, changed password of users.
Probably in /var/log/auth.log on Debian, or /var/log/secure on Redhat
19. Set time/date
Set date from the command line
date +%Y%m%d -s "20200202"
Set time from the command linedate +%T -s "12:00:00"
Set time and date from the command linedate -s "19 APR 2012 11:14:00"
View Real-time date time
watch -n 1 date
View Real-time with command
watch <command>
#hostnamectl set-hostname <new-host-name>
21. set sFTP for only users
On CentOS
--key gen
#ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /home/gis/.ssh/id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/gis/.ssh/id_rsa.
Your public key has been saved in /home/gis/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Wtrl4sVFLG10qpNUWcSB8C7BZswkD7C2XKs+WMug9Xk root@centos-test
The key's randomart image is:
+---[RSA 2048]----+
| ..o o.o*=. |
| . O *oo. |
| o . @ B |
| o o = O |
| o S * o |
| o .* + + |
| o *+oo + |
| . ..*.Eo |
| .o. |
+----[SHA256]-----+
#Copy and past public key to /home/<user>/.ssh/authorized_keys file. (you also add many public keys)
# Get private key input to Firezilla > Edit > Setting > SFTP > add private key to there.
Ref:
1. https://blog.tinned-software.net/setup-sftp-only-account-using-openssh-and-ssh-key/
2. https://blog.tinned-software.net/ssh-passwordless-login-with-ssh-key/
Note: when you ssh key for connecting but failed, please check permission of user like that:
Ref: https://unix.stackexchange.com/questions/311408/passwordless-ssh-is-not-working-in-centos-7/388649
/home/username
drwxr----x. 18 username groupname 4096 May 11 11:52 username
/home/username/.ssh
268823097 drwx------ 2 username groupname 29 May 11 11:53 .ssh
/home/username/.ssh/authorized_keys
-rw-r----- 1 username groupname 402 May 11 11:53 authorized_keys
22. Override and append
ll -al /folder > text.txt
ll -al /folder >> text.txt
23. Yum, NPM
Install, check software in:
-- Install DNS
$yum install bind
24. Config host deny and allow
// deny host and protocol
vi /etc/host.deny
//allow host and protocol
vi /etc/host.allow
Ex:
telnetd:ALL:deny
sshd:ALL:deny
ftpd:ALL:deny
Note:
ALL: ALL
This denies all service to all hosts, unless they are permitted access by entries in the allow file.
ALL: ALL
This denies all service to all hosts, unless they are permitted access by entries in the allow file.
25. SNPM
Simple Network Management Protocol (SNMP) is an Internet Standard protocol for collecting and organizing information about managed devices on IP networks and for modifying that information to change device behavior. Devices that typically support SNMP include cable modems, routers, switches, servers, workstations, printers, and more
#show running snmp
#redhat
ps -ef| egrep snmp
lsof -i :199
#stop snmp
kill -9 <PID>
service snmpd stop
#start snmp
service snmpd start
#check config
chkconfig snmpd off (<= redhat 6)
systemctl disable snmpd.service (>= redhat 7)
#Config file
vi /etc/snmp/snmpd.conf
option:
-- allow all ip income.
rocommunity !snmp_shb*nms
26. Find world-writable files
#find / -perm -2 -ls
27. automount service
--find automount service
#ps -ef | grep automount
or
#ps -ef | grep autofs
-- turn off/on automount service
#chkconfig autofs off (for Rhat 6)
#systemctl disable autofs.service (for Rhat 7)
27. finger service
Desc:
A finger service is running on this host. The finger protocol is used to
find out information about users on a remote system. Finger servers can
usually provide either a list of logged-in users or detailed
information on a single user.
Finger information has been frequently used by crackers as a way to initiate a social engineering attack on a company's computer security system. By using a finger client to get a list of a company's employee names, email addresses, phone numbers, and so on, a cracker can telephone or email someone at a company requesting information while posing as another employee.
Finger information has been frequently used by crackers as a way to initiate a social engineering attack on a company's computer security system. By using a finger client to get a list of a company's employee names, email addresses, phone numbers, and so on, a cracker can telephone or email someone at a company requesting information while posing as another employee.
--find finger service
#ps -ef | grep inetd
--kill process
#kill -HUP [PID]
--config finger
#vi /etc/inetd.conf
finger stream tcp nowait bin /usr/lbin/inetd -s (we can comment this as disable finger)
LINUX for xinetd
#vi /etc/xinetd.d/finger
--restart xinetd service
#service xinetd restart
#systemctl restart xinetd.service
28. Check file, directory has owner.
#find / -nouser -o -nogroup -xdev -ls 2> /dev/null
29. Make Home dir for exist user.
You want to make home dir for existing user in Linux.
#mkhomedir_helper <username>
30. Disable telnet
# vi /etc/xinetd.d/telnet
service telnet
{
flags = REUSE
socket_type = stream
wait = no
user = root
server = /usr/sbin/in.telnetd
log_on_failure += USERID
disable = yes // change there
}
service telnet
{
flags = REUSE
socket_type = stream
wait = no
user = root
server = /usr/sbin/in.telnetd
log_on_failure += USERID
disable = yes // change there
}
#service xinetd restart
31. init process in Linux
// parent of each process
/etc/inittab
Meaning in the inittab
id:runlevels:action:process
// the script has prefix "S", the system call and run:
/etc/rc.d/init.d/S<command>
// the script has prefix "K", the system call and run:
/etc/rc.d/init.d/K<command>
Run level in /etc/rc.d/
0 : Halt system
1 : Take system to single-user mode (good for Linux system maintenance)
2 : User defined or distribution like Debian use it
3 : Full multi-user mode (text mode login)
4 : Not used/user-defined
5 : Full multi-user GUI mode login
6 : Reboot system
32. rsync (Đồng bộ file, thư mục)
#rsync options source destination
option:
-v : hiển thị kết quả
-r : copy dữ liệu recursively, not sure
-a: chp phép copy dữ liệu recursively, đồng thời giữ nguyên dược tất cả các thông số thư mục và file.
-z: nén dữ liệu trước khi truyền.
--delete : xoá dữ liệu ở destination nếu source không tốn tại dữ liệu đó.
--exclude : loại trừ dữ liệu không muốn truyền đi.
Ex:
#rsync -zvh backup.tar /tmp/backups/
#rsync -avzh /a /b
sync between servers
#rsync -avz backup/ root@192.168.88.165:/home
#rsync -zvzh root@192.168.88.165:/root/data backup/data1
Sync together by SSH
#rsync -avzhe ssh backup.tar root@192.168.0.100/backups/ -- local remote
#rsync -avzhe ssh root@192.168.0.100:/root/install.log /tmp/ -- servers remote
//copy directory
#cp -r <dir_source> <target>
*copy overide without confirm.
# /cp -r <dir> <target>
*copy and not override exist file
#cp -Rn source target
* copy and not override exist file, print message per files (option = v)
#cp -Rvn source target
33. Find cmd
#find /data -name test.txt
#find/data -name test*
34. zip//unzip by gzip/gunzip, tar
#gzip /data/test1.txt
#gunzip /data/test1.txt.gz
--create file tar
#tar -cvf test.tar test.txt
--create tar file for folder "test"
#tar -cvf /home/test.tar /home/test
-- unzip
#tar -vxf test.tar -C /data/
-- create tar.gz
#tar -czvf test.tar.gz test
--List files in tar
#tar -ztvf test.tar.gz
-- Extract tar.gz
#tar -xzvf test.tar.gz
35. lsof
Sometime, you deleted a large file and it not descrease size of folder. please check deleted files.
Because when you deleted a large but the running process is holding it, the file will be not deleted actually.
show delete files
#lsof <path_deleted_file>
#lsof | grep <path_deleted_file>
solution:
#kill -9 <PID>
$ /usr/sbin/lsof | grep deleted
ora 25575(PID) data 33u REG 65,65 4294983680 31014933 /oradata/DATAPRE/file.dbf (deleted)
Resolved: https://access.redhat.com/solutions/2316
36. Kill command
#kill <option> <PID>
Option:
1 (HUP) - Reload a process.
9 (KILL) - Kill a process. (Kill process ngay lập tức)
15 (TERM) - Gracefully stop a process. (Gửi tín hiệu đến tiến trình để kill)
37. top cmd
Top cmd check resources of linux as memory, cpu,...
CPU(s):
1.6%us
0.6% sys
95.5%id: free % of CPU.
//Get percent of CPU
top -bn2 | grep '%Cpu' | tail -l | grep -P '(....|...) id, '|awk '{print "CPU Usage:" 100-$8 "%"}'
top -bn2 | grep '%Cpu' | tail -l | grep -P '(....|...) id, '|awk '{print "CPU Usage:" 100-($8/4) "%"}'
38. crontab
crontab -l : list of crontab
crontab -e : edit crontab
5 * * * * /home/admin/admin_crontab.sh
//edit for another user
crontab -u <user> -e
/etc/cron.allow : allow crontab for users.
/etc/cron.deny : deny crontab of users.
-- Check the user is using the cron tab
$ll /var/spool/cron
39. tcpdump
Capture package in a network interface.
#tcpdump dst <IP_ADDRESS>
-- capture packages and write files.
#tcpdump dst <IP_ADDRESS> and src port 22 -w FILE_NAME.pcap
-- Capture package within range port.
#tcpdump portrange 21-25 -c 9
40. netstat
show all connection on server.
# netstat -nat
# netstart -nat | grep LISTEN
# netstat -nltp
check port and pid using
#netstat -nlp | grep <port>
41. iptable cmd
--list
$ iptable -L
--allow all ip access via port 22
$ iptable -A INPUT -p tcp --dport 22 -j ACCEPT
How to use module extension: -m <extension name> --<properties>
x:
$ iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
42. Setup vsftpd
--install vsftpd
#yum install vsftpd
--edit configuration
#vi /etc/vsftpd/vsftpd.conf
-- restart service
#service vsftpd restart
43. NTP client/ server
#vi /etc/ntp.conf
#service ntpd restart
-- check status of NTP
#ntpq -pn
NTP Settings
# vi /etc/ntp.conf
restrict 192.168.100.0 mask 255.255.255.0 nomodify notrap # Release access restrictions so that local servers can get time information.
#server 0.rhel.pool.ntp.org # All existing servers are not used.
#server 1.rhel.pool.ntp.org
#server 2.rhel.pool.ntp.org
server [NTP server_ip] # Specifies the time-based server in the private network.
Service Registration
# service ntpd start
# chkconfig ntpd on
Check service operation
# ps -ef | grep ntp
Check if time sync
# ntpq -pn
Check for errors
# ntptime | grep returns"
44. du
check size of directory
du -sh path-file
45. Check format of disk
#lsblk -f
Result:
[admin@localhost ~]$ lsblk -f
NAME FSTYPE LABEL UUID MOUNTPOINT
sda
├─sda1 ext4 7b0e08ee-f797-4861-a572-173542fe7740 /boot
└─sda2 LVM2_member 01ZNuF-dhgH-5gQh-wvgO-lWff-3gHH-gSshRM
├─cl-root xfs 35522e98-5618-48a6-a2af-35048a5f3d00 /
└─cl-swap swap 9dbaf491-f737-40b5-a22e-4fd3653d2d98 [SWAP]
sr0
46. Count files
$ find <directory> -type f | wc -l
$ ls -l | wc -l OR $ ls | wc -l
47. Run process in background
When you make a process to do long time, you can put it background process so that do another process
//make background process
$ <command_line> &
//list of background process
$ jobs
$jobs -l
48. Firewall in Centos
When you make a process to do long time, you can put it background process so that do another process
* Zone: least trusted to most trusted
drop > block > public > external > internal > dmz > work > home > trusted
* Rule Performance
runtime-to-permanent : apply for test and lost after reload
runtime-to-permanent : apply for test and lost after reload
permanent: apply permanent and efftect after reload
//Start/stop firewall
#systemctl enable firewalld
#systemctl start firewalld
//Check status
#firewalld-cmd --state
-- Get default zone
#firewall-cmd --get-default-zone
--Get active zone
#firewall-cmd --get-active-zones
--Get all rule
#firewall-cmd --list-all
--Get a list of the available zones
#firewall-cmd --get-zones
-- Get a list of specific zone
#firewall-cmd --zone=home --list-all
--Get a list of the available zone less
#firewall-cmd --list-all-zones | less
-- Changeing the Zone of an Interface (--get-active-zones for check result again)
#firewall-cmd --zone=home --change-interface=eth0
-- Adjusting the default zone
#firewall-cmd --set-default-zone=home
* Setting Rules for Application
-- Get a list of the available service
#firewall-cmd --set-default-zone=home
-- Enable service
#firewall-cmd --zone=public --add-service=http
-- Opening a port for zone
#firewall-cmd --zone=public --add-port=5000/tcp
-- Opening a range port for zone
#firewall-cmd --zone=public --add-port=4990-4999/udp
-- Opening a port for zone
#firewall-cmd --zone=public --list-ports
-- Remove Allow port
#firewall-cmd --zone=public --remove-port=22/tcp
// Create new zone
firewall-cmd --new-zone=mariadb-access --permanent
firewall-cmd --reload
firewall-cmd --get-zones
//Allow specifics ip
firewall-cmd --zone=mariadb-access --add-source=10.24.96.5/20 --permanent
// Allow port
firewall-cmd --zone=mariadb-access --add-port=3306/tcp --permanent
firewall-cmd --reload
// Remove IP
# firewall-cmd --zone=mariadb-access --remove-source=10.24.96.5/20 --permanent
// Remove port
firewall-cmd --zone=mariadb-access --remove-port=3306/tcp --permanent
//Remove Zone
firewall-cmd --permanent --delete-zone=mariadb-access
// Reload
# firewall-cmd --reload
49. Check Java Heap memory
Ref:
$ jps -l
$jcmd <PID> GC.heap_info
$jmap -heap <PID>
50. mysql check
$ SHOW ENGINE INNODB STATUS\G;
$ SHOW FULL PROCESSLIST;
$ SHOW TABLES;
$ SHOW FULL COLUMNS FROM table_name; //show column info
$ DESCRIBE table_name;
# find query slow
$ show global variables like 'slow%log%';
+---------------------+-------------------------------+
| Variable_name | Value |
+---------------------+-------------------------------+
| slow_query_log | ON |
| slow_query_log_file | /var/log/mysql/mysql-slow.log |
+---------------------+-------------------------------+
51. Delete trace file in oracle , GRID Infragstructure
Ref: https://logic.edchen.org/how-to-delete-trace-files-in-oracle/
$ adrci
$ show homes // get all home path
$ set homepath <home_path in command above>
$ set homepath <home_path in command above>
$ show control
ADR Home = /u01/app/grid/diag/crs/node2/crs:
*************************************************************************
ADRID SHORTP_POLICY LONGP_POLICY
LAST_MOD_TIME LAST_AUTOPRG_TIME
LAST_MANUPRG_TIME ADRDIR_VERSION
ADRSCHM_VERSION ADRSCHMV_SUMMARY ADRALERT_VERSION
CREATE_TIME
-------------------- --------------------
-------------------- ----------------------------------------
----------------------------------------
---------------------------------------- --------------------
-------------------- -------------------- --------------------
----------------------------------------
3841422557 720
8760 2015-08-21 16:03:18.127927 +08:00
2018-03-07 10:43:49.850300
+08:00 1 2 82
1 2015-08-21 16:03:18.127927 +08:00
1 rows fetched
$ set control (SHORTP_POLICY = 168)
$ set control (LONGP_POLICY = 672)
$ purge -age 10080 // minus
after *.trc, *.trm will delete on /oracle/diag/rdbms/<INSTANCE>/<SSID>/trace
// Delete log in GRIG infragstructure
Ref:
-- Show access user
$ tfactl access lsusers
-- Add access user
$ tfactl access add -user oracle -local
Syntax:
tfactl managelogs
[-purge [[-older nm|h|d] | [-gi] | [-database all|d1,d2,...]]]
[-show [usage|variation] [[-older nd] | [-gi] | [-database all|d1,d2,...]]]
Example:
-- Show log before purge
$tfactl managelogs -show usage -older 30d -gi
--Purge log
$tfactl managelogs -purge -older 30d -gi
TIPs
1. connection close when use sftp although you input correct password
- Root cause: because the sftp account is expired.
- Check: grep -i <account> /var/log/*
- Solution: change the password of account
2. Files in Linux
/bin, /sbin : chứa các tập tin nhi phân hỗ trợ cho việc boot, thực thi các lệnh
/boot : chứa kernel, file hỗ trợ cho việc load hệ điều hành
/dev " chưa các tập tin thiết bị như CDRom, HDD
/etc: chứa các tập tin cấu hình hệ thống
/home : home directory của user.
/lib : chứa các kernel module, các thư viện chia sẻ cho các tập tin nhị phân trong /bin và sbin
/mnt: chứa các mount point cửa các thiết bị mount vào hệ thống.
/proc : lưu trữ thông tin về kernel, các tiến trình
Ex: Nếu có một tiến trình là PID = 001, bạn có thể check trong /proc/<PID>/
/root: lưu trữ home directory cho user root.
/tmp: chứa các file tmp.
/usr: chứa các chương trình đã được cài đặt
/var: chứa các log file, hàng đợi các chương trình, mailbox của users.
3. Not allow root user access by SSH
#vi /etc/ssh/sshd_config
uncomment PermitRootLogin line
PermitRootLogin yes
4. Grant "su" for another user
Ref: https://www.digitalocean.com/community/tutorials/how-to-create-a-sudo-user-on-centos-quickstart
#usermod -aG wheel username
(By default, on CentOS, members of the
wheel
group have sudo privileges.)#su - username
#su <command-line>
5. Install and config ISCSI
Description: An iSCSI initiator is the client who wishes to access the storage on a target, or server. The IP address of the target needs to be known for this process.
* Install ISCSI Initiator (CentOS)
Packages:
iscsi-initiator-utils-6.2.0.874-19.el7.x86_64.rpm
iscsi-initiator-utils-iscsiuio-6.2.0.874-19.el7.x86_64.rpm
Online install
# yum install iscsi-initiator-utils
Offline install
#rpm -i iscsi-initiator-utils-iscsiuio-6.2.0.874-19.el7.x86_64.rpm iscsi-initiator-utils-6.2.0.874-19.el7.x86_64.rpm
* Config ISCSI Initiator
#vi /etc/iscsi/scsid.conf
Uncomment properites:
node.session.auth.authmehtod=CHAP
node.session.auth.username = username
node.session.authen.password=password
* Restart service
#systemctl restart iscsid
* Discover target
#iscsiadm -m discovery -t sendtargets -p 192.168.1.1
* Connect to the target
#iscsiadm -m node -T iqn.2015-06.com.example:target1 --login
* Find the iSCSI disk name.
#grep "Attached SCSI" /var/log/messages
* Create a file system on that disk.
# mkfs.ext4 /dev/sdb
* Mount the file system.
# mkdir /mnt/iscsiTest
# mount /dev/sdb /mnt/iscsiTest
* Make it persistent across reboots by editing the /etc/fstab file.
# blkid /dev/sdb
*Get information about running sessions:
#iscsiadm -m session -P 3
* Shorter output
# iscsiadm -m session
*Logout session
#iscsiadm -m node -T iqn.2007-06.com.test.geeklab:storage.geeklab --portal 192.168.10.12:3260 -u
* Delete Record ID
When you discover the targets and log into it, the information is stored in the node database found in /var/lib/iscsi. In order to delete the target, we have to delete the target’s record ID out of /var/lib/iscsi:
# iscsiadm -m node -o delete -T iqn.2007-06.com.test.geeklab:storage.geeklab --portal 192.168.10.12:3260
Ref:
6. Create app as service in Linux
Ref:
For Relhat 6.5
1. Create service script in /etc/init.d/rc.d/
$ vi <service_name>
Ex: vi netty
2. Create symlink in /etc/init.d/rc5.d/
ls -s <file> <target>/S##<service_name>
ls -s <file> <target>/K##<service_name>
K: Kill
S: Start
##: Order to run
Ex:
$ ls -s /etc/init.d/rc.d/netty /etc/init.d/rc5.d/S90netty (Start service)
$ ls -s /etc/init.d/rc.d/netty /etc/init.d/rc5.d/K90netty (Kill service)
3. Verify your service
$ service netty start
$ service netty stop
$ service netty status
7. Setup lsyncd in Centos/Redhat
Sync two-way between servers. Make sure SSH was enable on both server.
Server 1: 192.168.1.1
Server 2: 192.168.1.2
Server #1:
Step 1: install EPEL
$ yum install epel-release
$ yum install lsyncd
Step 2: Create account on the server
$ useradd admin
Step 3: Create key on "admin" account.
$ su admin
$ ssh-keygen -t rsa
$ ssh-copy-id admin@192.168.1.2 // copy key from server #1 => server #2
authorized_keys : content public key of server #1.
id_rsa: private key
id_rsa.pub: public key
Step 4: Make folder to sync
$mkdir /email/repl
$mkdir /email/rsync_temp
Step 5: config lsyncd
$vi /etc/lsyncd.conf
settings {
logfile="/var/log/lsyncd/lsyncd.log",
statusFile="/var/log/lsyncd/lsyncd.status",
statusInterval=1,
nodaemon=true,
insist=true
}
sync {
default.rsync,
source ="/email/repl",
target ="admin@172.29.77.32:/email/repl",
delete ='running',
rsync ={
rsh ="/usr/bin/ssh -l admin -i /home/admin/.ssh/id_rsa",
update =true,
_extra ={"--temp-dir=/email/rsync_temp"},
times =true,
archive =true,
compress=true,
perms =true,
acls =true,
owner =true
}
}
Step 6: Modify watches
$ sudo sysctl fs.inotify
fs.inotify.max_queued_events = 16384
fs.inotify.max_user_instances = 128
fs.inotify.max_user_watches = 500000
$ sudo sysctl -w fs.inotify.max_user_watches=50000 // change max user watch
$ /etc/sysctl.conf // you can check again in this file
Step 6: Start/Stop service
$ service lsyncd start
$ service lsyncd stop
$ service lsyncd status
$ tail -f /var/log/lsyncd/lsyncd.log
$ tail -f /var/log/lsyncd/lsyncd.status
Step 7: Repeat from step #1 on server #2.
8. Setting the banner in Centos/Relhat
$ vi /etc/motd
enter your banner in here
when you login to servers by ssh, this will be show
9. how to exit "telnet" in linux, windows
$ quit
10. check open port without telnet command line.
$ nmap -p <port> <ip>
$ nc -zv <ip> <port>
// Check Port Open
$ nmap -sU -p U:<port> <IP or Host>
11. Change /etc/resolv.conf files
Stumbled on this problem on CentOS8.
The file may be marked immutable:
# lsattr /etc/resolv.conf
----i--------------- /etc/resolv.conf
Remove the immutable flag as follows:
# sudo chattr -i /etc/resolv.conf
# lsattr /etc/resolv.conf
-------------------- /etc/resolv.conf
Ref: https://askubuntu.com/questions/604760/can-not-edit-resolv-conf
12. How to change CentOS baseURL from mirror.centos.org to vault.centos.org
# cd /etc/yum.repos.d/
# sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
# sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*
13. Fix error install Virtualbox Addition in Centos
# yum groupinstall 'Development Tools'
14. ip route table (how to use route default ip when you have many interface network)
# ip route list // show default ip routing table
default via 192.168.23.1 dev enp0s3 proto static metric 100
default via 192.168.8.1 dev enp0s8 proto static metric 101
192.168.8.0/24 dev enp0s8 proto kernel scope link src 192.168.8.254 metric 101
192.168.23.0/24 dev enp0s3 proto kernel scope link src 192.168.23.3 metric 100
192.168.122.0/24 dev virbr0 proto kernel scope link src 192.168.122.1 linkdown
#ip route delete default // delete all default
# ip route add default via 192.168.8.1 dev enp0s8 // add defaut route ip
15. Stop nfslock, nfs in redhat 6.9
#/etc/init.d/nfslock stop //process is rpc.statd
#/etc/init.d/nfs stop
16. Error: Terminating sicnce out of inotify watches
$ cat /proc/sys/fs/inotify/max_user_watches
$ sysctl fs.inotify.max_user_watches=400000 // stop lsyncd before change
17. Turn off SELlinux
$vi /etc/selinux/config
$ SELINUX=enforcing => disabled
restart servers
18. Download RPM package with dependencies
$ yum install yum-plugin-downloadonly
$ yum install --downloadonly --downloaddir=<directory> <package-name>
19. Kill many process at one time in Linux
$ pkill -9 crsctl.bin
20. Git command line
$git clone <https_url>
$git add <files|folders
$git commit -m "comment"
$git push --all
$git pull
$git log
$git config --global
$git config -e //edit config
#Discard Local Changes
$ git reset --hard
#Discard Local Changes Specific File Name
$ git checkout <file_name>
21. Use Deploy Keys in Git
- Login to servers
- Make SSH key following the command below:
$ ssh-keygen -t ed25519 -C "USERNAME@EMAIL.com"
or
$ ssh-keygen -t rsa -b 4096 -C "USERNAME@EMAIL.com"
- Key will stored in /home/<user>/.ssh/
1. id_rsa
2. id_rsa.pub
$cat id_rsa.pub // copy and past to Deploy Keys in Git
- Clone project
$ git clone git@****
Note: if you use git clone with http/https, it will prompt enter Username/password.
22. Upgrade CentOS
$ dnf -y install centos-release-stream
$ dnf -y swap centos-{linux,stream}-repos
$ dnf -y distro-sync
23. Change CentOS to Remi Repository
$ yum install epel-release yum-utils -y
$ yum install http://rpms.remirepo.net/enterprise/remi-release-8.rpm
$ dnf module list php //list version of module
$ sudo dnf module enable php:remi-8.0 -y //enble module in redmi module
23. Mount to RHEL DVD to server
// Mount the RHEL installation ISO to a directory like /mnt/disc, e.g.:
# mkdir -p /mnt/disc
# mount -o loop RHEL7.9.iso /mnt/disc
// If you use DVD media, you can mount like below.
# mkdir -p /mnt/disc
#blkid // check disk mount
# mount /dev/sr0 /mnt/disc
// Copy the media.repo file from the root of the mounted directory to /etc/yum.repos.d/ and set the permissions to 0644 or another similar permissions set:
# cp /mnt/disc/media.repo /etc/yum.repos.d/rhel7dvd.repo
# chmod 644 /etc/yum.repos.d/rhel7dvd.repo
#Edit the new repo file, changing the gpgcheck=0 setting to 1 and adding the following 3 lines
vi /etc/yum.repos.d/rhel7dvd.repo
enabled=1
baseurl=file:///mnt/disc/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
To be:
[InstallMedia]
name=DVD for Red Hat Enterprise Linux 7.9 Server
mediaid=1359576196.686790
metadata_expire=-1
gpgcheck=1
cost=500
enabled=1
baseurl=file:///mnt/disc/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
//Clear the cache and check whether you can get the packages list from the DVD repo
# yum clean all
# yum repolist enabled
It should look like the following if no other repository is enabled.
To avoid any corruption its recommend to disable any non-RedHat repositories.
# yum repolist enabled
Loaded plugins: product-id, search-disabled-repos, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
repo id repo name
InstallMedia Red Hat Enterprise Linux 7.9
repolist: 5,229
24. Change Rotate of Logfile (wtmp, btmp)
Change config in here:
$ /etc/logrotate.conf
25. Split Big File by Git Bash
- Open Git Bash
$ cd <your_dir> // Aware path of Windows and Linux
$ split <file_name> -b 500m
26. Edit Network Configuration in RockyOS
$ nmtui
27. Compile C/C++ Code
-- Compile C
$ gcc -c -fPIC hello.c -o hello.o
-- Compile to Shared Object (.so)
$ gcc hello.o -shared -o libhello.so
28. Netstat command in RockyOS
In RockyOS 9.5, default not install netstat command
$ dnf install net-tools
29. Install JDK 8 in CentOS/RockyOS
$ yum -y install java-1.8.0-openjdk
30. Install chkconfig in RockyOS
$ yum install chkcofig
31. Add JAVA_HOME , ANT_HOME in Linx
Option #1: This command effect to user is login.
export ANT_HOME=/path/programz/apache-ant-1.9.16
export PATH=${PATH}:${ANT_HOME}/bin
export JAVA_HOME=/path/programz/jdk1.8.0_202
export PATH=${PATH}:${JAVA_HOME}/bin
Option #2 : Change .bash_profile
$vi .bash_profile
ANT_HOME=/path/programz/apache-ant-1.9.16
PATH=$PATH:$JAVA_HOME/bin
is updating...
Bài liên quan
Comments[ 0 ]
Post a Comment