Linux技巧
find, grep awk, sed tar
# network
hostname
hostnamectl set-hostname server1.example.com
ip a s
nmcli connection show
cat /etc/sysconfig/network-scripts/ifcfg-enp66s0f0
# restart the network.
#systemctl restart NetworkManager
sudo nmcli connection reload && sudo nmcli connection down enp68s0f0 && sudo nmcli connection up enp68s0f0
# restart the network.
# sudo nmcli networking off
# sudo nmcli networking on
sudo ip link set enp66s0f0 down
sudo ip link set enp66s0f0 up
# mtu
ifconfig enp66s0f0 mtu 1500
nmap 172.17.30.108 -p 22 -Pn
# storage
df -hT
lsblk -f
sudo blkid
# mount
## Assuming you have made changes to the /etc/fstab file, you can use the following command to remount the file system
sudo mount -av
# lvm
vgs
vgdisplay
lvs
lvdisplay
# process
ps -ef
pstree -p <pid>
free -m
# find
find /home/ -type f -name "*.sh" | xargs chmod +x
# systemctl
systemctl list-units --all
systemctl --type=service --state=active
systemctl --type=service --state=running
# looking for the service file of a specific service
systemctl cat isc-dhcp-server
# reload all daemon and include Automatically generated by systemd-sysv-generator
systemctl daemon-reload
# rsync
rsync --dry-run -avzh --progress {source} {target}
rsync -avzh --progress {source} {target}
# sed
sed -i 's/172.19.30.157/172.31.56.32/g' *
# ss
ss -tulnp
ss -tulnp | grep :80
# netstat
netstat -tulnp
# curl
curl -v telnet://test:53
# network interface monitor
iftop -i ens192 -B
netstat -I ens192 -w 2
- Linux 上的字串以及命令輸出處理 grep、awk、xargs、sed - Bingdoal's Note
- explainshell
- shell.how
- Practical Shell Patterns I Actually Use
- 你一定用過 htop,但你有看懂每個欄位嗎
- Best Linux Commands For Advanced Hardware and System Info
- 16.04 - Difference between systemctl init.d and service - Ask Ubuntu
- Bash Cheat Sheet | Just for noting
- 最牛B的Linux Shell命令 | plantegg
- Cheat sheet: Old Linux commands and their modern replacements | Opensource.com
- System monitoring utilities | System Analysis and Tuning Guide | openSUSE Leap 15.5
debug
- Linux 效能工具
- Linux 效能工具 - Intermediate
- 是谁杀了我? | 卡瓦邦噶!
- System becomes unresponsive with message "INFO: task {process}:{pid} blocked for more than 120 seconds". - Red Hat Customer Portal
- Why is space not being freed from disk after deleting a file in Red Hat Enterprise Linux? - Red Hat Customer Portal
- [Linux] 權限中黏滯位(sticky bit)的解釋(chmod 1777) - Clay-Technology World
apt
show kernal verion
How To Find Which Linux Kernel Version Is Installed On My System uname -r : Find Linux kernel version cat /proc/version : Show Linux kernel version with help of a special file hostnamectl | grep Kernel : For systemd based Linux distro you can use hotnamectl to display hostname and running Linux kernel version
memory
ps aux pmap gdb strace
ubuntu@ip-172-31-15-167:/var/log$ sudo pmap -d 26264 | sort -g -k 2 | tail
00007f23bb0bd000 15628 ----- 0000000000000000 000:00000 [ anon ]
00007f2405f8c000 25304 r-x-- 0000000000000000 103:00001 libicudata.so.55.1
00007f23b8000000 49908 rw--- 0000000000000000 000:00000 [ anon ]
00007f23cc000000 65232 rw--- 0000000000000000 000:00000 [ anon ]
00007f23c0000000 65524 rw--- 0000000000000000 000:00000 [ anon ]
00007f23e4000000 65536 rw--- 0000000000000000 000:00000 [ anon ]
00007f23d4000000 131072 rw--- 0000000000000000 000:00000 [ anon ]
00007f23dc000000 131072 rw--- 0000000000000000 000:00000 [ anon ]
0000000000ad1000 2446724 rw--- 0000000000000000 000:00000 [ anon ]
mapped: 3279696K writeable/private: 3085236K shared: 28K
ubuntu@ip-172-31-15-167:/var/log$ sudo cat /proc/26264/smaps | grep -A 18 0ad1000
00ad1000-96032000 rw-p 00000000 00:00 0 [heap]
Size: 2446724 kB
Rss: 2446600 kB
Pss: 2446600 kB
Shared_Clean: 0 kB
Shared_Dirty: 0 kB
Private_Clean: 0 kB
Private_Dirty: 2446600 kB
Referenced: 2446356 kB
Anonymous: 2446600 kB
AnonHugePages: 2445312 kB
Shared_Hugetlb: 0 kB
Private_Hugetlb: 0 kB
Swap: 0 kB
SwapPss: 0 kB
KernelPageSize: 4 kB
MMUPageSize: 4 kB
Locked: 0 kB
VmFlags: rd wr mr mw me ac sd
- pmap high memory usage by python script
- [Python] Debug 一支 daemon 狂吃記憶體的問題… 原來是 lxml 搞的鬼
- How to Check Memory Usage Per Process on Linux
character device file
- Creating a character device file - Unix & Linux Stack Exchange
- files - What are exactly mknod command parameters? - Unix & Linux Stack Exchange
grep
remove sparse row
by specific extensions
組合技
複製PE檔案至某個目錄 malicious_pe/md5_fb9d3acc7d067fcea343d3c48d35f887_55296: PE32 executable (console) Intel 80386, for MS Windows
file malicious/* | grep -i 'exe' | awk {'print $1'} | awk -F ':' {'print $1'} | xargs cp -t malicious_pe
找出pdf檔案並在另一個metadata檔案過濾
file malicious/* | grep -i 'pdf' | awk -F ':' '{print $1}' | awk -F '_' '{print $2}' | grep -f - malicious/csv/meta.csv
find
delete files older than specific date
find /path ! -newermt "YYYY-MM-DD HH:MM:SS" | xargs rm -rf
find ./GeoIP_Lite/Release/ -type d ! -newermt "2020-07-01" | xargs rm -rf
find ./GeoIP_Lite/download -mindepth 2 -type d ! -newermt "2020-07-01"
find a or b
rsync
- :star:Continuously Sync Files One-Way on Linux | Baeldung on Linux
- How To Use Rsync to Sync Local and Remote Directories | DigitalOcean
- Linux 使用 rsync 遠端檔案同步與備份工具教學與範例 - G. T. Wang
- How To Use Rsync to Sync Local and Remote Directories
- Rsync over SSH with key authentication
- How to Exclude Files and Directories with Rsync
- How to exclude subdirectory from rsync
- anywhere or not anywhere in the tree
- How to exclude subdirectory from rsync
- shell script - rsync / mv how to skip empty files - Unix & Linux Stack Exchange
將遠端的檔案備份至本地端
rsync -avzh pi@192.168.1.12:/mypath/myfile.gz /mybackup/
rsync -avzh --progress pi@192.168.1.12:/mypath/myfile.gz /mybackup/
sed
shell - How to delete from a text file, all lines that contain a specific string? - Stack Overflow
SED: insert text after the last line? - Unix & Linux Stack Exchange
unix - How to use variables in a command in sed? - Stack Overflow
regular expression - How can I use sed to replace a multi-line string? - Unix & Linux Stack Exchange To handle newline characters, you need to read multiple lines into the pattern space. This is why the command sed ':a;N;$!ba;s/\n/\n/g' works—it reads the entire input into the pattern space before performing the substitution.
sed reads and processes one line at a time. When you use sed 's/\n/\n/g', it doesn't see the newline characters within the lines because it processes each line separately.
#!/bin/bash
# Define the certificate content
CERTIFICATE="-----BEGIN CERTIFICATE-----
MIID0DCCArigAwIBAgIUf0rrp7kWJf1eYRqyBRQzZLBsmkwwDQYJKoZIhvcNAQEL
BQAwaDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAlZBMREwDwYDVQQHDAhOZXcgWW9y
azENMAsGA1UECgwEUXVheTERMA8GA1UECwwIRGl2aXNpb24xFzAVBgNVBAMMDnF1
YXkucG9sYWIuY29tMB4XDTI0MTExMDA3MTIwNloXDTI3MDgzMTA3MTIwNlowaDEL
MAkGA1UEBhMCVVMxCzAJBgNVBAgMAlZBMREwDwYDVQQHDAhOZXcgWW9yazENMAsG
A1UECgwEUXVheTERMA8GA1UECwwIRGl2aXNpb24xFzAVBgNVBAMMDnF1YXkucG9s
YWIuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu+iNCLjyMnB3
0AS4twt9BIqgNaifTCHi/u0bOilwpIWT2vVW92MGqNkHujBoKJFJhRQaaijtFSE1
iRpt8YyEUTXJJbW1nE9iolRJbJ3orkYfyHremQjsVxpKrAzIqEa9cgjmgMLJIj+b
fxqoLR3Hof4+TbNGo8x2wFU1iV/rJgrf/3G10NZXumng4rf0RW1c6wR9y/pnXFML
g8xQuuJSX8DTkw+kLBEQ3EnITQOUDu+25q3YOzhwzD9JIDD1O3/W/arZCc5ffQuS
EwrqahkGDcvVIruuclpBFe5lit6vP5wFexknIQcQFZqe+NfKSO/8Mu4lQ9pRQS5b
im4+APntmQIDAQABo3IwcDALBgNVHQ8EBAMCAuQwEwYDVR0lBAwwCgYIKwYBBQUH
AwEwGQYDVR0RBBIwEIIOcXVheS5wb2xhYi5jb20wEgYDVR0TAQH/BAgwBgEB/wIB
ATAdBgNVHQ4EFgQUfcKOlnOLCwrOtX0Gs7/Th763eyswDQYJKoZIhvcNAQELBQAD
ggEBAAdvOWkajk4NG0ataHEWXDt/EIS9Fqa8GN/hmz6kcFN5Ad56WsW/WvicMNE5
B/2iyeQM39Dx7pgBY25ZQ33evhZU4eeJqwx7mnCs5IvauoOanOkmGPeP7UdyCMGV
KhDoavfVf8gEdqS+IHkqUR9rfm2gms+y/BwNB/Qbn2bKG6JOz2c3WoyBajQqsJU9
DM3aSNcFJu9acAeTWpcC2CHXAs5qBHND/38YLd+/Wug4rH48xtGc16QiQElIJLE8
WqZzTb2dZH1MkFO4B98lYsBNrUO4s6ulQPvtem85hX+RQmopOXUzrsToycM7W4a+
nz8PCkHirBNL9g7LfRtDCgi11rI=
-----END CERTIFICATE-----"
# Replace end of line with \n
CERTIFICATE=$(echo "$CERTIFICATE" | sed ':a;N;$!ba;s/\n/\\n/g')
# Output the certificate content
echo "$CERTIFICATE"
awk
show specific line in large file
How to escape a single quote inside awk
remove duplicate row
filter speficif time
sudo awk -v n_times_ago="10 minutes" -v now="$(date +%H:%M:%S)" "\$3 >= n_times_ago && \$3 <= now {print} {next}" /var/log/messages
tar
https://terryl.in/zh/linux-tar-command/ https://stackoverflow.com/questions/18681595/tar-a-directory-but-dont-store-full-absolute-paths-in-the-archive
soft link -h https://superuser.com/questions/137388/how-can-i-tar-ball-a-directory-hierarchy-with-soft-links-in-linux
exlcude/include - How do I use tar to exclude all files of a certain directory? - Ask Ubuntu - Using tar to only backup specific folders - Ask Ubuntu
├── foo │ ├── shared_repo │ ├── bar
# exlude the shared_repo
tar zcvf foo_1.0.0_20230829_src.tar.gz --exclude="shared_repo/*" foo
# include the shared_repo only
tar zcvf foo_1.0.0_20230829_repo.tar.gz foo/shared_repo
zip/unzip
user
-m: Creates the home directory for the user. -g users: Sets the initial login group to "users". -s /bin/bash: Sets the login shell to Bash. -c "bar": Adds a comment or description for the user.
groupadd foo
useradd -m -g foo -s /bin/bash -c "bar" foo
passwd foo
echo 'foo ALL=(ALL:ALL) NOPASSWD: ALL' | sudo tee -a /etc/sudoers
id {user_name}
# lock user account
passwd -l {user_name}
# set the date on which the user account will be disabled
usermod --expiredate YYYY-MM-DD {user_name}
switch user How To Change User on Linux – devconnected
crontab
- education about cron
- How can I set the timezone for Crontabs
- Is
*/1 * * * *
and* * * * *
equivalent in CRON /bin/sh: 1: python: not found
when run via cron in docker- Cron doesn't set up the PATH environment variable the same as a normal login shell so python can't be found.
- Cron job delayed by \~1 second - Ask Ubuntu
- crontab不保證精確到秒
- linux - When does `cron.daily` run? - Server Fault
cron date file name Append current date to the filename via Cron? - Stack Overflow
update crontab by command automatically
#!/bin/bash
(crontab -u ubuntu -l; echo "SHELL=/bin/bash") | crontab -u ubuntu -
(crontab -u ubuntu -l; echo "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") | crontab -u ubuntu -
(crontab -u ubuntu -l; echo "$(cat my_cron_job)") | crontab -u ubuntu -
# my_cron_job is a file which contains crontab config
# */2 * * * * cd /home/ubuntu && ./check.sh
curl
- Linux Curl Command 指令與基本操作入門教學
- 10 Examples Why cURL is an Awesome CLI Tool | Martin Heinz | Personal Website & Blog
- Ways to check for open ports on RHEL - Red Hat Customer Portal
ss
- Socket listen() backlog
- How to get BACKLOG of listening socket
- 可能是最完整的 TCP 连接健康指标工具 ss 的说明 – Mark Zhu 的博客
Recv-Q Established: The count of bytes not copied by the user program connected to this socket. Listening: Since Kernel 2.6.18 this column contains the current syn backlog. Send-Q Established: The count of bytes not acknowledged by the remote host. Listening: Since Kernel 2.6.18 this column contains the maximum size of the syn backlog.
jq
- 使用 jq 達成覆寫相同 json key 的效果
- 使用 jq 將多個檔案內容組成一份 key/value json
- Analyzing multi-gigabyte JSON files locally | thenybble.de
diff
diff colordiff vimdiff
diff -y -W 60 test_file_1.txt test_file_2.txt
| — Line is different in the second file
> — Line is additional in the second file
< — Line has been deleted from the second file
diff -y -W 60 --suppress-common-lines test_file_1.txt test_file_2.txt
# ignore case
diff -y -W 60 --suppress-common-lines -i test_file_1.txt test_file_2.txt
SYN flooding log
Symptom: HTTP ok and in the sametime HTTPS timeout
Feb 22 12:02:18 ip-172-31-15-116 kernel: [ 164.209387] TCP: request_sock_TCP: Possible SYN flooding on port 443. Sending cookies. Check SNMP counters.
check net.ipv4.tcp_max_syn_backlog
: Specifies the maximum number of connection requests that are not acknowledged by the peer end and that can be stored in the queue.
- SYN packet handling in the wild
- How TCP backlog works in Linux
- How can I monitor the length of the accept queue
- TCP socket debugging on GNU/Linux using a handful of basic tools: lsof, awk and tail.
- What is the difference between tcp_max_syn_backlog and somaxconn
system setting
on the wild
system setting and on the wild in one command
ss -plnt sport = :443|cat
ubuntu@ip-172-31-15-116:/var/log$ ss -plnt sport = :443|cat
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 512 511 *:443 *:*
sysctl
copy
shuf
openssl
- Openssl Demo: Encrypting/Decrypting files using both Symmetric and Asymmetric Encryption
- How to encrypt a file with private key
- Openssl verification fails
- How to view a certificate fingerprint as SHA-256, SHA-1 or MD5 using OpenSSL for RSA Authentication ... - RSA Community - 4230
- 如何使用 OpenSSL 建立開發測試用途的自簽憑證 (Self-Signed Certificate) | The Will Will Web
- OpenSSL Essentials: Working with SSL Certificates, Private Keys and CSRs | DigitalOcean
- Generating a self-signed certificate using OpenSSL - IBM Documentation
- Create a self-signed certificate using OpenSSL | by Allan Sun | 隨筆雜記
- 那些關於SSL/TLS的二三事(十一) — 關於憑證的維運. 前面已經對 SSL 的原理有了比較詳細的解說, 這篇開始要談的是實作的細節… | by Carl | Medium
- How to Check Certificate with OpenSSL
- Generate a full self-signed certificate chain (Root -> Intermediate CA -> Server) using keytool, that can be used for 'localhost' development · GitHub
- Creating Fullchain SSL Certificate With Bash
OpenSSL 1.1.1f
Generate private key
Generate public key by private key
Encrypt the input data using an RSA public key and Decrypt the input data using an RSA private key
echo '{"mac":"BC:CF:4F:CF:E0:C6","sn":"S202L12345678","product":1}'| openssl rsautl -encrypt -pubin -inkey public_key.pem | base64 -w 0 > enc
cat enc | base64 --decode | openssl rsautl -decrypt -inkey private_key.pem
Sign/Verify the data with PKCS#1 v1.5 (the default) padding
echo '{"mac":"BC:CF:4F:CF:E0:C6","sn":"S202L12345678","product":1}'| openssl rsautl -sign -inkey private_key.pem | base64 -w 0 > enc
cat enc | base64 -d | openssl rsautl -verify -pubin -inkey public_key.pem
Sign/Verify the data with RSASSA-PSS padding
echo 'Hello world' > message
openssl dgst -sha256 -sign private_key.pem -sigopt rsa_padding_mode:pss message | base64 -w 0 > signature
cat signature | base64 -d > signature.bin
openssl dgst -sha256 -verify public_key.pem -sigopt rsa_padding_mode:pss -signature signature.bin message
# Verified OK or Verification Failure
https://www.jianshu.com/p/64cc65f2d04f
echo "Hello world!" > foo.txt
######################################################
# 方法一: 直接使用openssl dgst -sign和openssl dgst -verify完成
# 使用RSA private key 進行簽名, 其中: sigopt rsa_padding_mode:pss指定padding scheme
openssl dgst -sha256 -sign private_key.pem -sigopt rsa_padding_mode:pss -out sig.bin foo.txt
# 使用RSA public key verify刚才的签名
openssl dgst -sha256 -verify public_key.pem -sigopt rsa_padding_mode:pss -signature sig.bin foo.txt
输出 Verified OK 代表verify成功
################################################
# 方法2: 先使用 openssl dgst -binary 输出哈希校验和, 再使用 pkeyutl 进行数字签名和校验
openssl dgst -sha256 -binary -out sha256sum.bin 文件名.txt
openssl pkeyutl \
-inkey rsakeypair.pem -pkeyopt rsa_padding_mode:pss -pkeyopt digest:sha256 \
-sign -in sha256sum.bin -out sig2.bin
openssl pkeyutl \
-pkeyopt rsa_padding_mode:pss -pkeyopt digest:sha256 \
-pubin -inkey pubkey.pem \
-verify -in sha256sum.bin -sigfile sig2.bin
屏幕输出 Signature Verified Successfully 代表数字签名校验成功
certificate
How to view a certificate fingerprint as SHA-256, SHA-1 or MD5
Create a hashed password
Create a account by command
#!/bin/bash
echo "mypostbootscript begin !"
ACCOUNT=foo
ACCOUNT_HOME=/home/${ACCOUNT}
df -hT
useradd -m ${ACCOUNT}
usermod -p '$6$5ptqLocOXaqpsWlL$93Sy8bAos7xMsn4hOepfUWXgko2KkR3g9wFva1f0piWq9fWLHEHn8/srdiLuQcYI2z668dstZFi5vQZpUVKcK/' ${ACCOUNT}
ls -la /opt_shared
df -hT
test -d ${ACCOUNT_HOME}/.ssh || mkdir -p ${ACCOUNT_HOME}/.ssh
cp /opt_shared/diskless/authorized_keys ${ACCOUNT_HOME}/.ssh/
chown ${ACCOUNT}: ${ACCOUNT_HOME}/.ssh/authorized_keys
touch /etc/sudoers.d/${ACCOUNT} && echo "${ACCOUNT} ALL=(root) NOPASSWD:ALL" > /etc/sudoers.d/${ACCOUNT}
echo "mypostbootscript end"
$6$5ptqLocOXaqpsWlL$93Sy8bAos7xMsn4hOepfUWXgko2KkR3g9wFva1f0piWq9fWLHEHn8/srdiLuQcYI2z668dstZFi5vQZpUVKcK/ by the commnad
self-signed certificate
openssl req -x509 -newkey rsa:4096 -sha256 -nodes -keyout /tmp/test.key -out /tmp/test.crt -days 30 -subj "/C=TW/ST=Taiwan/L=Taoyuan City/O=Foo/OU=Bar/CN=foo.bar"
Checking the Status of a Certificate
JDK
Resize partition
/tmp Read-only file system
$ crontab -e
/tmp/crontab.Ul9dS1: Read-only file system
$ touch /tmp/test
... Read-only file system
$ mount
tmpfs都是rw
ex. tmpfs on /run/user/1004 type tmpfs (rw,nosuid,nodev,relatime,size=398492k,mode=700,uid=1004,gid=1004)
/dev/nvme0n1p1 on / type ext4 (ro,relatime,data=ordered)
$ sudo mount -o remount,rw /
mount: / not mounted or bad option
In some cases useful info is found in syslog - try
dmesg | tail or so.
$ dmesg | tail
[ 307.911010] EXT4-fs (nvme0n1p1): Couldn't remount RDWR because of unprocessed orphan inode list. Please umount/remount instead
$ sudo e2fsck -f /dev/nvme0n1p1
e2fsck 1.42.13 (17-May-2015)
Pass 1: Checking inodes, blocks, and sizes
Inodes that were part of a corrupted orphan linked list found. Fix<y>? yes
Inode 776 was part of the orphaned inode list. FIXED.
Inode 396524 was part of the orphaned inode list. FIXED.
...
Recover
- How to Recover Deleted Files in Ubuntu through TestDisk
- [數據恢復] 可救回EXT3/ EXT4 檔案格式的開源工具 - extundelete
- How To Recover Deleted Files In Linux [Beginner’s Guide]
- How to recover deleted files?
- Can files/directories deleted with rm be restored
- Ubuntu Official
Backup
- VirtualBox-Backup
- Ubuntu Official
dpkg-reconfigure
Dockerfile
# make /bin/sh symlink to bash instead of dash:
RUN echo "dash dash/sh boolean false" | debconf-set-selections
RUN DEBIAN_FRONTEND=noninteractive dpkg-reconfigure dash
Run 32bits on 64bits machine
Dockerfile
RUN dpkg --add-architecture i386 && apt update && apt install libc6:i386 libncurses5:i386 libstdc++6:i386 zlib1g:i386
show variables
only the environment variables
onlu
sudoer
foo is not in the sudoers file. This incident will be reported.
DNS
- DNS issues after upgrading to 20.04
- Why does /etc/resolv.conf point at 127.0.0.53?
- How to persist “systemd-resolve” configuration for a particular network interface
- linux - Activation via systemd failed for unit 'dbus-org.freedesktop.resolve1.service': Unit dbus-org.freedesktop.resolve1.service not found - Super User
In Ubuntu 20.04, the expected configuration of /etc/resolv.conf is to point to a local systemd-networkd resolver
snap
md5sum
watch
- Bash script needed to run every second
- How To Repeat A Command Every X Seconds On Linux
- How to kill watch command after certain time or set timeout for a watch command in bash
tcpdump
markdown to pdf
- Markdown to PDF – quick howto for linux users (Ubuntu)
- How to convert a Markdown file to PDF - Stack Overflow
- How To Convert Markdown to PDF
xargs
ls
md5_019633f975a7d7cfd1d388b8fb208223_9492 md5_3a4eb5ed075a3c6c8aeb14a982ebcb40_12441 md5_6d7c30ba02010a4cf331a512c80d8e8e_6029 md5_c328f07c2465a7153be141c539d1c5da_8236
md5_08bae41634d7ee7282b6f584b047cc97_536834 md5_3c8418fe3dc3d51f756433383b926a02_294060 md5_87af59d786edfac662d9ac0d0add1cb1_4561993 md5_e3ea049445d877a536755cb6ce926011_13865
md5_0c96aba202f3d2c31f467aff18878525_10348 md5_461b40bd273b7214c83e5ba450308da4_11372 md5_8845dea738dcbb55cf1552cdfb7be5f4_6961 md5_f249e9dd68edac76168b4d93d041d9fa_823084
md5_148a174bd0f7662a012d6207a946ef48_10465 md5_5f6f06a93f5b2aa6d3fff0112f8f8205_13820 md5_8f55ed591f7073a9063d64e006ebec75_7111
md5_33768c95f3cf0f93c1f1ea5daa056593_115010 md5_610beebe6bf2a9b189d6924d9d6a4ce4_8734 md5_9570bc6ec0bcc9e3ebf5f52a4436584d_22295
md5_34f5fcbc46f66c0fe352deceac2c3d9a_65536 md5_6b46685a1f7da37bc3b4f4708bc6cce7_8366 md5_bd2f633a8cddfc04a80d6f93d6ab5777_11103
ls | awk -F '_' '{print "mv "$1"_"$2"_"$3" "$2}' | xargs -I {} sh -c {}
ls
019633f975a7d7cfd1d388b8fb208223 33768c95f3cf0f93c1f1ea5daa056593 461b40bd273b7214c83e5ba450308da4 6d7c30ba02010a4cf331a512c80d8e8e 9570bc6ec0bcc9e3ebf5f52a4436584d f249e9dd68edac76168b4d93d041d9fa
08bae41634d7ee7282b6f584b047cc97 34f5fcbc46f66c0fe352deceac2c3d9a 5f6f06a93f5b2aa6d3fff0112f8f8205 87af59d786edfac662d9ac0d0add1cb1 bd2f633a8cddfc04a80d6f93d6ab5777
0c96aba202f3d2c31f467aff18878525 3a4eb5ed075a3c6c8aeb14a982ebcb40 610beebe6bf2a9b189d6924d9d6a4ce4 8845dea738dcbb55cf1552cdfb7be5f4 c328f07c2465a7153be141c539d1c5da
148a174bd0f7662a012d6207a946ef48 3c8418fe3dc3d51f756433383b926a02 6b46685a1f7da37bc3b4f4708bc6cce7 8f55ed591f7073a9063d64e006ebec75 e3ea049445d877a536755cb6ce926011
iptables
- linux - Debugging iptables and common firewall pitfalls? - Server Fault
- Day 46: debugging an iptables problem
iperf
- iPerf3 網路速度測試教學,頻寬檢測指令工具 - G. T. Wang
- Measuring Internal Bandwidth with iperf :: BalanceNG Load Balancer
ssh
- A Visual Guide to SSH Tunnels (with labs)
- SSH Tunneling (Port Forwarding) 詳解 · John Engineering Stuff
- Creating an SSH tunnel in Linux | The STAR experiment
- Port forwarding with SSH - Rufflewind's Scratchpad
- How to Set up SSH SOCKS Tunnel for Private Browsing | Linuxize
- 在 Ubuntu 中設定特定用戶的 SSH 密碼登入方法 - Clarence 的科技學習實戰筆記
port forwarding by multiple hosts
client => hostA => hostB(exist http server) => PDU(exist http server with 443)
hostA: 172.27.23.103 hostB: 167.22.10.1 PDU: 167.222.17.1
single hop
multiple hops
ssh -L 8888:localhost:12345 foo@172.27.23.103
ssh -N -L 12345:167.222.17.1:443 foo@167.22.10.1
# combine above into one commnad
ssh -L 8888:localhost:12345 foo@172.27.23.103 'ssh -N -L 12345:167.222.17.1:443 foo@167.22.10.1'
# if no passwordless
ssh -L 8888:localhost:12345 foo@172.27.23.103 'sshpass -p fakepwd ssh -N -L 12345:167.222.17.1:443 foo@167.22.10.1'
# access https://127.0.0.1:8888
known_hosts
- 第12章:SSH遠端連線設定與原理介紹(一) - iT 邦幫忙
- What is known_hosts File in Linux [Everything to Know]
- SSH Fingerprint: Get Fingerprint of SSH RSA Key - ShellHacks
- Ubuntu Manpage: ssh-keyscan — gather ssh public keys
- ssh_known_hosts file format - IBM Documentation
- ssh - Check the fingerprint for the ECDSA key sent by the remote host - Server Fault
- linux - How use ssh-keygen to show either ECDSA or ecdsa-sha2-nistp256? - Super User
- ssh - How to view ECDSA host key of a server? - Server Fault
- Linux Commando: How to disable SSH host key checking
current host which has known_hosts file
ssh-keyscan <remote host>
ssh-keyscan -t ecdsa <remote host>
ssh-keyscan -t rsa,ecdsa,ed25519 <remote host>
ssh-keyscan -t rsa,ecdsa,ed25519 -H <remote host>
ssh-keyscan -t rsa,ecdsa,ed25519 -H <remote host> 2>/dev/null >> .ssh/known_hosts
# Remove an entry from the known_hosts
ssh-keygen -R <remote host>
remote host
# the content will be added into the known_host
cat /etc/ssh/ssh_host_ecdsa_key.pub
# Show fingerprint of specified SSH key file.
# the output will be shown on the propmpt when access this host first time
ssh-keygen -lf /etc/ssh/ssh_host_ecdsa_key.pub
ssh-copy-id
- ssh-copy-id
- SSH 金鑰:免密碼登入遠端主機、傳遞檔案
- linux - How to ssh-copy-id through a jump-host? Something similar to the -J option with ssh command - Server Fault
ssh-copy-id foo@bar.tw
# through bastion
ssh-copy-id -o ProxyJump=jumpuser@jumphost:2455 remoteuser@remotehost
authorized_keys
ssh server(sshd)
if you changed the sshd server config file and before restart or reload OpenSSH server
ssh agent
- Working with SSH key passphrases - GitHub Docs
- Using SSH agent forwarding - GitHub Docs
- 5 SSH Agent Best Practices
- 淺談 SSH agent forwarding 和 proxy command 的安全風險與應用 « Nic Lin's Blog
- Ssh-agent single sign-on configuration, agent forwarding, the agent protocol.
env=~/.ssh/agent.env
agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
agent_start () {
(umask 077; ssh-agent >| "$env")
. "$env" >| /dev/null ; }
agent_load_env
# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2=agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)
if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
agent_start
ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
ssh-add
fi
unset env
If you want ssh-agent to forget your key after some time, you can configure it to do so by running ssh-add -t {seconds}.
config for sshd
premit root ssh login
cat <<EOF >> /etc/ssh/sshd_config.d/customized.conf
PermitRootLogin yes
PasswordAuthentication yes
EOF
systemctl restart sshd
firewalld
- CentOS Linux 7 以 firewalld 指令設定防火牆規則教學 - G. T. Wang
- firewalld from iptables - Documentation
- Secure your Linux network with firewall-cmd | Enable Sysadmin
- CentOS 7 設定防火牆允許特定 PORT 連線 - Yowko's Notes
basic
external - Used when you want to configure the firewall as a NAT gateway. The external zone is used for NAT masquerading such that your internal network stays private but reachable from external systems.
internal - Used for internal networks when you trust other computers or servers on your LAN.
each zone has its associated .xml file stored within the /usr/lib/firewalld/zones/ directory
By default, all the network interfaces are bound to default zone
# get a list of all the zones
sudo firewall-cmd --get-zones
sudo firewall-cmd --get-default-zone
sudo firewall-cmd --get-active-zones
# display all the services supported by Firewalld
sudo firewall-cmd --get-services
sudo firewall-cmd --list-services
sudo firewall-cmd --list-services --zone=public
# you can bind an interface to another zone
sudo firewall-cmd --change-interface=ens160 --zone=internal
# check out the configuration associated with the internal zone
sudo firewall-cmd --list-all --zone=internal
# add/remove Services on Firewalld
sudo firewall-cmd --add-service=http --zone=public
sudo firewall-cmd --remove-service=http --zone=public
The --permanent option makes the change persistent. For the change made to apply even after a reboot, reload the firewall.
sudo firewall-cmd --add-service=http --zone=public --permanent
sudo firewall-cmd --reload
sudo firewall-cmd --remove-service=http --zone=public --permanent
sudo firewall-cmd --reload
sudo firewall-cmd --zone=public --add-port=18443/tcp --permanent
sudo firewall-cmd --reload
sudo firewall-cmd --zone=public --remove-port=18443/tcp --permanent
sudo firewall-cmd --reload
nfs
sudo firewall-cmd --zone=public --list-all
sudo firewall-cmd --zone=public --add-service=nfs --permanent
sudo firewall-cmd --reload
sudo systemctl restart nfs-server
cat
tee
network
- Linux 網路設定
- Linux: How to find the device driver used for a device? - Unix & Linux Stack Exchange
ethtool -i enp2s0
sudo lspci -v | grep 'Ethernet controller'
- How to find PCI address of an ethernet interface? - Ask Ubuntu
sudo lshw -c network -businfo
grep PCI_SLOT_NAME /sys/class/net/*/device/uevent
- ethtool 命令,Linux ethtool 命令详解:显示或修改以太网卡的配置信息 - Linux 命令搜索引擎
- 36.2. 使用 NetworkManager 配置 ethtool offload 功能 Red Hat Enterprise Linux 8 | Red Hat Customer Portal
- Configuring Mellanox mlx5 cards in Red Hat Enterprise Linux - Red Hat Customer Portal
- Red Hat Enterprise Linux Network Performance Tuning Guide
- linux - Check if a DHCP server existing in my network using bash - Super User
nmap --script broadcast-dhcp-discover -e eth0
- networking - I can ping a server, but I can not ssh to it - Super User
nmap 172.17.30.108 -p 22
cpu
- Rivermax Linux Performance Tuning Guide [1]
- cpu - Understanding output of lscpu - Unix & Linux Stack Exchange
- What is the correct way to view your CPU speed on Linux? - Unix & Linux Stack Exchange
- How To Set CPU Scaling Governor to Max Performance (scaling_governor)
- 如何使用 cpufreq-set 和 cpufreq-info 進行 CPU 調效:提升系統性能的最佳實踐 - Clarence 的科技學習實戰筆記
lscpu
cpupower frequency-info
cat /proc/cpuinfo | egrep 'cpu MHz|processor'
cat /proc/cpuinfo | sed -n '/^processor\|^cpu MHz/p'
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq
rpm
umask
mount
- How to Mount and Unmount an ISO Image in Linux
- 使 Amazon EBS 磁碟區可在 Linux 上使用 - Amazon Elastic Compute Cloud
-
mount(8) — mount — Debian testing — Debian Manpages
--all
, in this case already mounted filesystems are ignored- mount(8): mount filesystem - Linux man page
nmap
arp
Ceasar's Free Life: Linux清除ARP 暫存
netstat
netstat -tulnp
udevadm
a tool used to manage the udev device manager in Linux.
The ID_WWN (World Wide Name) property in udev is a unique identifier for a device. It is often used to identify storage devices, such as hard drives and solid-state drives.
The ID_WWN property is assigned by the manufacturer of the device and is usually stored on the device itself. It is a 64-bit value that is unique to each device.
pstree
nmcli
- nmcli: NetworkManager Reference Manual
- 3 ways to configure a network interface in Linux | Enable Sysadmin
- How to assign an additional/alias IP addresses to a network card (NIC)? - Red Hat Customer Portal
- Linux NetworkManager 用命令列工具或組態檔設定網路連線 - 石頭閒語
config infiniband - 0000166: NetworkManager fails to configure IP over InfiniBand (IPoIB) connections - Rocky Linux BugTracker - NetworkManager restart fails with: device state change: prepare -> failed (reason 'dependency-failed') - Red Hat Customer Portal - Infiniband Troubleshooting – Hasan Mansur
# check the link status
ibdev2netdev
ibstatus
ibstat
iblinkinfo
nmcli connection add type infiniband con-name ib0 ifname ib0
nmcli connection modify ib0 ipv4.addresses 167.123.200.3/16
nmcli connection modify ib0 ipv4.method manual
nmcli connection modify ib0 ipv6.method ignore
# If ifcfg-files have changed, those changes can be applied with
nmcli connection reload
nmcli connection up ib0
gateway
# add the gateway
sudo nmcli connection modify enp68s0f0 ipv4.gateway "167.23.10.3"
# remove the gateway
sudo nmcli connection modify enp68s0f0 ipv4.gateway ""
sudo nmcli connection reload && sudo nmcli connection down enp68s0f0 && sudo nmcli connection up enp68s0f0
dns
# add the dns
sudo nmcli connection modify enp68s0f0 ipv4.dns "167.23.10.3 8.8.8.8"
# change the dns priority
sudo nmcli connection modify enp68s0f0 ipv4.dns-priority 50
# The default DNS priority values in NetworkManager are:
# 50 for VPN connections
# 100 for other connections
# A lower value indicates a higher priority. If you don't set a specific priority, these default values will be used.
# remove the dns
sudo nmcli connection modify enp68s0f0 ipv4.dns ""
sudo nmcli connection reload && sudo nmcli connection down enp68s0f0 && sudo nmcli connection up enp68s0f0
auto or manual
# manual
nmcli connection modify ens34 \
ipv4.method manual \
ipv4.address 192.168.10.11/24 \
ipv4.gateway 192.168.10.1 \
ipv4.dns 8.8.8.8
ip link set ens34 down && ip link set ens34 up
cat /etc/NetworkManager/system-connections/ens34.nmconnection
# auto
nmcli connection modify ens34 \
ipv4.method auto \
ipv4.address '' \
ipv4.gateway ''
ip link set ens34 down && ip link set ens34 up
cat /etc/NetworkManager/system-connections/ens34.nmconnection
if device is disconnected
netplan
- Ubuntu 20.04 網路設定 | 不務正業工程師的家
- Ubuntu 20.04 網路綁定 | 不務正業工程師的家
- How to Configure Networking in Ubuntu 20.04 with NetPlan - Serverlab
- linux - Is "netplan apply" required if I reboot after changing /etc/netplan/xxx-config.yaml file - Server Fault
- networking - Netplan does not apply at startup - Ask Ubuntu
- networking - How do I stop netplan from binding a default gateway on every interface - Ask Ubuntu
- networking - What does "routes" mean? [Netplan, YAML file] - Ask Ubuntu
- ubuntu - netplan static and dynamic interfaces without default route for static? - Stack Overflow
/etc/netplan
no default route
network:
ethernets:
ens160:
dhcp4: true
dhcp4-overrides:
use-routes: false
ens192:
addresses: [ 172.20.0.1/16]
version: 2
dhcp
To release the current dynamic IP address, use the "dhclient -r" command followed by the name of the network interface.
To remove a specific dynamic IP address, use the "ip addr del" command followed by the IP address and the network interface.
In-box driver
You can also use the lsmod command to list the modules that are currently loaded in the kernel, which will include in-box drivers that are being used by the system.
xml
xmlstarlet
yum install xmlstarlet
xmlstarlet sel -t -v "//comps/environment/name[not(@xml:lang)]" -n my.xml
xmlstarlet sel -t -v "//comps/group[id='infiniband']/packagelist/packagereq" -n my.xml
xmlstarlet sel -t -v "//comps/group[id='infiniband']/packagelist/packagereq[not(@type='optional')]" -n my.xml
ulimit
- 查詢與設定 Linux 使用者可開啟的行程數量上限值,限制開啟程式的數目 - G. T. Wang
- 解開CentOs 利用systemd 起service 的 ulimit 資源限制 | by Yen-Ying Lee | Medium
- limit - ulimit vs file-max - Unix & Linux Stack Exchange
- ulimit - do changes in /etc/security/limits.conf require a reboot? - Unix & Linux Stack Exchange
- Linux下的resource limits(ulimit) | C0reFast记事本
- Linux最大開啓檔案數- FineBI帮助文档 FineBI帮助文档
Operation not permitted
ulimit: open files: cannot modify limit: Operation... - Hewlett Packard Enterprise Community bash - ulimit PICKLE: "Operation not permitted" and "Command not found" - Unix & Linux Stack Exchange A normal user can adjust the soft limit freely in the range of 0.... A normal user can adjust the hard limit too, but can only decrease it. You must be root to increase the hard limit from its default value.
The limit values are inherited from the parent process to the child process: you could add the command to increase the hard limit to the sshd startup script, so that sshd and all sessions started through it will inherit the increased hard limit. After that, you should be able to increase the soft limit as a normal user.
/etc/security/limits.conf
nohup
- Linux 的 nohup 指令使用教學與範例,登出不中斷程式執行 - G. T. Wang
- [Day3] Linux 偷懶小工具 nohup
- linux - What's the difference between nohup and ampersand - Stack Overflow
fill whole disk space in Linux
/etc/shadow
# SHA512
openssl passwd -6 test
# $6$MY7OCrv90dRsfxoP$Lq8Uo1gNddpOC1YIOabuadH9XO/QxUTfb6V9.xeF/Cq50CG2asUa9eL0gUG0cOShhfgeqA7lYIdVjiEDnCYoM.
sudo usermod -p '$6$MY7OCrv90dRsfxoP$Lq8Uo1gNddpOC1YIOabuadH9XO/QxUTfb6V9.xeF/Cq50CG2asUa9eL0gUG0cOShhfgeqA7lYIdVjiEDnCYoM.' username
chrony
- Chapter 29. Using Chrony Red Hat Enterprise Linux 8 | Red Hat Customer Portal
- 13.2. 使用 Chrony | Red Hat Product Documentation
- chrony – chrony.conf(5)
systemd
- systemd - How to see full log from systemctl status service? - Unix & Linux Stack Exchange
- SLES 15 SP1 | Administration Guide | The systemd daemon
- Linux systemd 系統服務管理基礎教學與範例 - G. T. Wang
- Linux 建立自訂 Systemd 服務教學與範例 - G. T. Wang
- linux - Do you know how to make the system automatically restart daemon service? - Stack Overflow
- How to Control Systemd Services on Remote Linux Server
vim
gpustat
lspci
- lspci命令输出的一些解释 | C0reFast记事本
- /usr/share/hwdata/pci.ids.gz
- /usr/share/hwdata/pci.ids
- The PCI ID Repository
Bus Number:Device Number.Function Number
gpu
NVIDIA
[foo@bar ~]$ lspci | grep NVIDIA
01:00.0 3D controller: NVIDIA Corporation GA100 [A100 PCIe 80GB] (rev a1)
81:00.0 3D controller: NVIDIA Corporation GA100 [A100 PCIe 80GB] (rev a1)
[foo@bar ~]$
AMD
foo@bar:~$ lspci | grep Display
03:00.0 Display controller: Advanced Micro Devices, Inc. [AMD/ATI] Device 740f (rev 02)
foo@bar:~$
foo@mi325x:/tmp$ lspci | grep -i 'accelerators'
05:00.0 Processing accelerators: Advanced Micro Devices, Inc. [AMD/ATI] Device 74a5
15:00.0 Processing accelerators: Advanced Micro Devices, Inc. [AMD/ATI] Device 74a5
65:00.0 Processing accelerators: Advanced Micro Devices, Inc. [AMD/ATI] Device 74a5
75:00.0 Processing accelerators: Advanced Micro Devices, Inc. [AMD/ATI] Device 74a5
85:00.0 Processing accelerators: Advanced Micro Devices, Inc. [AMD/ATI] Device 74a5
95:00.0 Processing accelerators: Advanced Micro Devices, Inc. [AMD/ATI] Device 74a5
e5:00.0 Processing accelerators: Advanced Micro Devices, Inc. [AMD/ATI] Device 74a5
f5:00.0 Processing accelerators: Advanced Micro Devices, Inc. [AMD/ATI] Device 74a5
foo@mi325x:/tmp$
logrotate
- Setting up logrotate in Linux | Enable Sysadmin
- linux - How to make log-rotate change take effect - Unix & Linux Stack Exchange
ls -la /etc/cron.daily/
## debug output
logrotate -d /etc/logrotate.d/your-logrotate-config
## execute it directly
logrotate /etc/logrotate.d/your-logrotate-config
environment-modules
alternatives
ip
- rh_ip_command_cheatsheet_1214_jcs_print.pdf
- awesome-cheatsheets/tools/ip.txt at master · skywind3000/awesome-cheatsheets
- linux - ip vs ifconfig commands pros and cons - Unix & Linux Stack Exchange
- ip vs. ifconfig: Which do you use? | Enable Sysadmin
- Linux networking: ifconfig versus ip | Enable Sysadmin
- linux/ip---route---command.md at master · wl-sre/linux · GitHub
ip route del default
ip route add default via 172.19.50.1 dev enp3s0f1
ping -c 2 8.8.8.8; ping -c 2 www.google.com; curl www.google.com
static route
nvidia-smi
lsof
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
systemd-r 254 systemd-resolve 12u IPv4 23159 0t0 UDP 127.0.0.53:domain
systemd-r 254 systemd-resolve 13u IPv4 23160 0t0 TCP 127.0.0.53:domain (LISTEN)
dnsmasq
- linux - how to disable dnsmasq service in CentOS 8 - Stack Overflow
- How to configure DNS caching server with dnsmasq in RHEL - Red Hat Customer Portal
yq
Another tool named yq is at https://kislyuk.github.io/yq/. The two yq tools are not compatible; commands that are designed for one of them do not work with the other.
NMState
NFS
/etc/exports
specify which directories on a server should be available to NFS clients re-export all NFS shared directories specified in the /etc/exports file and provides verbose output
journalctl
VNC
dnsmasq
rclone
- Rclone:玩轉Google Drive & One Drive - 消失的亞特蘭提斯
- 手動打造Google Drive同步工具:ownCloud與rclone的組合 / Build a File Sync Tool for Google Drive: ownCloud + rclone - 布丁布丁吃什麼?
- GUI
timedatectl
timedatectl status
timedatectl list-timezones
timedatectl set-timezone "Asia/Taipei"
timedatectl timesync-status
apt install systemd-timesyncd
timedatectl set-ntp true
systemctl start systemd-timesyncd
systemctl status systemd-timesyncd
/etc/systemd/timesyncd.conf
iftop
build ISO
- GNU xorriso - GNU Project - Free Software Foundation
- How to create a modified Red Hat Enterprise Linux ISO with kickstart file or modified installation media? - Red Hat Customer Portal
- mkisofs