Linux FAQ

Linux FAQ

Linux FAQ

如何删除名字特殊文件

通过inode号删除

1
2
3
4
5
6
7
8
liuliancao@liuliancao:~/projects/devops-pipeline/terraform$ ls -li
total 78852
6308786 -rw-r--r-- 1 liuliancao liuliancao        0 9月  29 10:10 ''$'\274\216'
liuliancao@liuliancao:~/projects/devops-pipeline/terraform$ find . -inum 6308786 -exec rm {} \;cpf
liuliancao@liuliancao:~/projects/devops-pipeline/terraform$ ls -al
total 78864
drwxr-xr-x 9 liuliancao liuliancao     4096 9月  29 10:20 .
drwxr-xr-x 8 liuliancao liuliancao     4096 9月  17 18:50 ..

curl

curl下载文件

1
curl -o xxx http://xxxx

curl指定用户名密码

curl -u username:password http://xxx.xxx

curl列出文件列表

supervisor

supervisor通过http重启服务

刚开始看了文档没找到,后来想到,界面既然可以重启肯定有地址,所以看了果然可以

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
[root@liuliancao tasks]# curl -u username:password 'http://10.1.1.2:9001/index.html?action=stopall'
<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code 301.
<p>Message: Moved Permanently.
</body>

[root@liuliancao tasks]# curl -u username:password 'http://10.1.1.2:9001/index.html?action=restartall'
<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code 301.
<p>Message: Moved Permanently.
</body>

shell获取距1970年1月1日00:00的秒数,毫秒,纳秒数

这里要注意纳秒数不是date +%N,这个是获取具体的纳秒数,但是前面的s没带类似于3.5555

%N是5555而%s是3

1
2
3
4
5
6
# from 1970-01-01 00:00 seconds
date +%s
# from 1970-01-01 00:00 milseconds
date +%s%3N
# from 1970-01-01 00:00 nanoseconds
date +%s%N

linux使用命令行界面或者图形界面

debian10开机默认命令行需要如下,

grub修改,grub修改有两种办法和centos7比较类似,

a)修改/etc/default/grub 然后update-grub2

或者直接修改/boot/grub/grub.cfg(修改之前建议先备份)

一般建议修改/etc/default/grub(第一行是让用户登录时命令行login,第二行时grub选择系统界面为命令行)

GRUB_CMDLINE_LINUX_DEFAULT="quiet text"

GRUB_TERMINAL=console

b)改完以后执行update-grub2 这个时候去/boot/grub/grub.cfg检查是否cmd line增加了text,等开机了也检查下/proc/cmdline

c)然后设置多用户的配置

sudo systemctl set-default multi-user.target

如果要切回图形界面,

sudo systemctl set-default graphical.target

节点间copy断点续传

一般 建议用rsync, rsync -P xxx remote:xxx

允许用户登录

一般是把用户公钥追加到.ssh/authorized.keys即可 当然也可以使用ssh-copy-id -i xxx.pub 这里有个问题就是对于长这样的pub —- BEGIN SSH2 PUBLIC KEY —- —- END SSH2 PUBLIC KEY —- 需要通过ssh-keygen -f -i xxx.pub > xxx-new.pub 然后再进行后续,直接copy或者自己转化要去掉换行

samba linux配置和使用

debian类似yum provides的功能

1
2
3
4
5
  apt-file
  sudo apt-get install apt-file -y
  sudo apt-file update
  sudo apt-file search bin/ag
  sudo apt-get install silversearcher-ag -y

sed捕获xxx='xxx'里面的字符串

sed -r "s/.*xxx='([^']*)'.*/\1/"

获取云主机的外网ip

网上有不少,看起来这个ipinfo.io正规一点

1
curl ipinfo.ip/ip

tcpdump pcap to text

tcpdump -A -r xxx.pcap

终端管理tmux使用

echo xxx > $file_name有时候可能无法生效,模糊的重定向

echo xxx | tee $file_name echo xxx | tee -a $file_name

挂载远程目录

使用sshfs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
  # install
  liuliancao@liuliancao:~$ sudo apt-get install sshfs
  liuliancao@liuliancao:~$ sudo mkdir /mnt/vps
  liuliancao@liuliancao:~$ sudo chown -R liuliancao:liuliancao /mnt/vps
  # mount
  liuliancao@liuliancao:~$ sshfs root@blog.liuliancao.com:/ /mnt/vps
  liuliancao@liuliancao:~$ ls /mnt/vps
  bin  boot  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
  # umount
  # permanent, not suggest if it costs too much boot time
  liuliancao@liuliancao:~$ cat /etc/fstab|grep sshfs
  root@vps.liuliancao.com:/ /mnt/vps fuse.sshfs _netdev,allow_other,identityfile=/home/liuliancao/.ssh/id_rsa 0 0
  # you can add a script in you PATH
  cat <<EOF > mount_vps.sh
