# error cases # case: wrong password (special characters that can not pass through command line) # case: wrong source directory(caused by wrong spell or format is not correct) # case: access control issue. # case: ubuntu iptables # case: proxy(router)firewall
# case: china character show incorrectly. export LC_ALL=zh_CN.utf8 # before you set, make sure to run $ locale -a to see all language supported.
mount iso file
1 2
$ mount -o loop disk.iso /mnt/disk $ umount /mnt/disk
mount a raw file
1 2 3 4 5 6 7 8 9 10 11 12
# check disk type raw or qcow2 $ qemu-img info disk.img ... file format: raw ...
# get file system type $ blkid disk.img
# mount it $ mount -t xfs disk.img /mnt/disk $ umount /mnt/disk
# use a free nbd device $ qemu-nbd -c /dev/nbd100 disk.qcow2
# mount the first partition or second .. $ fdisk /dev/nbd100 -l Disk label type: dos Disk identifier: 0x000eb26e
Device Boot Start End Blocks Id System /dev/nbd100p1 * 2048 616447 307200 83 Linux /dev/nbd100p2 616448 1011460095 505421824 8e Linux LVM
$ mount /dev/nbd100p1 /mnt/disk
# =====fix the partition table========================= # if you see below error mount: special device /dev/nbd100p1 does not exist # if kpartx is not working, try partx -a /dev/nbd100 $ kpartx -a /dev/nbd100 # =====fix the partition table=========================
# mount this $ mount /dev/centos_dev/root /mnt/disk $ umount /mnt/disk $ qemu-nbd -d /dev/nbd100
# =========================another way: guestmount=================== # NOTE: this will start a micro vm(qemu-kvm) $ guestmount -a disk.qcow2 -i --ro /mnt/disk $ guestumount /mnt/disk # =========================another way: guestmount===================
lsattr and chattr
1 2 3 4 5 6 7 8 9 10 11 12
a: append only; 系统只允许在这个文件之后追加数据,不允许任何进程覆盖或截断这个文件。如果目录具有这个属性,系统将只允许在这个目录下建立和修改文件,而不允许删除任何文件。 c: compressed; 系统以透明的方式压缩这个文件。从这个文件读取时,返回的是解压之后的数据;而向这个文件中写入数据时,数据首先被压缩之后才写入磁盘。 d: no dump; 在进行文件系统备份时,dump程序将忽略这个文件。 i: immutable; 系统不允许对这个文件进行任何的修改。如果目录具有这个属性,那么任何的进程只能修改目录之下的文件,不允许建立和删除文件。 j: data journalizing; 如果一个文件设置了该属性,那么它所有的数据在写入文件本身之前,写入到ext3文件系统日志中,如果该文件系统挂载的时候使用了”data=ordered” 或”data=writeback”选项。当文件系统采用”data=journal”选项挂载时,所有文件数据已经记录日志,因此这个属性不起作用。仅仅超级用户或者拥有CAP_SYS_RESOURCE能力的进程可以设置和删除该属性。 s: secure deletion; 让系统在删除这个文件时,使用0填充文件所在的区域。 t: no tail-merging; 和其他文件合并时,该文件的末尾不会有部分块碎片(为支持尾部合并的文件系统使用)。 u: undeletable; 当一个应用程序请求删除这个文件,系统会保留其数据块以便以后能够恢复删除这个文件。 A: no atime updates; 告诉系统不要修改对这个文件的最后访问时间 D: synchronous directory updates; 任何改变将同步到磁盘;这等价于mount命令中的dirsync选项: S: synchronous updates; 一旦应用程序对这个文件执行了写操作,使系统立刻把修改的结果写到磁盘。 T: top of directory hierarchy; 如果一个目录设置了该属性,它将被视为目录结构的顶极目录
config nameserver
There are two ways to configure it, one shot or permanently
1 2 3 4 5 6 7
# one shot edit /etc/resolv.conf directly # Note: this file is dynamically created, if networking service restart or host reboots, its content will be overwritten
# you can also change the file 'attr' make it readonly to prevent rewriting $ chattr +i /etc/resolve.conf $ lsattr /etc/resolve.conf
# egrep: support basic regular pattern and extended pattern like + etc # grep : grep -E to use extended pattern and grep -v to search recursively # rgrep: recursively search # zgrep: like grep but support search .gz without extract content
-a treat binary as text -C | A | B num show NUM lines before/after/center the matching line -n show line number -l list file name that contains the content -H list file name and line number for matching -v list lines tht NOT matches -r recursively search subdir as well without follow symbolic links -R recursively search subdir as well with following symbolic links -o Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line, print matched part not the whole line!
-E extended pattern
# better to add alias to your bashrc # alias grep='grep -anH'
# use pattern, must quote 'ho+' to prevent the shell from erroneously replacing that # pattern with a list of filenames that match the pattern $ grep -anHE -C "ho*" *.txt
$ grep "home" *.txt # only *.txt file at current level $ grep -r "home" *.txt # all .txt files and subdir $ grep -v "Home" text.txt # list unmatched lines!!!
# grep chinese character $ grep -P '[\p{Han}]' *.txt
# show lines with ipv4 address $ grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' ip.txt
# show matched ipv4 address only $ grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' ip.txt
# lists the state of services controlled by System V and upstart $ service --status-all output format: + running - stopped ? unknown(managed by upstart)
/etc/init/dhcp.conf ---service name==dhcp # !!!plain txt, but with upstart format!!!
# dhcp.conf file # UpStart service config # details in http://upstart.ubuntu.com/cookbook/ description "dhcp server"
# Runlevel start on runlevel [345] stop on runlevel [!345]
# Umask umask 0007
# Core limit limit core unlimited unlimited
# Expect the process executed to call fork # fork: exactly once. # daemon: exactly twice. expect fork
# Respawn the job up to 3 times within a 5 second period. # If the job exceeds these values, it will be stopped and # marked as failed. respawn respawn limit 3 5
# Redirect console to /var/log/upstart/*.log console log
# Hooks pre-start script echo"# Starting at $(date -u +'%Y-%m-%dT%H:%M:%S.%NZ')" # Create run time file directory mkdir -m 0755 -p /var/run/dhcp end script
post-start script echo"# Started at $(date -u +'%Y-%m-%dT%H:%M:%S.%NZ')" end script
pre-stop script echo"# Pre-Stopping at $(date -u +'%Y-%m-%dT%H:%M:%S.%NZ')" end script
post-stop script echo"# Stopped at $(date -u +'%Y-%m-%dT%H:%M:%S.%NZ')" end script
# Start the process exec start-stop-daemon --start --oknodo --chuid dhcp --group dhcp --umask 0007 --exec /opt/bin/dhcp-s -f /config/dhcp.cfg
# comment the above line, then run it from shell, run it in foreground!!! $/opt/bin/dhcp-s -f /config/dhcp.cfg
write systemd service
/usr/lib/systemd/system is the path for service from rpm, pkg etc, so it’s common, if you want to add proxy due to your company, you should put specific conf for that service at /etc/systemd/system.
systemd service from pkg: /usr/lib/systemd/system
systemd service conf and local service not from pkg: /etc/systemd/system/
keywords
After=: only checks if the unit is activated already, and does not explicitly activate the specified units.
Requires=: The units listed in Requires are activated together with the unit. If any of the required units fail to start, the unit is not activated.
Wants=: This directive is similar to Requires= , but less strict. Systemd will attempt to start any units listed here when this unit is activated. If these units are not found or fail to start, the current unit will continue to function. This is the recommended way to configure most dependency relationships.
service daemon mode or not As systemd must get the exit code to determine if the service starts or not, hence if service can NOT run in daemon mode, it must runs in background!!!, otherwise systemd can NOT know if it starts or not and always restart it again and again.
later on to check the env of a given process by /proc/19571/environ
systemd restart systemd services have start rate limiting enabled by default. If service is started more than StartLimitBurst times in StartLimitIntervalSec seconds is it not permitted to start any more. This parameters are inherited from DefaultStartLimitIntervalSec(default 10s) and DefaultStartLimitBurst(default 5) in /etc/systemd/system.conf, but you can disable start rate like this.
1 2 3 4 5 6 7 8 9
[Service] Restart=always # time to sleep before restarting a service RestartSec=1
[Unit] # StartLimitIntervalSec in recent systemd versions StartLimitInterval=0 # StartLimitIntervalSec=0
systemd service parameter In some case, service file can use variable that’s defined outside, like this /usr/lib/systemd/system/crond.service
like $CRONDARGS and $MAINPID where are they defined, actually, they defined at /etc/sysconfig/crond must has the same name(crond) without service as suffix, systemd daemon will read this file and pass variable to service.
1 2 3
# Settings for the CRON daemon. # CRONDARGS= : any extra command-line startup arguments for crond CRONDARGS=
# -b mean since recent boots $ sudo journalctl --no-pager -b -u docker.service
# -p: Filter output by message priorities # "emerg" (0), "alert" (1), "crit" (2), # "err" (3), "warning" (4), "notice" (5), # "info" (6), "debug" (7). # If a single log level is specified, all messages with this log level or a lower (hence more important) log level are shown. $ sudo journalctl --no-pager -b -u docker.service -p 4
# with time range(relative and absolute) # last two hours ago $ sudo journalctl --no-pager -u docker.service -p 4 -S -2h # last 15 minutes ago $ sudo journalctl --no-pager -u docker.service -p 4 -S -15m
$ TM=$(date"+%H:%M:%S") # wait a while $ sudo journalctl -k -p err --no-pager --since=$TM
# since 9am $ journalctl --since 09:00
# time range $ journalctl --since "2015-01-10" --until "2015-01-11 03:00"
# show journal disk usage $ sudo journalctl --disk-usage
change systemd log level to debug /etc/systemd/system.conf
add samba user $ sudo smbpasswd -a user1 (user1 must be a system user as well!!!) edit /etc/samba/smb.conf with below content
# A publicly accessible directory, but read only, except for people in # the "staff" group [global] log level = 5
[share] comment = public share path = /home/share public = yes writable = no printable = no valid users = user1 user2
sudo service smb restart
# check exported dir by samba server smbclient -L 192.168.56.101
Enter SAMBA\root's password:
Sharename Type Comment --------- ---- ------- onedrive Disk one drive IPC$ IPC IPC Service (Samba 4.10.16) Reconnecting with SMB1 for workgroup listing.
through mount command,you can mount remote directory(linux) to the local machine over network. make sure the kernel supports nfs(server) before you use 'mount' command. by default Ubuntu disables nfs.
On server side
steps 1: install nfs if it is not installed Ubuntu18 $sudo apt-get install nfs-kernel-server Centos7 $yum install -y nfs-utils
steps 2: server exports a directory, edit /etc/exports file with something like this: /home/share/ 192.168.1.20(rw,insecure,sync,all_squash) /home/share/ 192.168.1.20(rw,insecure,sync,all_squash,anonuid=100,anongid=101) /home/share/ 192.168.1.20(rw,insecure,sync,no_root_squash) /home/share/ 192.168.1.20(rw,insecure,sync,no_root_squash,anonuid=100,anongid=101) (override the attributes for clinet<-->192.168.1.20 )
[ nfsd bases its access control to files on the server machine on the uid and gid provided in each NFS RPC request. The normal behavior a user would expect is that she can access her files on the server just as she would on a normal file system. This requires that the same uids and gids are used on the client and the server machine. This is not always true, nor is it always desirable.
Very often, it is not desirable that the root user on a client machine is also treated as root when accessing files on the NFS server. To this end, uid 0 is normally mapped to a different id: the so-called anonymous or nobody uid. This mode of operation (called `root squashing') is the default, and can be turned off with no_root_squash.
By default, exportfs chooses a uid and gid of 65534 for squashed access. These values can also be overridden by the anonuid and anongid options. Finally, you can map all user requests to the anonymous uid by specifying the all_squash option.
Here's the complete list of mapping options:
root_squash Map requests from uid/gid 0 to the anonymous uid/gid. Note that this does not apply to any other uids or gids that might be equally sensitive, such as user bin or group staff.
no_root_squash Turn off root squashing. This option is mainly useful for diskless clients.
all_squash Map all uids and gids to the anonymous user. Useful for NFS-exported public FTP directories, news spool directories, etc. The opposite option is no_all_squash, which is the default setting.
anonuid and anongid These options explicitly set the uid and gid of the anonymous account. This option is primarily useful for PC/NFS clients, where you might want all requests appear to be from one user. As an example, consider the export entry for /home/joe in the example section below, which maps all requests to uid 150 (which is supposedly that of user joe).
On client side check the export list #showmount -e $server_ip
steps 5: client mounts the dieretory #sudo mount -t nfs serverip:/home/share /media/share
(don't support user and password, create a user belongs to other group,so the permission of this user is determined by the configuration of /etc/exports )
Permission denied when write on nfs dir, even export with RW 1. check the mount user at client, if it's root, make sure export with no_root_squash set. 2. check /etc/exports to see RW is set. if you have anything wrong, please restart the service
B: show what nfs server exports to client!!! #showmount -e remote_nfs_server #showmount -e show what my self exported by nfs
C: FAQ "mount.nfs: access denied by server while mounting" 1 illegal port (client uses port larger than 1024) cat /var/log/messages | grep mount Jan 2 12:49:04 localhost mountd[1644]: refused mount request from 192.168.0.100 for /home/nfsshare/ (/home/nfsshare): illegal port 1689
FIX: add 'insecure' at server and restart nfs server
2 client and server use different nfs version Try use other version to connect with server -o "vers=3"
mount -v -o "vers=3" -t nfs 10.117.7.201:/root/jason /media
3 client must have the right to local mount point like /media
run your task daily, weekly etc
use cron daemon to execute schedule job, there are two ways you can choose to run your task one is user predefined period like daily, weakly, minutes etc, the other is defined own schedule whenever you want.
the maximal random delay added to the base delay of the jobs
RANDOM_DELAY=45
the jobs will be started during the following hours only
START_HOURS_RANGE=3-22
#period in days delay in minutes job-identifier command 1 5 cron.daily nice run-parts /etc/cron.daily 7 25 cron.weekly nice run-parts /etc/cron.weekly @monthly 45 cron.monthly nice run-parts /etc/cron.monthly`
debug cron
some checks
username is needed for jobs in cron.d and /etc/crontab are system jobs.
when username is used, should load user env from profile and set PATH for python, otherwise, cron has nothing with env(like $PATH set by profile not seen by cron)
1 steps of configuring bind9 1.1 edit /etc/bind/name.conf.local with the content below zone "example.com" { type master; file "/var/cache/bind/db.example.com"; allow-update {any;}; allow-transfer {any;}; allow-query {any;};
}; zone "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.ip6.arpa" { type master; file "/var/cache/bind/db.rev.2000"; allow-update {any;}; allow-transfer {any;}; allow-query {any;}; };
#edit /var/cache/bind/db.rev.2000 with content below $ORIGIN . $TTL 10800 ; 3 hours 0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.ip6.arpa IN SOA ns1.example.com.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.ip6.arpa. root.example.com. ( 2002111312 ; serial 28800 ; refresh (8 hours) 14400 ; retry (4 hours) 3600000 ; expire (5 weeks 6 days 16 hours) 86400 ; minimum (1 day) ) NS ns1.example.com. $ORIGIN 0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.ip6.arpa.
2 update AAAA using nsupdate #nsupdate >server 2000::1(specify the dns server) >update add worf.example.com 7200 IN AAAA 2000::58(zone example.com must be configured at dns server) >send (send the update) 3 query AAAA record #dig @2000::1(dns server) worf.example.com AAAA
put file in memory
For faster run, you can put files in memory, create a mount point with tmpfs, then put files there, but files are lost when it’s umounted or system boots, actually, you do not need to create this ram disk by yourself, system already creates somes for you, it’s /run, /dev/shm
# ssh client timeout after sometime # edit sshd config and restart sshd service # edit /etc/ssh/sshd_config ClientAliveInterval 60
$ service sshd restart
# ssh terminal timeout due to “timed out waiting for input: auto-logout” # edit ~/.bashrc unset TMOUT
Reset by peer even iptable and firewall is disabled
1 2 3 4 5 6 7 8
$ grep sshd /var/log/syslog Oct 16 08:59:45 openstack sshd[1214]: error: Could not load host key: /etc/ssh/ssh_host_rsa_key Oct 16 08:59:45 openstack sshd[1214]: error: Could not load host key: /etc/ssh/ssh_host_dsa_key Oct 16 08:59:45 openstack sshd[1214]: error: Could not load host key: /etc/ssh/ssh_host_ecdsa_key
# scp is used on client to copy data to server # on client $ mkdir -p /home/lzq/.ssh # create parent dir as well if not exist # create private and public key pairs $ ssh-keygen -t rsa (just enter, no other input)
# copy public key to ssh server $ scp /home/lzq/.ssh/id_rsa.pub root@serverip:/root/.ssh/new.pub
# show all processes of a given user $ ps -u $user $ pstree $user -ap # show a process and its owner $ ps u $pid
# show all processes of given group $ ps -g $user # show all groups from local and remote LDAP $ getent group # show all users from local and remote LDAP $ getent passwd # add a group with given id and name at local $ groupadd [-g 6002] school # create a system group $ groupadd -r $group_name # delete a group from local $ groupdel $group_name
# show groups for current user $ groups # show groups for a given user $ groups jason
# --- add a user to group does not effect for the given login # --- you need to login again or use $ newgrp $group
# add/delete an existing user to a given group $ gpasswd -a $user$group $ gpasswd -d $user$group $ gpasswd --members $user1, $user2$group # add user to given group $ sudo usermod -a -G root jason # add jason to root group
# show id of current user $ id -ru # show current user $ id -un # show id of given user(local or remote) $ id$user1
# add a new user or remove a user from local # adduser [--home DIR] [--shell SHELL] [--no-create-home] [--uid ID] [--ingroup GROUP | --gid ID] [--disabled-password] [--disabled-login] user
# -r means deleting its home directory $ userdel -r $user
# change passwd for current user $ passwd $ passwd $user
/etc/sudoers(Ubuntu18)
it’s a file used to control what commands a user can run
1
$ sudo visudo
/etc/sudoers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# User privilege specification, root user can run all with any user on all hosts with any command!!! root ALL = (ALL) ALL [user] [host] = [runas user] commands
jorge ALL=(root) NOPASSWD: /usr/bin/find, /bin/rm # user jorge can run as root user!!! # the command must have absolute path!!!, user jorge can run /bin/rm as root without password required.
# Allow members of group sudo to execute any command after they have provided their password %sudo ALL=(ALL) ALL
# Members of the admin group may gain root privileges # allow members of group admin/users to execute any command with any user on all host without password. %admin ALL= (ALL) NOPASSWD: ALL %users ALL= (ALL) NOPASSWD: ALL [group] [host] = (runas user) commands
# lb user can run /bin/rm as root without password on jason_dev host
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
lb@jason_dev$sudorm xx sudo unable to resolve host jason_dev(hostname of my machine) # take long time to show such warning
# let's see how this happens and fix it
# step 1: check the user: lb, ok allowed to run /bin/rm # step 2: check host(as lb is only allowed to run on 10.10.10.3 # we must know what's ip for current machine(jason_dev) # check /etc/hosts, if not found # DNSLookUp # still not found, can't find get the above error)
# step 3: run rm with root and no password
# to avoid dnslook, add entry at /etc/hosts with
127.0.0.1 jason_dev
broadcast message to all users from terminal
1 2 3 4 5 6 7
$ wall 'hello everyone'
# send msg to one pts $ who root pts/8 2019-11-24 22:30 (10.20.6.117) root pts/9 2019-11-25 23:59 (10.20.6.117) $ write root pts/8
copy file from local to remote ssh server
1 2 3
# -r will follow symbol link $ scp -r username@hostB:/home/lzq/vim . $ scp -r vim username@hostB:/home/lzq/
backup file with progress bar locally
1 2 3 4 5 6 7 8 9 10
$ rsync -avP /home/lzq/Document /share/
# skip following symbol link rsync -a --no-links vim root@hostB:/root/
non-interactive terminal bash/csh/sh /etc/bashrc and $HOME/.bashrc
interactive terminal /etc/profile and $HOME/.profile
/etc/profile vs /etc/environment System-wide environment variables [ /etc/environment is not part of POSIX, it belongs to PAM (Pluggable Authentication Module), and only programs compiled with PAM support are able to use it (primarily login systems, which subsequently start the shell or user environment). This means it isn't even read by your shell. -------------------------------------------------------------------------------------------------------- You can see the programs using /etc/environment with grep -l pam_env /etc/pam.d/*. So /etc/environment is used for setting variables for programs which are usually not started from a shell -------------------------------------------------------------------------------------------------------- ] A suitable file for environment variable settings that affect the system as a whole (rather than just a particular user) is /etc/environment. An alternative is to create a file for the purpose in the /etc/profile.d directory.
/etc/environment
This file is specifically meant for system-wide environment variable settings. It is not a script file, but rather consists of assignment expressions, one per line.
FOO=bar
Note: Variable expansion does not work in /etc/environment.
/etc/profile.d/*.sh
Files with the .sh extension in the /etc/profile.d directory get executed whenever a bash login shell is entered (e.g. when logging in from the console or over ssh), as well as by the DisplayManager when the desktop session loads.
You can for instance create the file /etc/profile.d/myenvvars.sh and set variables like this:
While /etc/profile is often suggested for setting environment variables system-wide, it is a configuration file of the base-files package, so it's not appropriate to edit that file directly. Use a file in /etc/profile.d instead as shown above. (Files in /etc/profile.d are sourced by /etc/profile.)
/etc/default/locale is specifically meant for system-wide locale environment variable settings. It's written to by the installer and when you use Language Support to set the language or regional formats system-wide. On a desktop system there is normally no reason to edit this file manually.
The shell config file /etc/bash.bashrc is sometimes suggested for setting environment variables system-wide. While this may work on Bash shells for programs started from the shell, variables set in that file are not available by default to programs started from the graphical environment in a desktop session.
# show system reboot and shutodwn event # NOTE: last read files from /var/log/wtmp or /var/log/btmp $ last -xF reboot | head -3 reboot system boot 4.14.15-1.el7.el Fri May 17 04:45:16 2024 - Thu May 23 06:24:04 2024 (6+01:38) reboot system boot 4.14.15-1.el7.el Fri May 10 06:37:05 2024 - Thu May 23 06:24:04 2024 (12+23:46) reboot system boot 4.14.15-1.el7.el Fri May 10 06:29:01 2024 - Fri May 10 06:35:46 2024 (00:06)
$ last -xF shutdown
# show the latest reboot time $ who -b system boot 2024-05-17 04:45
$ uptime -s 2024-05-17 04:43:51
# show the lastest reboot $ last -x reboot | head -1
# show how lang system boots $ uptime
# disable selinux $ setenforce 0 # temporary close selinux OR edit /etc/selinux/config
In the event your Linux box experiences disk or file system issues you may receive a “Give root password for maintenance” prompt upon reboot. If you have your root password you can login but in the event your using ‘slide’ or ‘sudo’ for wheel access or you’ve just mis-placed your root password – you’ll need to reset it.
To reset your root password: 1. When the GRUB loader shows during boot press the spare bar to pause boot.
2. Select your boot kernel.
3. Type ‘e’ to edit the default kernel line.
4. Type ‘e’ again on the line that starts with ‘kernel’.
5. Add ‘init=/bin/bash’ to the end of the ‘kernel’ line then press enter.
6. Type ‘b’ to boot the modified kernel parameters.
7. Once you’re at the /bin/bash prompt you will need to remount the root file system as read/write in order to edit the passwd file:
# mount -o remount,rw /
8. Change your root password:
# passwd root
9. Remount the filesystem back to read only:
# mount -o remount,ro /
10. Reboot your server using CTR-ALT-DELETE.
11. You will now be able to login with your new root password and carry out the maintenance.
disable boot from save grub entry for grub2
1 2 3 4 5 6 7 8 9 10 11 12 13
Ubuntu18
GRUB_DEFAULT=saved GRUB_SAVEDEFAULT=true
to
GRUB_DEFAULT=0 (always first entry) GRUB_SAVEDEFAULT=false
then generate /boot/grub2/grub.cfg newly #grub2-mkconfig -o /boot/grub2/grub.cfg
force enter command-line mode when boots
1 2 3 4 5 6 7 8 9 10 11
$sudo vi /etc/default/grub
Do below changes: Comment the line GRUB_CMDLINE_LINUX_DEFAULT=”quiet splash”, by adding # at the beginning, which will disable the Ubuntu purple screen. Change GRUB_CMDLINE_LINUX=”” to GRUB_CMDLINE_LINUX=”text”, this makes Ubuntu boot directly into Text Mode. Uncomment this line #GRUB_TERMINAL=console, by removing the # at the beginning, this makes Grub Menu into real black & white Text Mode (without background image)
fstab is a configuration file that contains information of all the partitions and storage devices in your computer. The file is located under /etc, so the full path to this file is /etc/fstab.
/etc/fstab contains information of where your partitions and storage devices should be mounted and how. If you can't access your Windows partition from Linux, aren't able to mount your CD or write to your floppy as a normal user, or have problems with your CD-RW, you probably have a misconfigured /etc/fstab file. So, you can usually fix your mounting problems by editing your fstab file.
/etc/fstab is just a plain text file, so you can open and edit it with any text editor you're familiar with. However, note that you must have the root privileges before editing fstab. So, in order to edit the file, you must either log in as root or use the su command to become root.
Note that this system has two IDE partitions, one which is used as /, and the other used as /home. It also has two DOS partitions which are mounted under /mnt. Note the user option provided for the cdrom, and the floppy drive. This is one of the many default parameters you can specify. In this case it means that any user can mount a cdrom, or floppy disk. Other options will be dealt with later.
fstab file format explination
fstab consists of a number of lines (one for each filesystem) seperated into six fields. Each field is seperated from the next by whitespace (spaces/tabs).
So from the example given previously:
/dev/hdc /mnt/cdrom iso9660 noauto,ro,user 0 0
first field (/dev/hdc) is the physical device/remote filesystem which is to be described.
second field (/mnt/cdrom) specifies the mount point where the filesystem will be mounted.
third field (iso9660) is the type of filesystem on the device from the first field.
fourth field (noauto,ro,user) is a (default) list of options which mount should use when mounting the filesystem.
fifth field (0) is used by dump (a backup utility) to decide if a filesystem should be backed up. If zero then dump will ignore that filesystem. The sixth field (0) is used by fsck (the filesystem check utility) to determine the order in which filesystems should be checked.
If zero then fsck won't check the filesystem.
(as the example line above is a cdrom there is very little point in doing a fsck on it, so the value is zero).
File system mount options
As the filesystems in /etc/fstab will eventually be mounted using mount(8) it isn't surprising that the options field simply contains a comma-seperated list of options which will be passed directly to mount when it tries to mount the filesystem.
The options common to all filesystems are:
sync / async
All I/O to the file system should be done (a)synchronously.
auto
The filesystem can be mounted automatically (at bootup, or when mount is passed the -a option). This is really unnecessary as this is the default action of mount -a anyway.
noauto
The filesystem will NOT be automatically mounted at startup, or when mount passed -a. You must explicitly mount the filesystem.
dev / nodev
Permit any user to mount the filesyste. This automatically implies noexec,
exec / noexec
Permit/Prevent the execution of binaries from the filesystem.
suid / nosuid
Permit/Block the operation of suid, and sgid bits.
ro
Mount read-only.
rw
Mount read-write.
user
Permit any user to mount the filesystem. This automatically implies noexec, nosuid,nodev unless overridden.
nouser
Only permit root to mount the filesystem. This is also a default setting.
defaults
Use default settings. Equivalent to rw,suid,dev,exec,auto,nouser,async.
There are numerous options for the specific filesystes supported by mount. However these are some of the more useful, for the full list check out the man page for `mount`.
ext2
check={none, normal, strict} Sets the fsck checking level.
debug
print debugging info on each remount.
sb=n
n is the block which should be used as the superblock for the fs.
fat
check={r[elaxed], n[ormal], s[trict]}
Not the same as ext2. Rather deals with allowed filenames. See mount man page.
conv={b[inary], t[ext], a[uto]}
Performs DOS<->UNIX text file conversions automatically. See mount man page.
uid=n, gid=n
iso9660
norock
Disables Rock Ridge extensions.
fstab file Supported file systems list
affs - I have know idea what this is, if anyone else does please enlighten me.
coherent
ext - Don't use this. ext has been superseded by ext2.
ext2 - The standard Linux filesystem. (NB, this has nothing to do with extended partitions.)
fat - DOS.
hpfs - OS/2 High Performance File System.
iso9660 - CD-ROM's. Supports Rock Ridge extensions by default.
minix - can be useful for floppy disks.
msdos - Just fat with some addtional error checking.
nfs - Network FileSystem. Dealt with later.
proc - The process psudeo-filesystem now standard in Linux.
smb - Another network filesystem. Compatable with WFW, and NT. See Samba.
ufs - Unix FileSystem.
unsdos - Unix filesystem on a FAT partition.
vfat - MS's kludge of FAT to provide long filenames.
xenix
xiafs
deep in remove file
1 2 3 4 5 6 7 8 9
$ rm test.c # actually, kernel takes two steps to delete the file 1. remove fentry(then you can NOT see test.c) 2. free inode of this file if its reference count is 0 Only these two steps executed, the disk space is freed
# show all deleted files(not see from disk), but still opened by process $ lsof 2>/dev/null | grep deleted ovsdb-ser 1089 openvswitch 7u REG 253,0 159 69471332 /tmp/tmpfVYsNnz (deleted)
what about app opens a large file, during it’s reading, someone rm that file?
Only fentry is deleted, inode is not freed, as when app opens that file, it increments the reference of that inode when app closes that file, at that time, it will be deleted from disk.
$ mv a.c b.c # actually, fentry(b.c) points to inode of (a.c) # a.c(fentry is deleted), inode of (b.c) is freed if no use open it!!!
update file time
1 2 3 4 5 6 7
# Update the access and modification times of each FILE to the current time $ touch test.doc $ touch -d "2010-05-31 08:10:30" test.doc
# or change only one $ touch -m -d "2010-05-31 08:10:30" test.doc $ touch -a -d "2010-05-31 08:10:30" test.doc
cut command
1 2 3
# cut split string by tab by default, the first indiex if 1 $ echo"hello boy" | cut -d ' ' -f 1 hello
remove file named with special character
1 2 3 4 5 6 7 8 9
$ ls #a.c -a.c
$ rm'#a.c' $ rm \#a.c $ rm ./-a.c
# use eval $ eval"rm =1.3.0,"
display output to screen and also write it to file
1
$ echo"just a test" | tee log.txt
command xargs
1 2 3 4 5 6 7
# xargs will split parameters passed by tab or space, then call after command with splited parameter one by one $ echo"hello boy" | xargs rm rm: cannot remove 'hello': No such file or directory rm: cannot remove 'boy': No such file or directory
# if you see xargs: argument line too long $ xx | xargs -l1 rm# -l1 each time each parameter
find command(better use find file, not content of file)
# -name exactly match!!! # -iname case insensitive
# -type f | d | c | l(link) | b(block) | p(pipe) # -size n[cwbkMG] # 1M, -1k # -maxdepth 1 (max depth) # -perm 755 (permission with 755) # -user jason
$ find - type f -size +1k -name "/*test.c"
# when use | for find better to use -print0 $ find . -type f -print0 | xargs -0 rm -f
# more exec on some file $ find . -type f -print0 -execls {} \; -execrm -f {} \;
$ find . -type f -print0 -execrm -f {} \; # in some case it may meet error 'too long parameter/argument' something like use, use find | xargs to sovle it
print0: print the full file name on the standard output, followed by a null character (instead of the new-line character that ‘-print’ uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the ‘-0’ option of xargs.
# find file with executable attribute $ find . -executable
# negative $ find . ! -name "*.txt" # find with two or more conditions
$ find . -iname class.* -o -name basic*
rename a batch of files with pattern
1 2 3
$ rename 's/ //g' *.txt # remove space from filename $ find . -type f -exec rename 's/ //g' {} \; # remove space from file name only $ find . name "* *" -exec rename 's/ //g' {} \; # remove space from file name or dir name
#!/bin/bash logger -t "title""message" /* use tcp socket server port 601 */ logger -d "title""message" /* use udp socket server port 514 */ logger -u /dev/log "title""message" # [looger is a command that can write syslog]
rsyslog conf
1 2 3 4 5 6 7 8
In /var/log/syslog you may see these kind of message "Previous message repeated X times", where X is a number
it's useful for supressing message, but for debugging, you can't see it directly, turn it off by(ubuntu)
edit /etc/rsyslog.conf
$RepeatedMsgReduction off
wget
download particular files from particular website
1 2 3 4 5
$ wget -r -A .html http://cunit.sourceforge.net/doc/ $ wget -r --no-parent -A '*.deb' http://www.xyun.com/amd64/
----sda1 has 100G, but the new add part should format with fs--- Device Start End Sectors Size Type /dev/sda1 227328 209715166 209487839 99.9G Linux filesystem /dev/sda14 2048 10239 8192 4M BIOS boot /dev/sda15 10240 227327 217088 106M EFI System
$ sudo resize2fs /dev/sda1 resize2fs 1.44.1 (24-Mar-2018) Filesystem at /dev/sda1 is mounted on /; on-line resizing required old_desc_blocks = 2, new_desc_blocks = 13 The filesystem on /dev/sda1 is now 26185979 (4k) blocks long.
count line of code
There are lots of tools for counting code, two fast and popular ones, scc and tokei
nc is command to setup tcp(tls)/udp server or used as tcp/udp client
1 2 3 4 5 6 7 8 9
# start tcp server $ nc -lv nc -lv Ncat: Version 7.50 ( https://nmap.org/ncat ) Ncat: Listening on :::31337 Ncat: Listening on 0.0.0.0:31337
# send tcp data with nc $ echo"hello" | nc localhost 31337
check virtual disk real size
1 2 3 4
# use -s option # disk size set 10G, but real size is 133M $ ls -slh pod-23vmqfdjge-2021-09-08-21-00-07.raw 133M -rw-r--r-- 1 root root 10G Sep 8 20:51 pod-23vmqfdjge-2021-09-08-21-00-07.raw
# show current timezone $ ls -al /etc/localtime lrwxrwxrwx. 1 root root 35 Sep 14 09:33 /etc/localtime -> ../usr/share/zoneinfo/Asia/Shanghai
# OR use command line $ timedatectl status Local time: Tue 2021-09-14 09:36:45 CST Universal time: Tue 2021-09-14 01:36:45 UTC RTC time: Tue 2021-09-14 01:36:51 Time zone: Asia/Shanghai (CST, +0800) NTP enabled: yes NTP synchronized: no RTC inlocal TZ: no DST active: n/a
# show all available zones $ timedatectl list-timezones
# set correct zone $ timedatectl set-timezone Asia/Shanghai
# ntpdate will update time with ntpserver to the zone you're using # if you set zone incorrect, the time you get may be not expected. $ ntpdate cn.pool.ntp.org 14 Sep 09:34:01 ntpdate[1524]: adjust time server 124.108.20.1 offset 0.028670 sec
# without ntp, set time by date directly, note for web GMT(UTC) is returned!!! # so must with 'Z' suffix to convert to local time zone $ date -s "$(curl -H'Cache-Control:no-cache' -sI baidu.com | grep '^Date:' | cut -d' ' -f3-6)Z" # use proxychains for net proxy $ date -s "$(proxychains -q curl -H'Cache-Control:no-cache' -sI baidu.com | grep '^Date:' | cut -d' ' -f3-6)Z"
# use proxychains for net proxy $ date -s "$(proxychains -q curl -H'Cache-Control:no-cache' -sI google.com | grep '^Date:' | cut -d' ' -f3-6)Z"
# state of process can be in below code D Uninterruptible sleep (usually IO), in kerenl space, can not wake up by signal!! R Running or runnable (on run queue) S Interruptible sleep (waiting for an event to complete) T Stopped, either by a job control signal(kill -STOP $pid) or because it is being traced. Z Defunct ("zombie") process, terminated but not reaped by its parent. When a process finishes its task, it `releases the system resources it was using and cleans up its memory`. However,` its entry from the process table is not removed`, and its status is set as EXIT_ZOMBIE.
For BSD formats and when the stat keyword is used, additional characters may be displayed: < high-priority (not nice to other users) N low-priority (nice to other users) L has pages locked into memory (for real-time and custom IO), never swaped the memory out to disk!!! s is a session leader l is multi-threaded (using CLONE_THREAD, like NPTL pthreads do) + is in the foreground process group
# show more info(backtrace) about D process $ echo w > /proc/sysrq-trigger This command produces a report and a list of all processes in D state and a full kernel stack trace to /var/log/messages $ grep 'state:D stack' /var/log/messages
# show all processes id in D state $ ps axl | awk '$10 ~ /D/'
# show all processes in Zombine state $ ps axl | awk '$10 ~ /Z/'
# show pstree of given process, show tree from 1 to its child with args
# pstree -ansp 115764, as you can seee under docker-containe,115764, there are many {docker-containe},$id which is thread of {docker.containe} process!!! systemd,1 --switched-root --system --deserialize 21 └─docker-containe,115764 c946e9c0e6845d4496d808c317d20a54086203932d940b103f9705322f4e9308 /var/run/docker/libcontainerd/c946e9c0e6845d4496d808c317d20a54086203932d940b103f9705322f4e9308 /usr/libexec/docker/docker-runc-current ├─{docker-containe},115765 ├─{docker-containe},115766 ├─{docker-containe},115767 ├─{docker-containe},115768 ├─{docker-containe},115770 ├─{docker-containe},115771 ├─{docker-containe},115772 ├─{docker-containe},115774 ├─{docker-containe},115775 └─(tail,116336)
# clear process in D state Reboot, Reboot!
# clear process in Z(zombine) state We can’t really kill a zombie process since it’s already dead. However, there are a few workarounds we can use to clean up a zombie process 1. Manually send the SIGCHLD signal to the parent of a zombie process, it works only when parent process handles such signal!!! kill -s SIGCHLD $parent_pid 2. Kill parent process.
but if the parent process is init(pid 1), so that you can NOT kill init This pretty much leaves you with two options.
- Manually modify the process table, eg. create a dummy process, link the [defunct process] as a child of the dummy, thenkill them off. Quite dangerous, and you may have to manually clean up other process resources such as semaphores and file handles.
- Reboot the system
copy excludes some dir
1 2 3 4
# copy html dir to dev without sites/video # The the --exclude path is relative to the source directly. Even if you put full absolute path, it will not work # -v is for verbose, -a is for archive mode which means you want recursion and want to preserve almost everything $ rsync -av --exclude 'sites/video' /var/www/html /var/www/dev
show start time of process
1 2 3 4 5 6 7 8 9 10 11
$ ps -eo pid,lstart,cmd PID STARTED CMD 1 Mon Jan 24 11:21:04 2022 /usr/lib/systemd/systemd --system --deserialize 15 2 Mon Jan 24 11:21:04 2022 [kthreadd] 4 Mon Jan 24 11:21:04 2022 [kworker/0:0H] 6 Mon Jan 24 11:21:04 2022 [ksoftirqd/0] 7 Mon Jan 24 11:21:04 2022 [migration/0] 8 Mon Jan 24 11:21:04 2022 [rcu_bh] 9 Mon Jan 24 11:21:04 2022 [rcu_sched] 10 Mon Jan 24 11:21:04 2022 [lru-add-drain] 11 Mon Jan 24 11:21:04 2022 [watchdog/0]
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1 root 20 0 191832 4776 2620 S 0.0 0.1 0:07.57 systemd 2 root 20 0 0 0 0 S 0.0 0.0 0:00.02 kthreadd 4 root 0 -20 0 0 0 S 0.0 0.0 0:00.00 kworker/0:0H 6 root 20 0 0 0 0 S 0.0 0.0 0:01.06 ksoftirqd/0
us - user cpu time (or) % CPU time spent in user space sy - system cpu time (or) % CPU time spent in kernel space ni - user nice cpu time (or) % CPU time spent on low priority processes id - idle cpu time (or) % CPU time spent idle wa - io wait cpu time (or) % CPU time spent inwait (on disk) hi - hardware irq (or) % CPU time spent servicing/handling hardware interrupts si - software irq (or) % CPU time spent servicing/handling software interrupts st - steal time % CPU time in involuntary wait by virtual cpu while hypervisor is servicing another processor (or) % CPU time stolen from a virtual machine
NOTE: it is aggregate value, if you want to check usage for each CPU press `top` then press 1.
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1856 mongod 20 0 1604016 116512 11132 S 0.3 1.4 2:23.77 mongod 2148 root 20 0 164024 6480 4952 S 0.3 0.1 0:15.29 sshd
NOTE: By default, the top will refresh the output every 3 seconds.
TIPS: press `c` to show full path press `o` to filter based on Field. example(support partial match): COMMAND=libvirt press `=` to clear filter press `e` to switch memory unit(kb, mb,gb,tb) for mem colums by default is kb
# sort by CPU or memory $ top -o %CPU $ top -o %MEM # OR $ top then press P M (RES not VIRT)
# add more fields to see TIP: 1 `press f` to show all fields 2 move cursor to the line 3 `press space` to define this line 4 `press right arrow` to select it then move the field to righ position
# check current swap size $free -h total used free shared buff/cache available Mem: 31G 5.5G 25G 8.7M 870M 25G Swap: 31G 0B 31G
$swapon -v NAME TYPE SIZE USED PRIO /dev/dm-1 partition 32G 0B -2
# check trend that swap is used from global, each cgroup can change it within that group $cat /proc/sys/vm/swappiness
# temporary disable/enable swap $swapon -a # when swap is off, all data in swap(disk) will be swap in to memory!!! if not enough memory is avaiable, swapoff will fail with 'can $swapoff -a
set process prority
Priority value(PRI) — The priority value is the process’s actual priority which is used by the Linux kernel to schedule a task. In Linux system priorities are 0 to 139 in which 0 to 99 for real-time and 100 to 139 for users.
Nice value(NI) — Nice values are user-space values that we can use to control the priority of a process. The nice value range is -20 to +19 where -20 is highest, 0 default and +19 is lowest.
The relation between nice value and priority is as such Priority_value = Nice_value + 20
1 2 3 4 5 6 7 8 9
# nice value(NI) can be range -20(highest) to 19(lowest)
# start process with nice value, threads will inherited parent's nice value $ nice -5 ./app arg1
# change nice value after process starts(only change 1055, not it's children) $ renice -n -10 -p 1055 # renice process which has multi-threads $ renice -n -10 -p `ps --no-heading -Lo tid 1055`
split large file into smaller ones
Some website does not allow to upload larger file, split it into smaller ones.
1 2 3 4 5 6 7 8 9 10
# -d use digital sufffix # -a one digital # centos. as prefix $ split -b 1G CentOS-7-x86_64-GenericCloud.qcow2 -d -a 1 centos. centos.0 centos.1
# combine them to orignal one # NOTE: not >> $ cat centos.* > CentOS-7-x86_64-GenericCloud.qcow2
setup ftp server (centos)
The difference for modes is who is the initialator for data connection, for active mode, server always use 20 as the source port.
In passive mode, the client uses the control connection to send a PASV command to the server and then receives a server IP address and server port number from the server, which the client then uses to open a data connection from an arbitrary client port to the server IP address and server port number received.
vsftpd
By default, vsftpd allows local users to login in and switch to its $HOME
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
$ yum install vsftpd $ service vsftpd start
# edit /etc/vsftpd/vsftpd.conf
# Use virtual HOME for local user not $HOME/$USER # https://www.ryadel.com/en/vsftpd-configure-different-home-folder-each-user-specific-directory/
# test it
$ yum install -y ftp # standard port 21 for ftp $ ftp localhost
# open on different port $ ftp ftp>open localhost 6621
# show thread name of a process $ ps -L -o tid,pid,comm 19562 PID TID COMMAND 19562 19562 qemu-kvm 19562 19565 qemu-kvm 19562 19566 qemu-kvm 19562 19567 IO iothread1 19562 19571 CPU 0/KVM 19562 19572 CPU 1/KVM 19562 19574 vnc_worker
# show custom output for given process $ ps -eo user,pid,ppid,%cpu,%mem,vsz,rss,pri,ni,start,time,cmd -fp $pid
# show custom output and more $ ps -eo user,pid,ppid,%cpu,%mem,vsz,rss,pri,ni,start,time,cmd USER PID PPID %CPU %MEM VSZ RSS PRI NI STARTED TIME CMD root 1 0 0.0 0.0 191528 3216 19 0 Jan 11 00:00:09 /usr/lib/systemd/systemd --switched-root --system --deserialize 22 root 2 0 0.0 0.0 0 0 19 0 Jan 11 00:00:00 [kthreadd] root 4 2 0.0 0.0 0 0 39 -20 Jan 11 00:00:00 [kworker/0:0H] root 6 2 0.0 0.0 0 0 19 0 Jan 11 00:00:03 [ksoftirqd/0] root 7 2 0.0 0.0 0 0 139 - Jan 11 00:00:00 [migration/0] root 8 2 0.0 0.0 0 0 19 0 Jan 11 00:00:00 [rcu_bh]
# The "+" is optional since default direction is increasing numerical or lexicographic order $ ps -eo user,pid,ppid,%cpu,%mem,vsz,rss,pri,ni,start,time,cmd --sort=+rss $ ps -eo user,pid,ppid,%cpu,%mem,vsz,rss,pri,ni,start,time,cmd --sort=rss
# top five memory usage process $ ps -eo user,pid,ppid,%cpu,%mem,vsz,rss,pri,ni,start,time,cmd --sort=-rss | head -6
# show memory in MB unit(format field 7) only support format one field by numfmt!! $ ps -eo user,pid,ppid,%cpu,%mem,vsz,rss,pri,ni,start,time,cmd --sort=-rss | numfmt --header --field 7 --to=iec --from-unit=1024
# show rss field value(default unit KB) only $ps -q 1354 -o rss= 51464 # show given process only $ ps -fp $pid
# there are two process PID 1 and PID 2 which have no parent! # all user processes are child of PID 1 # all kernel processes are child of PID 2 # UID PID PPID C STIME TTY TIME CMD # root 1 0 0 Mar08 ? 00:00:59 /usr/lib/systemd/systemd --switched-root --system --deserialize 21 # root 2 0 0 Mar08 ? 00:00:02 [kthreadd]
# only show user application process not kernel thread $ ps -ef | awk '$3!="2" {print $0}' # only show kernel thread $ ps -ef | awk '$3=="2" {print $0}'
lsmem lists memory blocks and their state; these reflect physical memory and are counted in units of memory blocks, i.e. 128MiB on your system. To do this, lsmem reads information made available by the kernel in /sys/devices/system/memory. On your system, the kernel tracks 64 memory blocks for a total of 8GiB.
free lists memory that’s usable by the system; “total” is the amount of physical memory, minus memory reserved by the system (for the firmware’s purposes mostly) and the kernel’s executable code. free reads this information from /proc/meminfo.
# global setting, this works only when application use such environment variable $ cat ~/.bashrc export http_proxy='http://10.226.198.162:3128' export https_proxy='http://10.226.198.162:3128'
# pip proxy or set global HTTP_PROXY $ pip install --proxy http://user:password@proxyserver:port TwitterApi
# proxychains to force any application to use proxy # NOTE: it supports TCP only (no UDP/ICMP etc). $ yum install proxychains-ng $ cat /etc/proxychains.conf strict_chain proxy_dns remote_dns_subnet 224 tcp_read_time_out 15000 tcp_connect_time_out 8000 [ProxyList] http 192.226.136.231 3128 # then run app this way $ proxychains pip install ipvsd
# global setting(default for process, but can be reset by process) $ ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 1030598 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 102400 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 10240 cpu time (seconds, -t) unlimited max user processes (-u) 307200 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited
# real limits of each process
$ cat /proc/116446/limits Limit Soft Limit Hard Limit Units Max cpu time unlimited unlimited seconds Max file size unlimited unlimited bytes Max data size unlimited unlimited bytes Max stack size 10485760 20971520 bytes Max core file size 0 unlimited bytes Max resident set unlimited unlimited bytes Max processes 307200 307200 processes Max open files 204800 204800 files Max locked memory 65536 65536 bytes Max address space unlimited unlimited bytes Max file locks unlimited unlimited locks Max pending signals 1030598 1030598 signals Max msgqueue size 819200 819200 bytes Max nice priority 0 0 Max realtime priority 0 0 Max realtime timeout unlimited unlimited us
random lines
use shuf to write a random permutation of the input lines to standard output.
1 2 3 4 5
# standoutput $ shuf new.txt
# file as output $ shuf new.txt -o random.txt
pgrep vs pidof
The programs pgrep and pidof are not quite the same thing, but they are very similar. For example:
# get children process(not thread) of given pid $ pgrep -P 1824 1825
# it shows process and threads as well # 1694, 1695 are threads not process $ pstree -p 1824 dnsmasq(1824)───dnsmasq(1825)
As you can see, pidof failed to find a match for [i]ref. This is because pidof program returns a list of all process IDs associated with a program called program. On the other hand, pgrep re returns a list of all process IDs associated with a program whose name matches the regular expression re.
In their most basic forms, the equivalence is actually: $ pidof 'program' == $ pgrep '^program$'
remove cgroup from /sys/fs
First you have to move all processes from this cgroup, then delete it, otherwise it, error shows cgroups can't be cleaned up: Device or resource busy
1 2 3 4 5 6 7 8
# use cpu cgroup as an example $ cat /sys/fs/cgroup/cpu/test/cgroup.procs 8666 # move 8666 to root group, also moved it from test group $ echo 8666 >/sys/fs/cgroup/cpu/cgroup.procs
# list all memory used by a process # numa bind policy for huage page, default policy for others $ cat /proc/82389/numa_maps 7f069ab9a000 default file=/usr/lib64/ld-2.17.so anon=1 dirty=1 N0=1 kernelpagesize_kB=4 7f0588000000 bind:0-1 file=/mnt/huge_2MB/libvirt/qemu/141-i-f2w3m8owht/qemu_back_mem._objects_ram-node0.2IyOfZ\040(deleted) huge dirty=2048 mapmax=4 N0=2048 kernelpagesize_kB=2048 # the first column is memory address # the second column is numa node used by this memory # default means all numa nodes # bind:0-1 means only numa node 0 and node 1 are allowed for this memory, but we may only used one node. # the third column is file related # the last column is kernel page for this memory # the one before last colum is the page count of this memory on each node # N0=2048 means allocate 2048*kernelpagesize_kB on node 0
$ numastat -p 82389 Per-node process memory usage (in MBs) for PID 82389 (qemu-kvm) Node 0 Node 1 Total --------------- --------------- --------------- Huge 4096.00 0.00 4096.00 Heap 65.16 0.00 65.16 Stack 0.03 0.00 0.04 Private 32.34 1.21 33.55 ---------------- --------------- --------------- --------------- Total 4193.53 1.21 4194.74
# total numa stat $ numastat node0 node1 numa_hit 271446988685 306962573062 numa_miss 144931 15014353674 numa_foreign 15014353674 144931 interleave_hit 35352 35604 local_node 271445218315 306961782987 other_node 1915301 15015143749
# huage page on two numa nodes $numastat -p 1144 Per-node process memory usage (in MBs) for PID 1144 (qemu-kvm) Node 0 Node 1 Total --------------- --------------- --------------- Huge 1752.00 6440.00 8192.00 Heap 1.04 44.79 45.82 Stack 0.00 0.04 0.04 Private 16.66 11.42 28.08 ---------------- --------------- --------------- --------------- Total 1769.70 6496.25 8265.95
# as you can see N0(node 0) 876*2M and N1(node 1) 3220*2M # numa bind policy $ cat /proc/1144/numa_maps | grep 2048 7fbd58000000 bind:0-1 file=/mnt/huge_2MB/libvirt/qemu/38-i-y4s8f9zg2o/qemu_back_mem._objects_ram-node0.dlp9WP\040(deleted) huge dirty=4096 mapmax=4 N0=876 N1=3220 kernelpagesize_kB=2048
# numa prefer policy for huge page
# prefre node 1 but huage page is allocated at node0(N0) 12G and node1(N1) 20G $ cat /proc/140662/numa_maps | grep 1G 7f5480000000 prefer:1 file=/mnt/huge_1GB/qemu_back_mem._objects_ram-node0.8Jxnog\040(deleted) huge anon=32 dirty=32 N0=12 N1=20 kernelpagesize_kB=1048576
UUID is a filesystem-level UUID, which is retrieved from the filesystem metadata inside the partition. It can only be read if the filesystem type is known and readable.
PARTUUID is a partition-table-level UUID for the partition, a standard feature for all partitions on GPT-partitioned disks. Since it is retrieved from the partition table, it is accessible without making any assumptions at all about the actual contents of the partition.
# uuid is return if this partition has a filesystem $blkid /dev/sdm1 /dev/sdm1: UUID="38db244b-e0b7-34fb-adbd-a168b6fd00fd" TYPE="xfs"
# partuuid is return if no filesytem on it $blkid /dev/sdl1 /dev/sdl1: PARTLABEL="meta" PARTUUID="87a0bfbf-2374-4be8-93c7-b5d49810ee9b"
regular pattern greedy vs lazy match
'Greedy' means match longest possible string. while 'Lazy' or non-greedy means match shortest possible string.
Greedy quantifier
Lazy quantifier
Description
*
*?
Star Quantifier: 0 or more
+
+?
Plus Quantifier: 1 or more
?
??
Optional Quantifier: 0 or 1
{n}
{n}?
Quantifier: exactly n
{n,}
{n,}?
Quantifier: n or more
{n,m}
{n,m}?
Quantifier: between n and m
1 2 3 4
# grep with lazy match # egrep does not support non-greedy matching. Using perl mode -P will help you: # -o only print the matched part!!! $grep -o -P 'https.*?mp3' example.txt | sort | uniq
The /etc/sudoers file is a critical configuration file on Unix-like operating systems, including Linux, that controls the permissions for users to execute commands with superuser (root) privileges using the sudo command. Here are the key aspects of the /etc/sudoers file:
Access Control: The primary function of the /etc/sudoers file is to define which users or groups can execute specific commands as the root user or another user. This allows for fine-grained control over administrative privileges without giving users full root access.
Defaults and Aliases: The file can also contain default settings and aliases to simplify configuration. Aliases can be defined for users, hosts, commands, and run-as specifications to group multiple entries togethe
By default sudo inherits ENV and PATH from users, but it should be reset by /etc/sudoers to prevent the use of potentially harmful variables and allow only trusted directories are used for command execution, so that user should set Defaults env_reset and Defaults env_reset at /etc/sudoers file