文件操作
-
讀取一個文件的 11-20 行
nl test.ext | head -n 20 | tail -n 10
nl 命令會列出文件行號
-
管道 | 和 xargs
-
管道 | 表示把管道前的結果(stdout)作為輸入交給管道后的命令取處理,實際就是利用管道進行兩個進程間單向通信
例如:echo "--help" | grep "help" 中,"--help" 是作為grep的輸入
-
xargs涕滋, xargs將其接受的字符串做成后續(xù)命令的一個命令參數來運行
例如:echo '--help' | xargs cat 等價于 cat --help
-
-
文件隱藏屬性扭勉,文件除了rwx還有隱藏屬性
-
chattr [+-=] [Asacdistu] 文件名
例如:文件 +i 這個文件就無法修改刪除了闯团,詳見 man chattr
lsattr 文件名 查看文件隱藏屬性
-
-
文件特殊權限 SUID SGID SBIT
-
SUID(s):執(zhí)行該文件的用戶短暫獲得該文件所有者權限剃氧,只能用在二進制可執(zhí)行文件中
比如 /usr/bin/passwd但指,執(zhí)行這個文件或短暫獲得root權限得以修改密碼文件 /etc/shadow/passwd静袖,
[root@ flash]# ls -l /usr/bin/passwd -rwsr-xr-x 1 root root 59640 Mar 23 2019 /usr/bin/passwd
SGID(s):用于二進制文件執(zhí)行文件時觉鼻,獲得該文件的群組支持用于目錄時,用戶進入該目錄 建立的文件 群組是該目錄的群組 而不是建立文件用戶的群組
-
SBIT(t):只能用于目錄队橙,該目錄下建立的文件和目錄只有 創(chuàng)建者和root 可以刪除該文件
chmod u+s滑凉,g+s,o+t text 或者 chmod 7777 text
-
-
搜索文件
find 直接讀取磁盤信息查找文件喘帚,效率低
type/which 指令名 根據[PATH] 搜索指令文件位置
whereis 文件名 從特定目錄中查找文件 whereis -l 查看搜索目錄
locate 關鍵字 由已建立的數據庫中搜索結果(/var/lib/mlocate)畅姊,文件數據庫每天更新一次(和系統(tǒng)配置有關),手動更新 updatedb(耗時)
磁盤與文件系統(tǒng)管理
-
磁盤格式化:
文件系統(tǒng)格式化時吹由,可以指定 block (最小存儲塊)的大小若未,如果 block 太大,而存儲的文件都是小文件倾鲫,會造成存儲空間的浪費粗合,如果 block 太小,在 inode 中就會記錄太多 block 號乌昔,
文件讀寫性能會降低隙疚,且因為 inode 中存儲 block 的位置大小是有限的,最大可存儲文件大小也是固定的磕道。如果磁盤存儲大文件居多供屉,則 block 大一些,否則小一些溺蕉。不過現(xiàn)在磁盤都很大伶丐,直接 4k 就行了。文件內存存儲在各個 block 中疯特,但是并不是一定在連續(xù)的 block 號中哗魂,如果存儲的跨度過大,讀寫效率會變低漓雅,所以一個文件系統(tǒng)大小不要設置過大录别。
-
常見指令:
blkid:列出系統(tǒng)已經格式化的裝置
dumpe2fs /dev/sdb :查詢 superblock 和 block group 信息朽色,可以查看文件系統(tǒng)的信息,比如 block组题、inode 總個數葫男,剩余個數等等,linux 中每個文件都會占用一個 inode 往踢,superblock 中 group0 中有若干 block
記錄了文件的 inode table 信息,一個 inode 大小一般是 25byte徘层,所以這個磁盤的 inode 個數為 inode table * 4096 / 256df [ahikHTm] 查看文件系統(tǒng)磁盤使用情況
du [ahskm] 查看目錄使用情況
diff -r dir1 dir2 :檢查目錄差異
dd : convert and copy a file峻呕,該命令會挨個扇區(qū)讀取
cpio :copy files to and from archives
iconv :convert text from one character encoding to another
dos2unix/unix2dos:轉換 linux 和 windows 的換行符
netstat - Print network connections, routing tables趣效, interface statistics瘦癌, masquerade connections, and multicast memberships
-
創(chuàng)建文件或目錄:
-
EXT文件系統(tǒng):
-
當創(chuàng)建一個目錄時跷敬,首先系統(tǒng)分配一個 inode 和至少一個 block讯私,inode 記錄這個目錄的權限、屬性西傀,以及那個 block 號斤寇,block 中具體記錄的是目錄中 的 子文件以及子目錄的 inode 和 文件名,所以一般目錄大小為一個 block拥褂。
但是并不是每個目錄大小都是 1個 block娘锁,如果目錄中文件太多了,則會超過 一個 block(一般是4096)例如: [root@ usr]# ls -dl /usr/bin drwxr-xr-x 2 root root 36864 Apr 28 15:26 /usr/bin
-
創(chuàng)建一個文件類似于創(chuàng)建一個目錄饺鹃,
1. 確定用戶對于當前目錄的權限 2. 根據 inode bitmap 找到未使用的 inode 3. 根據 block bitmap 找到未使用的 block莫秆,將數據寫入 block ,并更新 inode 中的 block 指向這些 block 4. 更新 superblock 的內容以及 inode bitmap 和 block bitmap 只不過文件的 block 中記錄的是數據悔详,并且要注意 inode 中記錄的 block 可能存在多級指向問題镊屎,也就是說 inode 中指向的 block 中記錄的不是文件內容,而是 block 號茄螃,那些 block 號中才記錄著文件內存缝驳,inode 中最多有 12 個一級指向。 可以看出归苍,文件名并不記錄在 inode 中党巾,而是記錄在目錄的 block 中。
-
XFS文件系統(tǒng):和 EXT 思路類似霜医,只是 inode 和 block 是動態(tài)產生齿拂,不是格式化的時候就生成,xfs_info 查看 superblock
-
-
硬盤掛載
查看分區(qū)狀態(tài)肴敛,lsblk署海,blkid吗购,parted(可以查看分區(qū)的格式)
磁盤分區(qū):根據 parted 查看格式,如果是 GPT 用 gdisk砸狞,如果是 MBR 用 fdisk捻勉,
格式化(建立文件系統(tǒng)):mkfs.ext4 或者 mkfs -t ext4
文件系統(tǒng)檢驗:xfs_repair fsck.ext4
掛載與卸載:mount / unmount
磁盤文件參數修訂:mknod(修改硬件裝置(b、c刀森、p)的 major 和 minor)踱启, xfs_admin/tune2fs 修改 UUID 和 Lable Name
設置開機掛載:修改配置文件 /etc/fstab,修改完成輸入 mount -a 驗證配置格式正確研底,否則可能會開機失敗
大文件也可以用loop的方式建立文件系統(tǒng)并重新掛載埠偿,建立 swap(內存不夠時將內存數據存放在磁盤的swap中,格式化:mkswap 啟動:swapon
可以使用 parted 一條命令完成磁盤的分區(qū)
文件壓縮榜晦、打包冠蒋、備份
- 文件擴展名在 linux 中沒什么作用,但是不同壓縮指令的壓縮技術不同乾胶,一般還是用后綴來區(qū)分
-
linux 常見的壓縮文件擴展名如下:
.Z compress .zip zip .gz gzip .bz2 bzip2 .xz xz .tar tar(打包程序抖剿,不壓縮)
-
對應壓縮指令如下
gzip [-cdtv] 文件名 , gunzip 或 gzip -d 解壓 (zcat/zmore/zless) 可以查看壓縮文件內容识窿,(egrep)可以過濾壓縮文件內容
bzip2 [-cdkzv] 文件名斩郎, (bzcat/bzmore/bzless/bzgrep)
xz [-dtlkc] 文件名, (xzcat/xzmore/xzless/xzgrep)
-
打包:tar
壓縮方式選項:z(gzip) j(bzip2) J(xz)
其他選項:v(可視化)喻频,f(文件名)孽拷,c(建立打包文件),x(解包)半抱,p(保留文件原有屬性脓恕,常用于備份),--exclude=filname(不包含)
例如:打包窿侈、壓縮(gzip壓縮):tar -zcvf filename.tar.gz srcfiles (-f 選項 務必寫在最后炼幔,后面解析為文件名)
查詢:tar -ztvf filename.tar.gz 解包、解壓縮:tar -zxvf filename.tar.gz -C dstdir
-
Bash
linux 下默認使用的 shell
-
功能:
記錄歷史命令在~/.bash_history
tab 聯(lián)想史简、補全
alias 命令別名
job control乃秀、foreground、background
shell 腳本
通配符圆兵,例如 ls 可以使用正則來匹配文件名
type 指令名可以查看指令的類型
-
變量
變量賦值用等號連接跺讯,切兩邊不能有空格
變量值如果有空格,可以用 單引號(特殊字符解析為文本殉农,不處理)刀脏,雙引號(特殊字符保留原本特性,比如 $ 會解析變量)超凳,或者轉義字符 \
-
指令嵌套可以用 `指令` 或者 $(指令)愈污,例如:
gdb -p \`ps -a | grep procname\` gdb -p $(ps -a | grep procname)
變量增加內容
PATH=${PATH}:/var/lib
或者PATH="$PATH":/var/lib
耀态, 取消變量使用為unset
關鍵字export
關鍵字可以將變量導出為環(huán)境變量-
常見變量
列出環(huán)境變量 env
列出所有變量 set
$ 也是一個變量,代表該 shell 的進程 ID
PS1暂雹, 命令提示符
? 存儲上一次指令的執(zhí)行返回值
Bash特殊符號.png
- 常見指令:
- bash 指令可以在當前 shell 創(chuàng)建一個新的子shell首装,父shell休眠,exit退出
- read varName: 讀取鍵盤輸入賦值給 varName杭跪, declare/typeset [-aixr] 變量名仙逻,指定類型(bash 中默認判定變量為字符串)
- ulimit: get and set user limits
- stty -a :查看目前環(huán)境的快捷鍵列表
- 數組變量:直接使用 arr[1]=a, 也可以先用 declare -a arrName 涧尿, 先指定數組類型再使用
```
注意:shell 下的數組下標從 1 開始系奉, 不是從 0 開始
```
- 變量的刪除和取代:
- 刪除:`#` 刪除最短的那個 `${PATH#/*local/bin:}`, `##` 刪除最長的那個 `${PATH##/*:}`现斋, `%` 從后往前刪除內容 `${PATH%:*bin}`
- 替換:`/ ${PATH/sbin/SBIN}`喜最, 用 SBIN 替換 sbin 偎蘸, `//`全部替換 `${PATH//sbin/SBIN}`
![Bash變量刪除替換.png](https://upload-images.jianshu.io/upload_images/13593096-010925ea8c29610a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![Bash變量特殊賦值方式.png](https://upload-images.jianshu.io/upload_images/13593096-9c8a7f3e9998cfa3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
```
[root@ ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
[root@ ~]# echo ${PATH#/*local/bin:}
/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
[root@ ~]# echo ${PATH##/*:}
/snap/bin
[root@ ~]# echo ${PATH%:*bin}
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
[root@ ~]# echo ${PATH/sbin/SBIN}
/usr/local/SBIN:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
[root@ ~]# echo ${PATH//sbin/SBIN}
/usr/local/SBIN:/usr/local/bin:/usr/SBIN:/usr/bin:/SBIN:/bin:/usr/games:/usr/local/games:/snap/bin
```
-
Bash shell 操作環(huán)境
-
路徑和指令的搜索順序
以相對或絕對路徑執(zhí)行指令
由 alias 找到該指令執(zhí)行
由 bash 的內建(builtin)指令執(zhí)行
根據 PATH 的路徑找到第一個執(zhí)行的位置
-
環(huán)境配置文件
login-shell
- 讀取 /etc/profile (全局環(huán)境配置文件)庄蹋, 才會讀取 - 讀取個人配置文件,順序如下迷雪,讀取到一個就停止 ~/.bash_profile -> ~/.bash_login -> ~/.profile限书,一般這些文件中也會讀取 ~/.bashrc
nonlogin-shell : 直接讀取 ~/.bashrc
-
-
數據流重定向
command [1>(stdout) 2>(stderr) 2>&1(stderr 重定向給 stdout)] outputFile , 將 command 執(zhí)行結果輸出到 outputFile 中(會覆蓋原有內容)章咧, >> 表示不覆蓋文件中的原有內容倦西, 追加到文件中
stdin : command [< <<] inputFile , cat > file1 會將標準輸入存入文件file1中赁严,cat > file1 < file2 扰柠, 則會將file2的內容作為標準輸入存入文件file1
-
命令執(zhí)行判斷依據:
;
分隔命令 , cmd1 && cmd2疼约, cmd1 || cmd2 卤档, 都依賴于 $?(上一個指令的返回值)例: ls dir && echo "exist" || echo "not exist"
-
管道命令(pipe)
| , 相當于把前一個命令的 stdout 作為 stdin 傳給后一個命令程剥,注意后一個命令一定要能夠接受 stdin
cut 對一行中的數據進行分解
grep劝枣, 取出包含存在信息的那一行
sort,排序 例:ls -al | sort
uniq织鲸, 只顯示一個
wc [-lwm] 舔腾, 統(tǒng)計有多少行、字(英文單字)搂擦、字符
tee : read from standard input and write to standard output and files
-
字符轉換:
tr - translate or delete characters 稳诚, col — filter reverse line feeds from input , join - join lines of two files on a common field 瀑踢, paste - merge lines of files 采桃, expand - convert tabs to spaces split - split a file into pieces懒熙, With no FILE, or when FILE is -普办, read standard input. 合并:cat file* >> totalFile xargs - build and execute command lines from standard input工扎, 例:cut -d ':' -f 1 /etc/passwd | head -n 3 | xargs -n 1 id
正則表達式和文件格式化處理
-
正則表達式
linux中的正則表達式.pnggrep 命令支持正則表達式
-
sed - stream editor for filtering and transforming text
例如:nl file | sed '2,5d' 用 sed 將 2-5 行的顯示刪除 [root@ temp]# ifconfig lxcbr_mgt lxcbr_mgt: flags=4163<UP衔蹲,BROADCAST肢娘,RUNNING,MULTICAST> mtu 1500 inet 192.168.152.128 netmask 255.255.255.0 broadcast 192.168.152.255 inet6 fe80::3c83:bbff:fe2d:634b prefixlen 64 scopeid 0x20<link> ether 3e:83:bb:2d:63:4b txqueuelen 1000 (Ethernet) RX packets 23989 bytes 3564278 (3.5 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 32230 bytes 33123567 (33.1 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 [root@ temp]# ifconfig lxcbr_mgt | grep "inet " | sed 's\^.*inet\\g' | sed 's\ *netmask.*$\\g' 192.168.152.128
-
正則表達式的延伸舆驶,用 egrep 或者 grep -E
linux中的正則表達式延申.png
-
文件的格式化與相關處理
printf 也是一個指令
-
awk: 相比較于 sed 作用于一整行數據的處理橱健,awk 傾向于將整行數據分成數個字段來處理, 一般形式為 awk '條件1{動作1} 條件2{動作2} ...' filename沙廉, 也可以接收標準輸出
awk內建變量.png[root@ amd64_installer]# last -n 5 root pts/0 192.168.152.1 Thu Aug 19 13:44 still logged in root pts/2 192.168.152.1 Thu Aug 19 13:44 still logged in root pts/3 192.168.152.1 Thu Aug 19 10:17 - 13:28 (03:10) root pts/0 192.168.152.1 Thu Aug 19 08:51 - 13:28 (04:36) reboot system boot 4.15.0-112-gener Thu Aug 19 08:50 still running wtmp begins Sun Jun 28 17:16:02 2020 # 打印 [root@ amd64_installer]# last -n 5 | awk '{print $1 "\t lines: " NR}' root lines: 1 root lines: 2 root lines: 3 root lines: 4 reboot lines: 5 lines: 6 wtmp lines: 7 # 帶邏輯判斷 但是第一行未生效 [root@ amd64_installer]# cat /etc/passwd | awk '{FS=":"} $3 < 10 {print $1 "\t" $3}' root:x:0:0:root:/root:/bin/bash daemon 1 bin 2 sys 3 sync 4 games 5 man 6 lp 7 mail 8 news 9 # BEGIN 從第一行就開始生效 [root@ amd64_installer]# cat /etc/passwd | awk 'BEGIN{FS=":"} $3 < 10 {print $1 "\t" $3}' root 0 daemon 1 bin 2 sys 3 sync 4 games 5 man 6 lp 7 mail 8 news 9 [root@ amd64_installer]# # 帶條件動作 [root@ temp]# cat awk_learn.txt Name 1st 2nd 3th hgz 100 200 300 zzz 99 999 9999 hgzzz 88 888 8888 [root@ temp]# cat awk_learn.txt | awk 'NR==1{printf "%-10s %-10s %-10s %-10s %-10s"拘荡, $1, $2撬陵, $3珊皿, $4, "Total\n"} \ > NR>=2{total=$2+$3+$4; printf "%-10s %-10d %-10d %-10d %-10.2f\n"巨税, $1蟋定, $2, $3草添, $4驶兜, total}' Name 1st 2nd 3th Total hgz 100 200 300 600.00 zzz 99 999 9999 11097.00 hgzzz 88 888 8888 9864.00 [root@ temp]#
-
文件對比工具 diff - compare files line by line(還可以比較目錄差異),cmp - compare two files byte by byte
利用 diff 指令可以生產 patch 文件远寸,結合 patch - apply a diff file to an original 指令可以恢復文件
pr - convert text files for printing抄淑,文件打印控制相關
shell 腳本
-
注意事項
文件最好以 .sh 結尾,并且要有 rx 權限
第一行為 #!/bin/bash 宣告這個腳本使用哪種 shell
-
script執(zhí)行方式的差異(source驰后, sh/bash script肆资, ./script,. script)
直接使用絕對路徑或者相路徑執(zhí)行(./script)倡怎, 或者 sh/bash script 執(zhí)行腳本迅耘, 創(chuàng)建一個子 shell 執(zhí)行這個腳本
source 或者 . , 在當前 shell 環(huán)境中執(zhí)行
test - check file types and compare values 指令可以用來做文件的校驗(是否存在监署、屬性颤专、內容), 數據比較(整數數值钠乏、字符串內容)等測試用途栖秕, 在腳本中比較常用
[] 也可以用來判斷, 用法類似 test 晓避, 但是 [] 中的每個組件都要用空格隔開簇捍, 一般配置條件語句去使用
shell 腳本中的參數只壳,
$0
為腳本文件名,$1 $2 ....
依次為調用腳本時傳入的參數暑塑,$#
為用戶入參個數吼句,$@
為"$1" "$2" "$3"
.... ,$*
為"$1$2$3$4"
-
條件判斷事格, 一般一個 [] 寫一個條件判斷惕艳, 用 || 或者 && 連接多個判斷表達式
if [ 條件判斷 ]; then 條件成立執(zhí)行 elif [ 條件判斷 ]; then 條件成立執(zhí)行 else 條件不成立執(zhí)行 fi case $variable in "case1") 滿足case1執(zhí)行 ;; "case2) 滿足case2執(zhí)行 ;; *) 其他情況執(zhí)行 ;; esac
-
function 功能
- 語法
function funcname() { 腳本代碼 }
-
注意事項:
函數在使用之前必須定義
1
* $# 的含義和 shell 腳本中的含義一致,和參數相關
-
循環(huán)
-
while 循環(huán)驹愚, condition 成立時執(zhí)行
while [ condition ] do 循環(huán)體 done
-
until 循環(huán)远搪, 執(zhí)行到 condition 成立, 其實就是不成立時執(zhí)行
until [ condition ] do 循環(huán)體 done
-
for 循環(huán)逢捺, var 依次等于 con1 con2 con3 去執(zhí)行循環(huán)體
for var in con1 con2 con3... do 循環(huán)體 done for var in $(seq 1 100) do 循環(huán)體 done for var in {1..100} # bash 內建機制 do 循環(huán)體 done for ((初始值; 限制值; 執(zhí)行步階)) do 程序段 done
-
-
shell 腳本調試谁鳍, sh 命令
sh -n
只檢查語法, 不執(zhí)行腳本sh -x
將執(zhí)行過程打印出來sh -v
先將 shell 腳本輸出
linux賬號管理和ACL權限設定
-
Linux 賬號和群組
-
UID 和 GID 標識一個用戶劫瞳,系統(tǒng)用的也是 UID 和 GID
[root@ shell_script]# id uid=0(root) gid=0(root) groups=0(root) [root@ shell_script]# id root uid=0(root) gid=0(root) groups=0(root) [root@ shell_script]#
-
/ect/passwd 存儲用戶名等信息 man 5 passwd
[root@ shell_script]# cat /etc/passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin [root@ shell_script]# man 5 passwd PASSWD(5) File Formats and Conversions PASSWD(5) NAME passwd - the password file DESCRIPTION /etc/passwd contains one line for each user account倘潜, with seven fields delimited by colons (“:”). These fields are: · login name · optional encrypted password · numerical user ID · numerical group ID · user name or comment field · user home directory · optional user command interpreter
-
/ect/shadow 存儲密碼信息 man 5 shadow
[root@ shell_script]# cat /etc/shadow root:$6$BZ7lregP$g.ph7e12WqK/iZjLtlc4xR.O16iDSYi.wWgm3xLML06Il7VUYkWwIjfoQfr4RX3TiF1Vcdd9vzwTYJ8ZambNt.:18441:0:99999:7::: 各字段含義如下 login name It must be a valid account name, which exist on the system. encrypted password Refer to crypt(3) for details on how this string is interpreted. If the password field contains some string that is not a valid result of crypt(3)柠新, for instance ! or *窍荧, the user will not be able to use a unix password to log in (but the user may log in the system by other means). This field may be empty辉巡, in which case no passwords are required to authenticate as the specified login name. However恨憎, some applications which read the /etc/shadow file may decide not to permit any access at all if the password field is empty. A password field which starts with an exclamation mark means that the password is locked. The remaining characters on the line represent the password field before the password was locked. date of last password change The date of the last password change, expressed as the number of days since Jan 1郊楣, 1970. The value 0 has a special meaning憔恳, which is that the user should change her password the next time she will log in the system. An empty field means that password aging features are disabled. minimum password age The minimum password age is the number of days the user will have to wait before she will be allowed to change her password again. An empty field and value 0 mean that there are no minimum password age. maximum password age The maximum password age is the number of days after which the user will have to change her password. After this number of days is elapsed, the password may still be valid. The user should be asked to change her password the next time she will log in. An empty field means that there are no maximum password age净蚤, no password warning period钥组, and no password inactivity period (see below). If the maximum password age is lower than the minimum password age, the user cannot change her password. password warning period The number of days before a password is going to expire (see the maximum password age above) during which the user should be warned. An empty field and value 0 mean that there are no password warning period. password inactivity period The number of days after a password has expired (see the maximum password age above) during which the password should still be accepted (and the user should update her password during the next login). After expiration of the password and this expiration period is elapsed今瀑, no login is possible using the current user's password. The user should contact her administrator. An empty field means that there are no enforcement of an inactivity period. account expiration date The date of expiration of the account程梦, expressed as the number of days since Jan 1, 1970. Note that an account expiration differs from a password expiration. In case of an account expiration橘荠, the user shall not be allowed to login. In case of a password expiration屿附, the user is not allowed to login using her password. An empty field means that the account will never expire. The value 0 should not be used as it is interpreted as either an account with no expiration, or as an expiration on Jan 1哥童, 1970. reserved field This field is reserved for future use.
-
/etc/group 存儲用戶組信息
- 用戶可以加入多個群組挺份,在使用已存在的文件時,用戶擁有全部加入群組的權限贮懈。但是在創(chuàng)建文件時匀泊,新文件的群組是屬于有效群組的优训,使用命令 groups 輸出的第一個群組既是有效群組,使用指令 newgrp 切換有效群組各聘,這個指令會新建一個子 shell 進行后續(xù)操作揣非。
[root@localhost /]# man 5 group GROUP(5) Linux Programmer's Manual GROUP(5) NAME group - user group file DESCRIPTION The /etc/group file is a text file that defines the groups on the system. There is one entry per line, with the following format: group_name:password:GID:user_list The fields are as follows: group_name the name of the group. password the (encrypted) group password. If this field is empty躲因, no password is needed. GID the numeric group ID. user_list a list of the usernames that are members of this group妆兑, separated by commas.
-
/etc/gshadow
[root@localhost etc]# man 5 gshadow GSHADOW(5) File Formats and Conversions GSHADOW(5) NAME gshadow - shadowed group file DESCRIPTION /etc/gshadow contains the shadowed information for group accounts. This file must not be readable by regular users if password security is to be maintained. Each line of this file contains the following colon-separated fields: group name It must be a valid group name, which exist on the system. encrypted password Refer to crypt(3) for details on how this string is interpreted. If the password field contains some string that is not a valid result of crypt(3)毛仪, for instance ! or *搁嗓, users will not be able to use a unix password to access the group (but group members do not need the password). The password is used when an user who is not a member of the group wants to gain the permissions of this group (see newgrp(1)). This field may be empty, in which case only the group members can gain the group permissions. A password field which starts with a exclamation mark means that the password is locked. The remaining characters on the line represent the password field before the password was locked. This password supersedes any password specified in /etc/group. administrators It must be a comma-separated list of user names. Administrators can change the password or the members of the group. Administrators also have the same permissions as the members (see below). members It must be a comma-separated list of user names. Members can access the group without being prompted for a password. You should use the same list of users as in /etc/group.
-
-
賬號管理
-
指令
-
useradd [-u uid] [-g gid] [-d homepath] [-s shell]
- 新建用戶會默認新建一個同名群組 - useradd -D 顯示用戶添加的默認值箱靴,這些值來源于 /etc/default/useradd腺逛, 另外還會參考 /etc/login.defs - 用戶的 home 目錄復制來源于 /etc/skel
passwd [--stdin] [賬號名], 新創(chuàng)建的用戶是沒有設定密碼的衡怀,這個指令可以修改密碼棍矛,以及密碼相關屬性,例如密碼生存周期
chage 也可以修改密碼相關的屬性
usermod 修改用戶相關屬性
userdel 刪除用戶
id 查詢 uid gid
finger 查詢用戶信息
chfn 修改 finger 中顯示的內容
chsh 修改用戶使用的 shell
groupadd抛杨, 新建群組
groupmod够委, 修改群組相關屬性
groupdel, 刪除群組怖现,需要群組內沒有用戶存在
gpasswd茁帽, 設置群組密碼和管理員,或者有群組管理員用來管理群組成員
-
-
-
ACL(Access Control List)
ACL可以針對單一使用者屈嗤,單一目錄潘拨、文件來進行 rwx 的管理, 需要文件系統(tǒng)去支持該特性
-
指令
-
setfacl - set file access control lists
# 設定指定用戶test1對于文件的權限 [root@localhost ~]# setfacl -m u:test1:r test # 設定指定群組group1對于文件的權限 [root@localhost ~]# setfacl -m g:group1:r test # 設定文件的 mask饶号, 設定的權限要和 mask 做與操作铁追,相當于最大權限 [root@localhost ~]# setfacl -m m:r test # 設定指定群組group1對于文件的權限, 使用 d 選項表示設置默認屬性茫船,在目錄下的文件會繼承ACL默認屬性 [root@localhost ~]# setfacl -m d:g:group1:r dir
-
getfacl - get file access control lists
[root@localhost ~]# ll total 0 -rw-r--r--+ 1 root root 0 Aug 26 16:24 test [root@localhost ~]# getfacl test # file: test # owner: root # group: root user::rw- user:test1:r-- group::r-- mask::r-- other::r--
-
-
切換用戶
-
su - run a command with substitute user and group ID琅束,
選項
-
或者-l
表示使用 login-shell 的方式切換用戶,bash 的一些相關配置會重新加載算谈, 如果不用這些選項涩禀,切換以后用戶環(huán)境不會變化選項
-c
可以只執(zhí)行一次指令 su - -c "cat /etc/passwd"root 可以隨意切換用戶而不用輸入密碼
-
sudo, sudoedit — execute a command as another user
sudo [-b 后臺執(zhí)行] [-u username] 指令
-
用戶能不能使用 sudo 指令要看 /etc/sudoers 文件中的配置濒生,一般使用專用指令 visudo 去修改這個文件
# User privilege specification # 含義為 用戶名 登錄主機來源(可切換的身份:可切換的群組) 可執(zhí)行的指令 root ALL=(ALL:ALL) ALL # Members of the admin group may gain root privileges %admin ALL=(ALL) ALL # 在該文件中還可以使用別名來簡化文件書寫 # 用戶別名 User_Alias USERS = user1埋泵, user2, user3 #主機別名 Host_Alias HOSTS = smtp栈戳, smtp2 # 指令別名 ! 表示該指令不可用诞挨,還可以在指令中用正則表達式 Cmnd_Alias CMDS = !/usr/bin/passwd, !/usr/bin/passwd root设拟, /usr/bin/passwd [A-Za-z]* # 使用別名指定權限 USERS HOSTS=(root:root) CMDS
-
-
特殊的shell和PAM模塊
特殊的 shell雁社, /usr/sbin/nologin浴井, 擁有該類shell 的用戶無法登錄,但是可以使用系統(tǒng)資源
-
PAM(Pluggable Authentication Modules) - for Linux霉撵, Linux-PAM is a system of libraries that handle the authentication tasks of applications (services) on the system.
修改密碼的流程: 1. 用戶調用 /usr/bin/passwd 2. passwd 調用 PAM 3. PAM 模塊到 /etc/pam.d/ 找到和 passwd 同名的配置文件 4. 根據 /etc/pam.d/passwd 配置磺浙,引用 PAM 模塊逐步分析驗證 5. PAM 調用結果傳回給 passwd 6. passwd 繼續(xù)處理
具體 PAM 配置文件的格式 可以參考
man 5 pam.d
-
用戶查詢、檢查相關指令
w - Show who is logged on and what they are doing.
who - show who is logged on
last徒坡, lastb - show a listing of last logged in users
lastlog - reports the most recent login of all users or of a given user
write user [tty] — send a message to another user
pwck - verify integrity of password files
pwconv撕氧, pwunconv, grpconv喇完, grpunconv - convert to and from shadow passwords and groups
chpasswd - update passwords in batch mode
進階文件管理系統(tǒng)
-
Quota
用于文件系統(tǒng)資源分配問題伦泥, 可以限制包括群組、用戶锦溪、目錄的最大磁盤配額不脯。 例如在郵箱系統(tǒng)中, 限制每個用戶的郵箱存儲大小
-
使用限制
在 EXT 文件系統(tǒng)中僅能針對整個 filesystem刻诊,不能針對目錄防楷,所以要先搞清楚文件系統(tǒng)的支持情況。
Linux 核心必須支持 Quota
對 root 來說不起作用则涯,僅對一般用戶有效
若啟用 SELinux复局,不是所有的目錄都可以使用 quota,SELinux 會加強某些細節(jié)的文件權限
-
Quota 的限制項目
分別針對群組是整、用戶或者目錄
容量限制(block)或者文件數量(inode)限制
柔性規(guī)勸和硬性規(guī)定(soft/hard): 超過 hard 限制就會鎖住該用戶的磁盤使用權肖揣,超過 soft 低于 hard 一般給出告警民假,并給予一個寬限時間(grace time)
-
寬限時間(grace time): 超過這個時間 soft 變?yōu)?hard浮入,鎖住磁盤
quota.png
-
磁盤陣列(Redundant Arrays of Independent Disks,RAID)
RAID_0(等量模式羊异,stripe 性能最佳): 將數據分割成不同條帶(Stripe)分散寫入到所有的硬盤中同時進行讀寫事秀。多塊硬盤的并行操作使同一時間內磁盤讀寫的速度提升N倍,但是任一磁盤損壞可能導致所有數據無法讀取野舶。
RAID_1(映像模式易迹,mirror 完整備份): 原理是把一個磁盤的數據鏡像到另一個磁盤上,也就是說數據在寫入一塊磁盤的同時平道,會在另一塊閑置的磁盤上生成鏡像文件睹欲,在不影響性能情況下最大限度的保證系統(tǒng)的可靠性和可修復性上,只要系統(tǒng)中任何一對鏡像盤中至少有一塊磁盤可以使用,甚至可以在一半數量的硬盤出現(xiàn)問題時系統(tǒng)都可以正常運行窘疮,當一塊硬盤失效時袋哼,系統(tǒng)會忽略該硬盤,轉而使用剩余的鏡像盤讀寫數據闸衫,具備很好的磁盤冗余能力涛贯。雖然寫入效率不佳,但是讀出時由于有備份的存在蔚出,依然會有所優(yōu)化弟翘,主要是備份功能。
RAID0+1/RAID1+0: 結合 RAID_0 和 RAID_1 的優(yōu)點:數據除分布在多個盤上外骄酗,每個盤都有其物理鏡像盤稀余,提供全冗余能力,允許一個以下磁盤故障趋翻,而不影響數據可用性滚躯,并具有快速讀/寫能力,至少需要四個磁盤嘿歌。
spare disk(預備磁盤): 當磁盤陣列中有磁盤損壞時掸掏,spare disk會加入磁盤陣列,將損壞的磁盤移除宙帝,并立即重建數據系統(tǒng)丧凤。
-
可以分為硬件磁盤陣列和軟件磁盤陣列
硬件磁盤陣列:通過磁盤陣列卡達成數組的目的,卡上由專門的芯片處理RAID任務步脓,性能好愿待,但是價格高,且操作系統(tǒng)需要相關驅動程序來支持磁盤陣列卡靴患。
-
軟件磁盤陣列:通過軟件仿真數組任務仍侥,對于 cpu 和 I/O 總線消耗更高。例如:centos 的 mdadm鸳君,只要由兩個以上的分區(qū)槽就可以使用軟件磁盤陣列农渊,指令見
man mdadm
.
RAID.png
-
LVM(Logical Volume Manager 邏輯卷管理)
-
本質上是一個虛擬設備驅動,是在內核中塊設備和物理設備之間添加的一個新的抽象層次或颊。它可以將幾塊磁盤(物理卷砸紊,PhysicalVolume)組合起來形成一個存儲池或者卷組(VolumeGroup)。LVM可以每次從卷組中劃分出不同大小的邏輯卷(LogicalVolume)創(chuàng)建新的邏輯設備囱挑。底層的原始的磁盤不再由內核直接控制醉顽,而由LVM層來控制。對于上層應用來說卷組替代了磁盤塊成為數據存儲的基本單元平挑。LVM管理著所有物理卷的物理盤區(qū)游添,維持著邏輯盤區(qū)和物理盤區(qū)之間的映射系草。LVM邏輯設備向上層應用提供了和物理磁盤相同的功能,如文件系統(tǒng)的創(chuàng)建和數據的訪問等唆涝。但LVM邏輯設備不受物理約束的限制悄但,邏輯卷不必是連續(xù)的空間,它可以跨越許多物理卷石抡,并且可以在任何時候任意的調整大小檐嚣。相比物理磁盤來說,更易于磁盤空間的管理啰扛。
LVM.png LVM 注重的是文件系統(tǒng)的彈性調整容量嚎京。
-
指令:pvcreate -> vgcreate -> lvcreate
LVM指令.png 容量變更: 主要是將 lv 的容量變更,只要 vg 容量足夠就可以擴容隐解,使用指令為 lvresize鞍帝, 然后使用 xfs_growfs 對文件系統(tǒng)擴容,目前 EXT 支持縮小煞茫,xfs不支持帕涌。
-
定時任務
-
at
at and batch read commands from standard input or a specified file which are to be executed at a later time.
-
處理只執(zhí)行一次的任務,依賴于 atd 服務续徽,如果任務有 stdout 或者 stderr 會發(fā)郵件
systemctrl (enable | restart | status) atd/crond
[root@ /]# at now + 1 minute at> echo "hello" > /dev/pts/2 # at執(zhí)行和終端環(huán)境無關 at> ^C[root@dwqiu etc]# [root@ /]# at now + 1 minute at> echo "hello at" at> <EOT> job 2 at 2021-09-03 16:09 [root@ /]#
用戶權限問題:查找 /etc/at.allow /etc/at.deny 中查看用戶是否可以使用該功能蚓曼,原則是如果 /etc/at.allow 存在,則只有其中的用戶可以使用钦扭, 如果 /etc/at.deny 存在纫版,則其中用戶不能使用,都不存在只有 root 能使用客情。
atq: 查看
atrm: 刪除
batch 也是調用 at其弊,不過會選擇在系統(tǒng)不忙碌的時候去執(zhí)行任務,而不是指定時間
-
crontab
處理循環(huán)執(zhí)行的任務膀斋,依賴于 crond 服務梭伐,如果任務有 stdout 或者 stderr 會發(fā)郵件
/etc/cron.allow /etc/cron.deny 和 at 類似
/var/spool/cron 中記錄設置的任務,且以用戶名分文件存儲仰担,
crontab -e
產生的任務存儲在這里糊识,一般個人化的任務放在這個文件里面/etc/crontab 中存儲著系統(tǒng)的定時任務,如果要增加系統(tǒng)性的任務惰匙,直接編輯該文件
/etc/cron.d/* 中的任務也會定時執(zhí)行技掏,如果是自己開發(fā)軟件,則可以將任務放在該目錄下
-
用法: crontab [-u username] [-l(list) | -e(edit) | -r(remove)]
cron -e.png[root@ mail]# crontab -e 1 # Edit this file to introduce tasks to be run by cron. 2 # 3 # Each task to run has to be defined through a single line 4 # indicating with different fields when the task will be run 5 # and what command to run for the task 6 # 7 # To define the time you can provide concrete values for 8 # minute (m)项鬼, hour (h), day of month (dom)劲阎, month (mon)绘盟, 9 # and day of week (dow) or use '*' in these fields (for 'any').# 10 # Notice that tasks will be started based on the cron's system 11 # daemon's notion of time and timezones. 12 # 13 # Output of the crontab jobs (including errors) is sent through 14 # email to the user the crontab file belongs to (unless redirected). 15 # 16 # For example, you can run a backup of all your user accounts 17 # at 5 a.m every week with: 18 # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/ 19 # 20 # For more information see the manual pages of crontab(5) and cron(8) 21 # 22 # m h dom mon dow command 23 # 添加這一行 每分鐘輸出一次 hello 24 */1 * * * * echo "hello" > /dev/pts/1
-
anacron
和 crontab 和 at 不同,anacron 是一個程序而不是一個服務龄毡,crontab 和 at 是定時執(zhí)行任務吠卷,一旦這個時間過了而沒有執(zhí)行任務,是不會再執(zhí)行的(比如正好要執(zhí)行的時候斷電了沦零,再重啟則不會執(zhí)行任務)祭隔,而 anacron 則會去執(zhí)行這個任務。
/etc/anacrontab 配置了要執(zhí)行的任務(可以設置執(zhí)行周期(hour)和延時(分鐘)等)路操,anacron 的原理是會將任務執(zhí)行的時間戳存儲疾渴,再次激活時檢查上次任務執(zhí)行的時間和系統(tǒng)時間差值決定是否執(zhí)行任務,而激活的操作在 /etc/cron.hourly 里面屯仗,每小時執(zhí)行一次搞坝。
-
流程:
- crond 服務每分鐘主動讀取 /etc/cron.d/0hourly
- 執(zhí)行 /etc/cron.hourly
- 執(zhí)行 /etc/cron.hourly/0anacron, 每小時執(zhí)行 anacron
- 根據 /etc/anacrontab 執(zhí)行其中的配置
進程管理和SELinux
-
進程
-
進程:在 linux 中魁袜,觸發(fā)任何一個時間桩撮,系統(tǒng)都會將它定義成一個進程,并且賦予一個PID峰弹,同時按照觸發(fā)這個進程的用戶給與進程相應的權限
proc文件.png 一些常駐的進程稱為服務(daemon)店量, 一般名字都是以 d 結尾, 例如 crond atd ssd 等
多人多任務環(huán)境鞠呈,可以在終端中使用 Alt+[F1-F7] 切換 tty
-
-
job control
在我們登陸 bash shell 以后垫桂,在一個終端下同行進行多個任務的行為管理,每個任務其實都是當前 bash 的子進程粟按。
-
job 分為 foreground job 和 background job诬滩, 在使用指令時加上 & 可以使得任務進入 background 執(zhí)行,但是這類任務一般都是自動執(zhí)行的灭将,不需要交互疼鸟。
指令 &
將指令在后臺執(zhí)行, stdout stderr 仍然會輸出庙曙,可以將其重定向到文件中ctrl + z
:將正在執(zhí)行的指令改為 background 并暫停-
jobs
顯示當前執(zhí)行的 job空镜,+
表示最近添加的 job,-
則是倒數第二個捌朴,其它的不會有符號[root@ hgz]# jobs [1]+ Stopped vi test.c [2]- Running find / -name "*.html" > /hgz/find.log 2>&1 &
fg + %jobnum
吴攒, 可以將job切換到前臺操作, jobnum 也可以是+ -
沒有指定則是+
那個jobbg
可以把 background 中暫停(ctrl + z)的 job 運行起來kill -signal %jobnum
砂蔽,殺死job洼怔,一定要加%
,否則就是殺死進程nohup
- run a command immune to hangups, with output to a non-tty左驾,可以脫離當前 tty 執(zhí)行
-
進程管理
-
ps
指令查看進程信息-
ps -l
:查看自己的 bash 相關進程F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 4 S 0 2344 2093 0 80 0 - 5433 wait pts/0 00:00:01 bash F:權限 4 表示 root 權限 S: status镣隶, R 運行, S 休眠(可以被signal), D 不可喚醒的休眠(等待I/O))), T 停止, Z 僵尸態(tài) UID/PID/PPID C: cpu 利用率 PRI/NI: 執(zhí)行優(yōu)先級 ADDR/SZ/WCHAN:ADDR表示進程在內存那個位置 - 表示 running, SZ 表示用了多少內存极谊,WCHAN 表示是否在運行 TTY:執(zhí)行終端 TIME:實際執(zhí)行花費的 cpu 時間 CMD:執(zhí)行指令
-
ps aux
:列出內存中所有進程USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND daemon 1465 0.0 0.1 28332 1980 ? Ss 09:58 0:00 /usr/sbin/atd -f root 1480 0.0 0.2 30028 2864 ? Ss 09:58 0:00 /usr/sbin/cron -f USER:進程用戶 PID:進程號 %CPU:cpu使用率 %MEM:內存使用率 VSZ:虛擬內存使用量(Kbytes) RSS:占用固定內存量(Kbytes) TTY:終端 STAT:狀態(tài) START:啟動時間 TIME:在cpu中實際運行時間 COMMAND:指令
pstree
:display a tree of processestop
:觀察進程動態(tài)變化數據kill
- send a signal to a processkillall
- kill processes by name
-
-
進程優(yōu)先級
也就是之前
ps
指令中的PRI、NI
安岂,用戶只可以指定NI
值來修改優(yōu)先級轻猖,PRI
由內核動態(tài)調整,關系為:PRI(new) = PRI(old) + NI域那,NI
值子進程繼承于父進程nice [-n (-20-19)] cmd
:以指定的NI
值執(zhí)行 cmd`renice [number] PID - alter priority of running processes
-
系統(tǒng)資源
free
- Display amount of free and used memory in the systemuname
- print system informationuptime
- Tell how long the system has been running.netstat
- Print network connections, routing tables, interface statistics, masquerade connections, and multicast membershipsdmesg
- print or control the kernel ring buffervmstat
- Report virtual memory statistics
-
-
特殊文件與進程
-
SUID/SGID:在執(zhí)行擁有這些權限的文件時咙边,在程序執(zhí)行期間可以獲得文件所有者的權限,也就是說啟動的進程權限不是調用者權限次员,而是文件所有者權限败许,例如:
passwd
指令[root@ bin]# ll /usr/bin/passwd -rwsr-xr-x 1 root root 59640 Mar 23 2019 /usr/bin/passwd* 用戶在執(zhí)行 passwd 時獲得 root 指令,得以修改 /etc/shaow 文件
/proc/*
中存儲了運行中的進程相關的信息和數據fuser -uv file
- 查看文件被那些進程使用lsof -u usernmae +d dir
:列出打開的全部文件pidof program_nmae
:列出program_nmae
的PID
-
-
SELinux:security enhanced linux
傳統(tǒng)文件權限和賬號關系是
DAC discretionary access control
翠肘,依據文件的 rwx 屬性來判斷用戶權限檐束,但是對于 root 不生效。SELinux 使用MAC mandatory access control
束倍,權限設置的主體不再是用戶被丧,而是進程,可以針對進程設置訪問權限绪妹,并且有一些預設的 policy甥桂,其中存在默認的多個 rule。-
運行模式
安全控制主體為進程
安全控制目標為文件系統(tǒng)的權限
安全控制依據為 policy邮旷,依照某些服務的特性來預指定 policy黄选,policy中還有詳細的規(guī)則,例如限制 httpd 進程只能訪問 /Apache/WWW 目錄婶肩,當然办陷,這些都可以修改
security context
,除了 policy律歼,還要對比主體和目標的security context
是否一致民镜,類似于 rwx可執(zhí)行文件運行時會創(chuàng)建一個進程,進程會根據可執(zhí)行文件的類型(type)獲得一個域(domain)险毁,在 policy 中已經為各個domain制定了規(guī)則制圈,其中的規(guī)則就包括這個domain的進程可以訪問哪些類型(type)的文件
sestatus | getenforce
:獲取 SELinux 運行狀態(tài),包括 enforcing(強制)畔况,permissive(寬容鲸鹦,只提示),disabled(禁用)setenforce [0|1]
: (臨時修改)不能設置禁用跷跪,設置禁用需要修改配置文件 /etc/selinux/config馋嗜,并重啟getsebool/getsebool [-a] [rulename]
:查看規(guī)則是否啟用sesearch [-s domain]
:查看進程domain能夠訪問的文件typechcon [-R] [-t type] file
:修改文件類型restorecon [-Rv] file
:恢復預設類型
系統(tǒng)服務
-
早期的 System V 的 init 管理行為
所有的系統(tǒng)服務啟動腳本都放置在 /etc/init.d/ 底下
腳本的執(zhí)行分為[0-6],各個執(zhí)行等級的腳本通過 /etc/rc.d/rc[0-6]/SXXscript 連接到 /etc/init.d/script域庇,S 為 start 的含義嵌戈,XX為數字覆积,表示啟動順序听皿。
chkconfig
- updates and queries runlevel information for system services
-
systemd 使用的 unit 分類
從 centos 7.x 以后熟呛,改用 systemd 這個啟動服務管理機制
多個服務同時啟動
服務器依賴性的自我檢查,例如服務A依賴服務B尉姨,那么在啟動A時會自動啟動服務B
-
依照服務的功能分類庵朝,將服務定義一個服務單位unit,并分類(service socket target path snapshot timer)
systemd擴展名.png 將多個服務歸類為一個群組(target)
兼容 init 管理行為
-
文件又厉,優(yōu)先級依次升高
/usr/lib/systemd/system
九府,每個服務最主要的啟動腳本設定/run/systemd/system
系統(tǒng)執(zhí)行過程中產生的服務腳本/etc/systemd/system
管理員依據主機系統(tǒng)的需求所建立的執(zhí)行腳本
注意:不要用
kill
去殺死一個正在被systemd
監(jiān)管的程序,否則systemd
會無法繼續(xù)監(jiān)管該程序覆致,用systemctl stop servername
-
systemd + systemctl 指令侄旬,
systemctl [OPTIONS...] COMMAND [NAME...]
systemctl
查看所有服務systemctl list-units --type=service --all
帶選項篩選查看systemctl show 服務
查看服務的屬性systemctl stop 服務
關閉服務systemctl mask 服務
This will link these unit files to /dev/null,這個服務無法再啟動煌妈,可以用unmask
取消systemctl mask XXX.target
對于target
類型的 unit儡羔,使用isolate
命令systemctl poweroff | reboot | suspend(暫停) | hibernate(休眠) | rescue(救援模式) | (emergency)
systemctl list-dependencies --reverse 服務
列出服務間的依賴關系systemctl daemon-reload
Reload the systemd manager configuration,新增服務增加了配置文件需要使用這個指令
/etc/services
- Internet network services list璧诵,存儲服務和端口號的默認對應關系將所有服務狀態(tài)寫入文件
systemctl list-units | awk '{print $1}' | xargs -n 1 systemctl status >> /var/server_status
汰蜘,可以將這個命令設置成定期執(zhí)行任務-
配置文件,以 sshd 為例
[root@ system]# cat sshd.service [Unit] # unit 本身說明和依賴關系說明 Description=OpenBSD Secure Shell server # 說明 After=network.target auditd.service # 該unit在哪些服務之后啟動(非強制) ConditionPathExists=!/etc/ssh/sshd_not_to_be_run [Service] EnvironmentFile=-/etc/default/ssh # 啟動腳本的環(huán)境變量配置文件 ExecStartPre=/usr/sbin/sshd -t # 啟動前額外執(zhí)行的腳本 ExecStart=/usr/sbin/sshd -D $SSHD_OPTS # 啟動腳本 ExecReload=/usr/sbin/sshd -t # 和 systemctl relaod 相關 ExecReload=/bin/kill -HUP $MAINPID KillMode=process # 終止模式(process 終止當前程序 control-group 終止產生的所有程序) Restart=on-failure RestartPreventExitStatus=255 Type=notify RuntimeDirectory=sshd RuntimeDirectoryMode=0755 [Install] WantedBy=multi-user.target # 附掛在哪一個 target 底下 Alias=sshd.service # 別名 [root@ system]#
-
利用 timer 這種 unit 也可以達到定時執(zhí)行任務的功能
前提:一定要啟動
timer.target
-
配置一個 unit之宿,配置一個
.timer
族操,在.timer
中配置時間相關的配置以及要執(zhí)行的 unit 詳情見man systemd.timer
,配置文件在/etc/systemd/system/*.timer
timer.png
日志文件
-
常用日志文件
/var/log/boot.log
開機啟動信息日志/var/log/cron
cron 服務相關日志/var/log/dmesg
開機的硬件檢測過程日志/var/log/lastlog
所有賬號最近登錄時間/var/log/messages
系統(tǒng)發(fā)生的錯誤信息都記錄在這個文件里/var/log/secure
涉及到輸入密碼的程序的登入信息都記錄在這個文件中/var/log/wtmp /var/log/faillog
記錄 正確/錯誤 登入的賬戶信息
-
日志文件記錄方式
軟件自主記錄日志文件
使用
rsyslog.service
統(tǒng)一管理日志文件systemd
管理系統(tǒng)的各種服務比被,也會將服務的啟動等操作日志通過systemd-journald.service
以二進制的形式記錄在內存中色难,再發(fā)送給rsyslog.service
進一步記錄在文件中
-
rsyslog.service
-
配置文件在
/etc/rsyslog.conf
中,配置服務的名稱等缀,服務產生日志的等級和記錄日志的文件位置#rules #add by hgz learning linux *.info /var/log/admin.log auth.=error root # 將 auth 模塊的錯誤日志發(fā)送郵件給 root
syslog服務類型.png
syslog日志等級.png -
配置本機作為日志服務器枷莉,接收網絡日志
# provides UDP syslog reception 需要開啟 UDP 接收日志就開啟底下兩行 #module(load="imudp") #input(type="imudp" port="514") # provides TCP syslog reception 需要開啟 TCP 接收日志就開啟底下兩行 #module(load="imtcp") #input(type="imtcp" port="514")
-
將日志記錄到日志服務器中的配置
*.* @@192.168.1.100 # TCP *.* @192.168.1.100 # UDP
-
-
日志輪換功能 ---
logrotate
將舊的日志文件重命名或刪除,創(chuàng)建一個新的日志文件來重新開始記錄日志
利用
/etc/cron.daily/logrotate
项滑,每天去執(zhí)行日志輪換的腳本-
配置文件在
/etc/logrotate.con /etc/logrotate.d
依沮,可以把/etc/logrotate.con
中的配置理解為全局配置/etc/logrotate.d
中的則是每個日志文件的具體配置[root@ cron.daily]# more /etc/logrotate.conf # see "man logrotate" for details # rotate log files weekly weekly # 全局類型的 # use the syslog group by default, since this is the owning group # of /var/log/syslog. su root syslog # keep 4 weeks worth of backlogs rotate 4 # create new (empty) log files after rotating old ones create # uncomment this if you want your log files compressed #compress # packages drop log rotation information into this directory include /etc/logrotate.d # no packages own wtmp, or btmp -- we'll rotate them here /var/log/wtmp { # 針對每個日志文件的定制配置 missingok monthly create 0664 root utmp rotate 1 } /var/log/btmp { missingok monthly create 0660 root utmp rotate 1 size=10M # 超過10M就輪換,不需要等到monthly compress # 壓縮 sharedscripts # 腳本開始 prerotate # 輪換執(zhí)行之前執(zhí)行這里的shell指令 /usr/bin/chattr -a /var/log/btmp endscript # 腳本結束 sharedscripts postrotate # 輪換執(zhí)行之前執(zhí)行這里的shell指令 # rsyslog reload /bin/kill -HUP `cat /var/run/syslog.pid 2> /dev/null` 2> /dev/null || true /usr/bin/chattr +a /var/log/btmp endscript } # system-specific logs may be configured here
除了定期執(zhí)行枪狂,也可以使用指令來輪換日志文件
ogrotate [-dv] [-f|--force] [-s|--state file] config_file
-
systemd-journald.service
簡介rsyslogd
需要在服務啟動之后才能夠開始記錄日志危喉,而在設備啟動前的日志則是由systemd 啟動 systemd-journald.service
來記錄,記錄在 ram 中州疾,掉電丟失日志記錄在文件
/run/log
中辜限,實際就是運行內存中配置文件
/etc/systemd/journald.conf
-
指令
journalctl - Query the systemd journal
logger - enter messages into the system log
[root@ log]# logger -p user.info "I am hgz" [root@ log]# journalctl SYSLOG_FACILITY=1 -n 3 -- Logs begin at Sun 2020-06-28 17:16:17 CST, end at Sat 2021-09-11 16:21:27 CST. -- Sep 11 16:21:27 simulator_pro root[2972]: I am hgz
開機流程,模塊管理和Loader
- Linux 的開機流程
- 載入 BIOS 的硬件信息與進行自我測試严蓖,并依據設置取得第一個可開機的設備薄嫡;
- 讀取并執(zhí)行第一個開機設備內 MBR 的 boot Loader (亦即是 grub2, spfdisk 等程序) 氧急;
- 依據 boot loader 的設置載入 Kernel ,Kernel 會開始偵測硬件與載入驅動程序毫深;
- 在硬件驅動成功后吩坝,Kernel 會主動調用 systemd 程序,并以 default.target 流程開機哑蔫;
- systemd 執(zhí)行 sysinit.target 初始化系統(tǒng)及 basic.target 準備操作系統(tǒng)钉寝;
- systemd 啟動 multi-user.target 下的本機與服務器服務;
- systemd 執(zhí)行 multi-user.target 下的 /etc/rc.d/rc.local 文件闸迷;
- systemd 執(zhí)行 multi-user.target 下的 getty.target 及登陸服務嵌纲;
- systemd 執(zhí)行 graphical 需要的服務