#!/usr/bin/env bash
# add for mount vps with sshfs by liuliancao at 20211210.
#
sshfs root@blog.liuliancao.com:/ /mnt/vps
EOF

如果是网络延迟比较高实际体验并不好,如果国内网络或者内网肯定是没啥问题的,建议在服务器操作吧,

或者scp过去文件

grep -q

连环grep的时候注意grep -q通常不如你所想,建议使用一条grep,如果需要判断

ssh通过一台公网服务器实现跳转

1
2
3
4
cat ~/.ssh/config
Host 10.0.200.12
    User root
    ProxyCommand ssh root@xx.xx.xx.xx  -W %h:%p

确保你和xx.xx.xx.xx互通,xx.xx.xx.xx和10.0.200.12互通 ssh 10.0.200.12测试就好了

free里面的内存究竟是怎么对应的

debian12下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
➜  ~ free
               total        used        free      shared  buff/cache   available
内存:   15929176     4157504     7646456      823308     4125216    10639272
交换:     999420           0      999420

# 我们可以发现total=used+free+buff/cache
➜  ~ cat /proc/meminfo
MemTotal:       15929176 kB
MemFree:         7638624 kB
MemAvailable:   10631596 kB
Buffers:          213340 kB
Cached:          3701392 kB
SwapCached:            0 kB
Active:          1307972 kB
Inactive:        5498232 kB
Active(anon):       6672 kB
Inactive(anon):  3678028 kB
Active(file):    1301300 kB
Inactive(file):  1820204 kB
Unevictable:      748372 kB
Mlocked:              48 kB
SwapTotal:        999420 kB
SwapFree:         999420 kB
Dirty:                96 kB
Writeback:             0 kB
AnonPages:       3541296 kB
Mapped:           870228 kB
Shmem:            826492 kB
KReclaimable:     213844 kB
Slab:             421364 kB
SReclaimable:     213844 kB
SUnreclaim:       207520 kB
KernelStack:       19424 kB
PageTables:        49192 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     8964008 kB
Committed_AS:   10919356 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      126008 kB
VmallocChunk:          0 kB
Percpu:            18112 kB
HardwareCorrupted:     0 kB
AnonHugePages:   1007616 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
FileHugePages:         0 kB
FilePmdMapped:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
Hugetlb:               0 kB
DirectMap4k:      601696 kB
DirectMap2M:     9553920 kB
DirectMap1G:     7340032 kB

centos7.9下

