分类 运维快感 下的文章

使用sed命令进行替换文本

sed -ie 's/匹配的字符串/替换的字符串/g' 文件
// 比如:把test.txt 中的 petternStr 替换为 ttt
sed -ie 's/petternStr/ttt/g' test.txt

每天切割日志

创建脚本,文件名为:/data/scripts/backupWebLog.sh

#/bin/bash
NGINX_PATH=/etc/nginx/
LOG_PATH=/var/www/logs/
NGINX_PID=/run/nginx.pid
YESTERDAY=`date +%F -d -1day`
cd $LOG_PATH
for logName in `ls ./ | grep .log`
    do
        logPath=`echo $logName|awk -F'-[a-z]+.log' '{print $1}'`
        fileType=`echo $logName|awk -F$logPath'-' '{print $2}'`
        logPathR=${LOG_PATH}${logPath}
        if [ ! -d $logPathR ];then
            mkdir $logPathR
        fi
        fileName=${logPathR}/${YESTERDAY}-${fileType}
        if [ -f $fileName ];then
            rm -f $fileName
        fi
        mv $logName $fileName
    done
kill -USR1 `cat ${NGINX_PID}`

启动定时任务进行每日切割

crontab -e
0 0 *  * *  /data/scripts/backupWebLog.sh

数据库备份

创建脚本文件: /data/scripts/backupDB.sh

#/bin/bash
mysqldump -uroot -proot --all-databases > /var/backup/db/`date  +%Y%m%d-%H%M%S`.sql

赋予执行权限

chmod a+x /data/scripts/backupDB.sh

创建定时任务

crontab -e
0 */8 * * * /data/scripts/backupDB.sh

安装环境shell脚本(centos7)

#!/bin/bash
#suppor china
yum install wqy-microhei-fonts wqy-zenhei-fonts

#office to pdf
yum install unoconv -y

#pdf to slide image
yum install ImageMagick -y

使用node构造核心类officeCovert.js

const unoconv = require('awesome-unoconv');
const fs = require('fs');
const child_process = require("child_process");

class OfficeCovert{
    //file to pdf 
    file2pdf(sourceFile, generateFile){
        return unoconv.convert(sourceFile, generateFile);
    }

    //file to image list
    file2images(file, path, prefix = '', suffix ='', ext = 'png'){
        return new Promise((resolve, reject)=> {
            if(fs.existsSync(file)){
                this.rm(path);
                this.mkdir(path);
                child_process.exec(`convert ${file} ${path}/${prefix}%d${suffix}.${ext} `, (...args) =>{
                    if(args && args[0] === null){
                        resolve(path);
                    }else{
                        reject(...args);
                    }
                }, err => {
                    reject(err);
                });
            }else{
                reject('file not found');
            }
        });
    }

    //delete file or path
    rm(path){
        let files = [];
        if(fs.existsSync(path)){
            if(fs.statSync(path).isDirectory()){
                files = fs.readdirSync(path);
                files.forEach((file, index)=> {
                    let curPath = path + '/' + file;
                    if(fs.statSync(curPath).isDirectory()){
                        this.rm(curPath);
                    }else{
                        fs.unlinkSync(curPath);
                    }
                });
            }else{
                fs.unlinkSync(path);
            }
        }
    }
    //create path
    mkdir(path){
        if(!fs.existsSync(path)){
            fs.mkdir(path,{ recursive: true }, res=>  {
                if(res){
                    console.warn(res);
                }
            });    
        }
    }
}

module.exports = OfficeCovert;

入口文件index.js

const {resolve} = require('path');

const OfficeCovert = require('./officeCovert');
//定义需要转换的文件
const pptFile = resolve('./office/test2.pptx');
//生成pdf名称
const pdfFile = resolve('./output/test2.ppf');
//设置图片目录
const imgFile = resolve('./output/test2/tst');
const oc = new OfficeCovert();

//geneate pdf
oc.file2pdf(pptFile, pdfFile).then(gFile =>{
    //generate image
    oc.file2images(gFile, imgFile, 'test11', 'mytest', 'png').then(path=> {
        console.log('generate image success !!!!', path);
        //clean file 
        oc.rm(gFile);
    }).catch((...args) => {
        console.log(args);
    });
});

连接数限制

ssh_exchange_identification: read: Connection reset by peer

应急方案

应急方案1、 重启服务器(估计远程连接也连接不了的话)
应急方案2、关闭ssh连接(如果可以进行远程连接)
systemctl restart sshd

解决方案

vi /etc/ssh/sshd_config

  • 把MaxStartups值改为1000

重启SSH服务,/etc/rc.d/init.d/sshd restart

查看端口连接数

查看22端口的连接数

netstat -nat|grep -i '22' |wc -l

docker概述

按照yum-config-manager工具

yum -y install yum-utils

安装docker-ce

安装docker-ce的yum源
sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo
#关闭使用最新版本docker-ce
sudo yum-config-manager --disable docker-ce-nightly
安装docker-ce
sudo yum install docker-ce docker-ce-cli containerd.io

启动容器

sudo systemctl start docker

pm2概述

  • 内建负载均衡(使用Node cluster 集群模块)
  • 后台运行
  • 0秒停机重载(维护升级的时候不需要停机).
  • 具有Ubuntu和CentOS 的启动脚本
  • 停止不稳定的进程(避免无限循环)
  • 控制台检测
  • 提供 HTTP API
  • 远程控制和实时的接口API ( Nodejs 9.模块,允许和PM2进程管理器交互 )

pm2命令

npm install pm2 -g     # 命令行安装 pm2 
pm2 start app.js -i 4 #后台运行pm2,启动4个app.js 
                              # 也可以把'max' 参数传递给 start
                              # 正确的进程数目依赖于Cpu的核心数目
pm2 start app.js --name my-api # 命名进程
pm2 list               # 显示所有进程状态
pm2 monit              # 监视所有进程
pm2 logs               #  显示所有进程日志
pm2 stop all           # 停止所有进程
pm2 restart all        # 重启所有进程
pm2 reload all         # 0秒停机重载进程 (用于 NETWORKED 进程)
pm2 stop 0             # 停止指定的进程
pm2 restart 0          # 重启指定的进程
pm2 startup            # 产生 init 脚本 保持进程活着
pm2 web                # 运行健壮的 computer API endpoint (http://localhost:9615)
pm2 delete 0           # 杀死指定的进程
pm2 delete all         # 杀死全部进程

pm2目录卸载

rm /usr/local/bin/pm2 
rm -r /usr/local/lib/node_modules 
rm -r /root/.pm2/ 
``

### pm2 自启动

安装pm2

npm install pm2 -g

保存当前进程状态

pm2 save

生成开机自启动服务

pm2 startup

启用开机自启:

systemctl enable pm2-root


### pm2 运行npm命令
### 简单用法
1. npm run dev
2. pm2 start npm -- run dev
以上使用是等效的
  

#### 监听并重新命名运行(--watch监听代码变化,--name 重命令任务名称,-- run后面跟脚本名字)
pm2 start npm --watch --name nickname -- run dev

### 手动删除pm2日志

pm2 flush

### 自动删除pm2日志

pm2 install pm2-logrotate // 注意是pm2 install而不是npm install
pm2 set pm2-logrotate-ext:retain 7 //保存7个文件
pm2 set pm2-logrotate-ext:max_size 100M //每个备份文件大小为100M