1
2
3
4
[root@vps ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:            512         127          35           0         349         383
Swap:           512          31         480

我们发现 total=used+free+buff/cache 所有内存包含使用的,从未被使用的,可以被回收的(目前有缓存或者文件meta数据的)

available=total-used-shared这个和windows里面的方法比较像 可用的=所有的内存-WorkingSet-Shared

总结下:

  1. total = used + free + buff/cache
  2. available < free + buffer + cache 实际buffer和cache中有不可回收的内存, 除了Unclaimable还有一些
  3. buffer和cache都是缓冲区,buffer用于把文件meta等块信息放到缓冲用于加速打开文件,cache用于

把文件内存放到内存以加速访问文件数据

  1. swap是一块磁盘区域,用于在操作系统内存不足的时候,把一些buffer和cache数据换出方便其他程序使用

但是会增加磁盘io,也可能导致系统变慢,内存足够的场景需要关掉,一般我们线上是关掉的,尤其是db。

比较两个目录

1
diff -r diretory_a diretory_b

什么是irq和irqbalance

irq

irq和irqbalance相关 irq是interrupts,中断

一般操作系统里面分为软中断和硬中断,硬中断是硬件发来的让cpu优先处理其请求,

比如键盘按下,打印机打印,鼠标移动等等,软中断比如cpu除以0触发等等,是软件相关的错误

软中断本质上是利用硬件中断的方式模拟中断通过异步实现更好地利用cpu。通过把中断分为上半部和下半部

上半部优先处理硬件相关、时间敏感的工作,而下半部通过内核线程处理剩下的工作

可以看下cat /proc/softirqs,有11种软中断类型,包含定时器,任务调度,网卡收发,RCU锁相关 一个很好的排查软中断的例子

linux里面把每个cpu的软中断线程标记为ksoftirqd/0等

从网上的例子看一般cpu 软中断高可能是网卡流量较高,具体可以通过检查ksoftirqd程序的占用有关

*注意*这里有个问题就是当我们是数据库等需要关闭NUMA的场景,其实我是希望尽量少的跨node进行交互的时候

那么最好是进行一些单独的irq设置,或者关闭irqbalance避免其均匀分配

irqbalance

irq balance是为了避免cpu出现负载过多的软件,适合多个核心的情况,

可以通过设置/etc/default/irqbalance文件配置忽略的cpu节点

ls的时候太慢

1
ls -1 -f

yum download only

1
2
yum install yum-plugin-downloadonly
yum install --downloadonly PACKAGE_NAME

curl如何自动redirect自动301跳转

1
2
curl -L URL
curl -L --max-dirs NUMBER URL

更多curl的例子curl的例子

提示no matching host key type found. Their offer: ssh-rsa

下面的都试下

1
2
3
4
5
#.ssh/config增加
#PubkeyAcceptedAlgorithms +ssh-rsa
#KexAlgorithms +diffie-hellman-group1-sha1    
HostkeyAlgorithms +ssh-rsa    
#PubkeyAcceptedKeyTypes +ssh-rsa

rsync from windows to linux

1
rsync  -av --delete xxx/* rsync://root@1.2.3.4:50873/section/yyy

50873是远程rsync的端口,这里要注意的一点是

从windows到linux的rsync,如果默认不设置是会权限混乱的

解决办法是rsync服务器端要增加一些设置

1
2
3
4
fake super = yes
use chroot = yes
read only = false
incoming chmod = Du=rwx,Dgo=rx,Fu=rw,Fgo=r

rsync delete远程不一样目录的时候忽略目的文件

1
rsync --delete -prvl --safe-links  --exclude="xxx" --exclude="yyy" /tmp/aaa_${version}_src/ $dest_dir/

sudo报错sudo: no valid sudoers sources found, quitting

最近sudo报错,diff正确的和错误的时候发现所有都不一样,但是cat >是可以,

所以怀疑是编码问题,cat -A发现是^M的,解决办法是编辑器默认设置utf8,

服务器dos2unix下

常见的timestamp类型

163源404

debian10 puppet安装的时候

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Do you want to continue? [Y/n] y
Err:1 http://mirrors.163.com/debian buster/main amd64 debconf-utils all 1.5.71
  404  Not Found [IP: 60.191.80.11 80]
Err:2 http://mirrors.163.com/debian buster/main amd64 libruby2.5 amd64 2.5.5-3+deb10u3
  404  Not Found [IP: 60.191.80.11 80]
Err:3 http://mirrors.163.com/debian buster/main amd64 ruby2.5 amd64 2.5.5-3+deb10u3
  404  Not Found [IP: 60.191.80.11 80]
E: Failed to fetch http://mirrors.163.com/debian/pool/main/d/debconf/debconf-utils_1.5.71_all.deb  404  Not Found [IP: 60.191.80.11 80]
E: Failed to fetch http://mirrors.163.com/debian/pool/main/r/ruby2.5/libruby2.5_2.5.5-3+deb10u3_amd64.deb  404  Not Found [IP: 60.191.80.11 80]
E: Failed to fetch http://mirrors.163.com/debian/pool/main/r/ruby2.5/ruby2.5_2.5.5-3+deb10u3_amd64.deb  404  Not Found [IP: 60.191.80.11 80]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

换了aliyun的源

1
2
3
4
5
6
7
8
deb http://mirrors.aliyun.com/debian/ buster main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ buster main non-free contrib
deb http://mirrors.aliyun.com/debian-security buster/updates main
deb-src http://mirrors.aliyun.com/debian-security buster/updates main
deb http://mirrors.aliyun.com/debian/ buster-updates main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ buster-updates main non-free contrib
deb http://mirrors.aliyun.com/debian/ buster-backports main non-free contrib
deb-src http://mirrors.aliyun.com/debian/ buster-backports main non-free contrib

^M文本出现这种异常情况windows的换行

1
sed -i 's/\r//g' xxx

按照文件名字查询

1
2
3
4
# find PATH -type f -name xxx
# find PATH \( -type f -not -perm 0644 \) -or \( -type d -not perm 0755\)
# updatedb(updated every day);locate -d PATH xxx
# whereis COMMAND # find your command

找出什么时间之后的文件

1
find /data/test* -newerct '2022-09-02 18:00' -type f|xargs -i ls -l {}

查看系统中的大文件

1
2
3
ncdu
find . -size +1G
du -h . --max-depth=3

查找对应文件目录的父目录

1
find /data -name xxx -type d -exec dirname {} \;

awk求和

awk '{sum+=$1} END{print sum}' xxx

crontab正常执行可以执行,实际执行失败

检查下是不是脚本里面没有使用绝对路径,或者/etc/crontab里面没有加环境变量

一般/usr/local/bin这种命令是没有的

监听文件或者文件夹的一种方式

inotify

systemd如何自动启动

1
2
3
[service]
Restart=on-failure
RestartSec=5s

操作完可以kill看看

申请免费证书

最近acme貌似有问题,用certbot正常,推荐

1
2
3
4
yum -y install python2-certbot-nginx certbot
certbot --nginx
crontab -e
0 0 1 * * /usr/bin/certbot renew --quiet >> /root/certbot.log

rpm cpio error

一般是rpm包没下完整,检查是不是wget了两次,那样包名字为xxx.rpm.1或者xxx.rpm.2

7z extract解压

p7zip

requests no proxy

1
2
3
4
import requests
session = requests.Session()
session.trust_env = False
response = session.get('http://www.stackoverflow.com')

nmap

检查ssl握手相关

1
sudo nmap -sV --script ssl-enum-ciphers -P 443 blog.liuliancao.com

openssl cert date

1
openssl x509 -in server.crt -noout -dates

批量 check i是类似blog.liuliancao.com的

1
for i in `cat domain`;do echo $(echo -n Q |openssl s_client -servername $i -connect $i:443 | openssl x509 -noout -dates) >> check_domain.out;done

openssl certificate unable to get local issuer

1
2
3
4
5
6
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

火狐下载证书链文件 下完以后放到centos7机器的/etc/pki/ca-trust/source/anchors/ 然后服务器执行 update-ca-trust extract

curl -u如何转化成curl -H

1
2
echo -n 'username:password' | base64
curl -H 'Authorization: Basic XXX'

awk统计tcp连接数量

1
netstat -n|awk '/^tcp/{++count[$NF]}END{for(a in count){print a,count[a]}}'

curl查看各个解析的时间

1
2
3
4
5
6
7
curl -s -w "
  \n解析时间:  %{time_namelookup}
  连接时间:  %{time_connect}
  TLS 握手时间:  %{time_appconnect}
  传输开始时间:  %{time_starttransfer}
  总时间:  %{time_total}
  \n" -o /dev/null http://example.com

配置logrotate

可以直接man logrotate,能看到各种例子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# sample logrotate configuration file
compress

/var/log/messages {
    rotate 5
    weekly
    postrotate
	/usr/bin/killall -HUP syslogd
    endscript
}

"/var/log/httpd/access.log" /var/log/httpd/error.log {
    rotate 5
    mail www@my.org
    size 100k
    sharedscripts
    postrotate
	/usr/bin/killall -HUP httpd
    endscript
}

/var/log/news/* {
    monthly
    rotate 2
    olddir /var/log/news/old
    missingok
    postrotate
	kill -HUP `cat /var/run/inn.pid`
    endscript
    nocompress
}

~/log/*.log {}

几个参数的含义

  • compress nocompress

被滚动的老的日志是否被压缩

  • create mode owner group, create owner group

创建文件的权限 属主

  • hourly daily weekly monthly

每小时 每天 每周

  • maxage maxsize

滚动的时候检查最大文件存在时间 如果超过这个时间就删除 滚动的时候检查最大文件大小 如果超过这个大小就删除 即使它没到指定的时间

  • minsize

滚动的最小的大小 如果每超过 就不滚动

  • missingok

文件不存在也接受,不会报错

logrotate加完可以自己测试下

1
logrotate -f /etc/logrotate.d/xxxx

sort分隔符号

1
sort -t'.'

arp扫描网段机器

1
2
sudo arp-scan --interface=enp3s0 --localnet
sudo arping -I enp3s0 192.168.0.177

find的时候忽略某个path

1
find / -size +100M -not -path "/data/*"

openssl req测试证书

压缩图片

1
2
sudo apt-get install imagemagick
mogrify -resize 50% -quality 85% {*.jpg,*.png}

合并两行

getline会进入下一行 此时 $0就是下一行的内容了,所以合并两行前保存一份

1
awk '{tmp=$0;getline;print tmp;"\t"$0}' test