0%

mysql数据库运维

导出

1
mysqldump -uroot -proot --databases supersign >/tmp/supersign.sql

导入

1
2
3
4
5
mysql -uusername -ppassword db1 < tb1tb2.sql

mysql>
user db1;
source tb1tb2.sql;

mongodb 学习

相关用户名密码

1
2
3
4
192.168.1.2 admin/xmwefun
localhost test1/test1

mongodb://test1:test1@localhost:27017/admin

docker 中 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
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
# 进入mongo的shell交互平台
mongo
# 查看当前的数据库
db
# 查看所有数据库--好像没效果--存在数据时才会展示
show dbs
# 插入数据
db.runoob.insert({'name': 'helloworld'})
# 使用test数据库-不存在时会直接创建数据库
use test
# 用户登录
db.auth('test1', 'test1')

# 创建集合创建表
db.createCollection('user')
# 展示所有表
show tables
show collections
# 删除表
db.user.drop()

# 插入数据
db.COLLECTION_NAME.insert
db.COLLECTION_NAME.save
# 查看数据
db.fmzh.find()
db.repo.find()

# 更新数据
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)

db.fmzh.update({'test': 'test insert is first db'}, {$set:{'test': 'mongodb'}})

# 删除数据
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>
}
)
db.fmzh.remove({'test': 'mongodb'})

# 导入数据
mongoimport --authenticationDatabase admin --username foursquare --password foursquare --db foursquare --collection foursquare_tips --file foursquare_tips.json --jsonArray

mongoimport --authenticationDatabase admin --username foursquare --password foursquare --db foursquare --collection foursquare_user --file foursquare_user.json --jsonArray

spring 中 mongoTemplate 的使用

  1. 工具类
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
## 使用MongoRepository
import org.jeecg.modules.foursquare.entity.FoursquareUser;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface IFoursquareUserDao extends MongoRepository<FoursquareUser, String> {
}


## 使用mongoTemplate
import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class BaseDao<T> {

@Resource
private MongoTemplate mongoTemplate;

/**
* 获取泛型Class
*/
private Class<T> clazz = (java.lang.Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

/**
* 获取base template
*
* @return
*/
public MongoTemplate getMongoTemplate() {
return mongoTemplate;
}

/**
* 分页查找数据
*
* @param query
* @param pageable
* @return
*/
public Page<T> find(Query query, Pageable pageable) {
long size = mongoTemplate.count(query, clazz);

query.skip(pageable.getOffset());
query.limit(pageable.getPageSize());

List<T> listTips = find(query);

return new PageImpl<T>(listTips, pageable, size);
}

/**
* 根据条件查询记录
*
* @param query
* @return
*/
public List<T> find(Query query) {
return mongoTemplate.find(query, clazz);
}

/**
* 查询集合全部记录
*
* @return
*/
public List<T> findAll() {
return mongoTemplate.findAll(clazz);
}

/**
* 根据ID获取记录
*
* @param id
* @return
*/
public T findById(String id) {
return mongoTemplate.findById(id, clazz);
}

/**
* 根据条件查询一条记录
*
* @param query
* @return 即便多条记录也只会返回第一条
*/
public T findOne(Query query) {
return mongoTemplate.findOne(query, clazz);
}

/**
* 新增记录
*
* @param t
* @return
*/
public T insert(T t) {
return mongoTemplate.insert(t);
}

/**
* 批量新增记录
*
* @param list
* @return
*/
public Collection<T> insertAll(Collection<? extends T> list) {
return mongoTemplate.insertAll(list);
}

/**
* 根据ID更新记录,对象属性全部更新
*
* @return
*/
public UpdateResult updateById(T t) {
Query query = new Query(Criteria.where("id").is(getIdByObject(t)));
Update update = getUpdateByObjectAllField(t);
return mongoTemplate.updateMulti(query, update, clazz);
}

/**
* 根据ID更新记录,仅更新不为null属性的对象
*
* @return
*/
public UpdateResult updateByIdSelective(T t) {
Query query = new Query(Criteria.where("id").is(getIdByObject(t)));
Update update = getUpdateByObjectNotNullField(t);
return mongoTemplate.updateMulti(query, update, clazz);
}

/**
* 根据条件批量更新记录
*
* @return
*/
public UpdateResult update(Query query, Update update) {
return mongoTemplate.updateMulti(query, update, clazz);
}

/**
* 根据条件删除记录
*
* @param query
* @return
*/
public DeleteResult delete(Query query) {
return mongoTemplate.remove(query, clazz);
}

/**
* 根据ID删除记录
*
* @param id
* @return
*/
public DeleteResult deleteById(String id) {
Query query = new Query(Criteria.where("id").is(id));
return mongoTemplate.remove(query, clazz);
}

/**
* 查询一条记录并删除这条记录
*
* @param query
* @return
*/
public T deleteOneAndReturn(Query query) {
return mongoTemplate.findAndRemove(query, clazz);
}

/**
* 根据条件查询全部记录并删除
*
* @param query
* @return
*/
public List<T> deleteAllAndReturn(Query query) {
return mongoTemplate.findAllAndRemove(query, clazz);
}

/**
* 根据ID,若数据库存在则更新数据,若数据库不存在则新增数据
*
* @param t
* @return
*/
public UpdateResult upsertById(T t) {
Query query = new Query(Criteria.where("id").is(getIdByObject(t)));
Update update = getUpdateByObjectAllField(t);
return mongoTemplate.upsert(query, update, clazz);
}

/**
* 从对象中获取ID属性值
*
* @return
*/
private Object getIdByObject(T t) {
try {
return t.getClass().getDeclaredField("id");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(clazz.getName() + "类不存在id属性");
}
}

/**
* 将对象的所有属性设置进update
*
* @param t
* @return
*/
private Update getUpdateByObjectAllField(T t) {
Document document = Document.parse(JSON.toJSONString(t));
Update update = new Update();
for (Map.Entry<String, Object> entry : document.entrySet()) {
update.set(entry.getKey(), entry.getValue());
}
return update;
}

/**
* 将对象内不为null的属性设置进update
*
* @param t
* @return
*/
private Update getUpdateByObjectNotNullField(T t) {
Document document = Document.parse(JSON.toJSONString(t));
Update update = new Update();
for (Map.Entry<String, Object> entry : document.entrySet()) {
if (entry.getValue() != null) {
update.set(entry.getKey(), entry.getValue());
}
}
return update;
}
}
  1. 持久化类使用 Document、 Field 注解
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
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.bson.types.ObjectId;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.util.Date;

@Data
@Document("foursquare_tips")
@TableName("foursquare_tips")
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "foursquare_tips对象", description = "foursquare_tips")
public class MongoFoursquareTips implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@TableField(exist = false)
private ObjectId objectId;

/**
* id
*/
@TableId(type = IdType.AUTO)
@ApiModelProperty(value = "id")
private Integer id;
/**
* 场景ID
*/
@Excel(name = "场景ID", width = 15)
@ApiModelProperty(value = "场景ID")
private String venueId;
/**
* 用户id
*/
@Excel(name = "用户id", width = 15)
@ApiModelProperty(value = "用户id")
@Field(value = "user_id")
private Integer userId;
/**
* 评论ID
*/
@Excel(name = "评论ID", width = 15)
@ApiModelProperty(value = "评论ID")
@Field(value = "tips_id")
private String tipsId;
/**
* 评论内容
*/
@Excel(name = "评论内容", width = 15)
@ApiModelProperty(value = "评论内容")
@Field(value = "tips_text")
private String tipsText;
/**
* 评论时间
*/
@Excel(name = "评论时间", width = 15, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "评论时间")
@Field(value = "createdAt")
private String createdat;
}

高阶用法

  1. 关系引用
  2. map reduce
  3. 查询分析\索引
  4. 读写分离

问题

  1. command insert requires authentication
    ,,创建对应数据库的权限用户,,切换数据库,即可
1
2
3
4
5
6
7
8
9
10
11
12
# 切换admin数据库
use admin
# 管理员用户登录
db.auth('test1', 'test1')
# 创建对应数据库的权限用户
db.createUser({user: 'fmzh', pwd: 'fmzh', roles: [{role: 'readWrite', db: 'fmzh'}]})
# 重新用新用户登录
db.auth('fmzh', 'fmzh')
# 切换数据库
use fmzh
# 验证
db.repo.insert({'name': 'hello world'})
  1. auth error: sasl conversation error: unable to authenticate using mechanism “SCRAM-SHA-1”
1
2
3
# 导入脚本添加参数

--authenticationDatabase admin
  1. Failed: cannot decode array into a D
1
2
3
# 添加参数

--jsonArray
  1. Exception authenticating MongoCredential and Uncategorized Mongo Db Exception
1
2
3
spring.data.mongodb.authentication-database=admin

spring.data.mongodb.uri=mongodb://user:passwod@localhost/test?authSource=admin
  1. converter found capable of converting from type [org.bson.types.ObjectId] to type [long]
1
2
3
4
5
6
7
8
9
10
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.format.annotation.DateTimeFormat;

@Document("foursquare_user")
public class FoursquareUser {

@Id
private ObjectId objectId;

6.

参考

  1. 菜鸟教程
  2. command insert requires authentication
  3. mongo 之 java 驱动
  4. mongo 之查询对照
  5. mongo 之 java 示例
  6. sasl c onversation error: unable to authenticate using mechanism…
  7. Failed: cannot decode array into a D
  8. Exception authenticating MongoCredential and Uncategorized Mongo Db Exception
  9. How the ‘_id’ field is handled in the mapping layer

zsign 安装

安装相关工具

  1. openssl-devel
1
yum install openssl-devel
  1. git
1
yum install git
  1. 下载 zsign
1
git clone https://github.com/zhlynn/zsign.git
  1. 编译
1
2
3
cd zsign

g++ -std=c++11 *.cpp common/*.cpp -lcrypto -O3 -o zsign
  1. 验证
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@c250756e5cc0 /]# zsign
Usage: zsign [-options] [-k privkey.pem] [-m dev.prov] [-o output.ipa] file|folder
options:
-k, --pkey Path to private key or p12 file. (PEM or DER format)
-m, --prov Path to mobile provisioning profile.
-c, --cert Path to certificate file. (PEM or DER format)
-d, --debug Generate debug output files. (.zsign_debug folder)
-f, --force Force sign without cache when signing folder.
-o, --output Path to output ipa file.
-p, --password Password for private key or p12 file.
-b, --bundleid New bundle id to change.
-n, --bundlename New bundle name to change.
-r, --bundleversion New bundle version to change.
-e, --entitlements New entitlements to change.
-z, --ziplevel Compressed level when output the ipa file. (0-9)
-l, --dylib Path to inject dylib file.
-w, --weak Inject dylib as LC_LOAD_WEAK_DYLIB.
-i, --install Install ipa file using ideviceinstaller command for test.
-q, --quiet Quiet operation.
-v, --version Show version.
-h, --help Show help.

其他

  1. docker 中设置环境变量重新进入未生效
1
2
3
4
vi ~/.bashrc

alias zsign=/home/fmzh/soft/zsign

参考

  1. 官网
  2. xmake
  3. g++ error:This file requires compiler and library support for the ISO C++ 2011 standard
  4. Docker 之/etc/profile 不生效得问题

fastlane 安装

ruby 安装

  1. 默认安装
    yum install ruby

  2. 检查版本
    ruby --version
    默认为 2.0.0 版本,fastlane 安装要求 ruby 在 2.5 以上

  3. ruby 版本更新-rvm 安装

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
# 添加阿里镜像
gem sources -a http://mirrors.aliyun.com/rubygems/

gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB

# 该步骤执行失败,需翻墙
#curl -sSL https://get.rvm.io | bash -s stable
curl http://static.foxhello.com/app/shell/rvm-installer.txt >> rvm-installer.sh

# docker安装which
yum install which

# 安装rvm
./rvm-installer.sh

# 更新环境变量
source /etc/profile.d/rvm.sh

# 检测
rvm -v

rvm list known

rvm install 2.7

ruby -v
  1. 安装 bundler
    gem install bundler

  2. 相关命令

1
2
3
4
5
6
7
8
9
10
# Create a ./Gemfile in the root directory of your project with the content
source "https://rubygems.org"

gem "fastlane"
# Run `bundle update` and add both the `./Gemfile` and the `./Gemfile.lock` to version control
# Every time you run fastlane, use `bundle exec fastlane` [lane]
# On your CI, add `bundle install` as your first build step
# To update fastlane, just run `bundle update` fastlane

fastlane init

参考

  1. fastlane github
  2. fastlane 官网
  3. fastlane 安装文档
  4. ruby 安装文档
  5. ruby 升级

挖矿病毒查杀

查看表现

  1. top 单个进程 cpu 程序占用 300% 以上
  2. 查看内存占用: free -h
  3. ssh 服务器不能登录
  4. 应用程序不能启动等
  5. 查看 cpu 占用最高
1
2
3
4
5
6
7
8
9
# linux 下 取进程占用 cpu 最高的前10个进程
ps aux|head -1;ps aux|grep -v PID|sort -rn -k +3|head


# linux 下 取进程占用内存(MEM)最高的前10个进程
ps aux|head -1;ps aux|grep -v PID|sort -rn -k +4|head

# linux 下 取进程僵死进程 (删除ppid)
ps -A -ostat,ppid,pid,cmd | grep -e '^[Zz]'

查看路径

  1. 查看进程详细信息:ps -ef|grep xx (xx 为进程号)
    查看父子进程号:ps ajx
  2. ll /proc/xx/ 或者 ll /proc/xx/exe 其中 xx 为进程号
  3. 查看系统定时任务: crontab -l
  4. cat ~/.ssh/authrized_keys

处理病毒

  1. 删除父子进程
  2. 删除子进行(病毒路径)的文件
    /tmp/xxxxx/config.json /tmp/xxxxx/*
  3. 删除系统定时器的内容
    crontab -e || dd || wq
  4. 删除未信任的 ssh 主机
  5. 修改不使用用户名密码登录,使用 pem 密钥文件登录, 见环境配置-注意点-第 5 条

参考

  1. 阿里云文档
  2. linux 相关命令
  3. MaCloud 博客-病毒查杀
1
2
3
4
5
6
7
8
9
10
11
步骤简化:

1.pkill java 杀掉挖矿程序的进程

2.rm -rf java 删除挖矿程序

3.crontab -r 删除定时任务

4.检查用户列表,开机启动,.ssh文件

5.去阿里云控制台设置安全组关闭不安全端口

应用中时区异常

操作系统时区

ubuntu

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#查看当前系统时间
date -R

#时区设置
tzselect
4 Asia
9 China
1 Beijing Time
1 Yes

#复制文件
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

#检查 CST(北京) UTC(格林尼治标准时间)
date -R

数据库时区

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 -uroot -p123456

#查看时区 system_time_zone CST; time_zone CST
show variables like '%time_zone%';

select now();
select curtime();
#返回08:00表示为北京时间
select timediff(now(),convert_tz(now(),@@session.time_zone,'+00:00'));
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);

select now();
show variables like '%time_zone%';
set global time_zone = '+8:00';
# 立即生效,其实没效果;只要重连就可以
flush privileges;

vi /etc/mysql/my.cnf
#mysqld下添加
default-time_zone = '+8:00'

#重启
service mysql restart

java 应用层面

  1. 在 jdbc 的 url 加上参数
1
2
3
4
5
serverTimezone=GMT%2B8
serverTimezone=Asia/Shanghai

&serverTimezone=UTC
&serverTimezone=Asia/Hongkong
  1. jvm 环境指定时区
1
2
-Duser.timezone=Asia/Shanghai
export TZ=Asia/Shanghai
  1. 通过代码指定
1
2
final TimeZone timeZone = TimeZone.getTimeZone("GTM+8");
TimeZone.setDefault(timeZone);

权限认证

oauth2 应用的步骤

  1. 配置资源服务器 EnableResourceServer
  2. 配置认证服务器 EnableAuthorizationServer
  3. 配置 Spring security EnableWebSercurity

oauth2 据场景分4种模式

  1. 授权码模式 (authorization code) 使用场景: 网站授权
  2. 简化模式 (implicit)
  3. 密码模式 (resource owner password credentials) 使用场景:有用户、权限体系
  4. 客户端模式 (client credentials) 使用场景:仅是接口、不考虑用户

Spring security中具体内容UserDetailsService \ AuthenticationManager \ authenticationProvider 关系

EnableResourceServer具体内容

TokenGranter

  1. CompositeTokenGranter
  2. AbstractokenGranter
  • ResourceOwnerPasswordTokenGranter
  • AuthorizationCodeTokenGranter
  • ImplicitTokenGranter
  • ClientCredentialsTokenGranter
  • RefreshTokenGranter refresh_token 刷新token专用

AuthorizationServerTokenServices创建、刷新、获取token
tokenStore中包含redis、jwt、db实现

问题

  1. 登陆 接口
    TokenEndpoint类 /oauth/token 见postman中【鉴权-demo】
  2. 刷新token
    1⃣️ 什么时候用?
    access_token过期
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    if (error.response) {
    if (error.response.status === 401) {

    // 如果当前路由不是login,并且用户有 “记住密码” 的操作
    // 那么去请求新 token
    if (router.currentRoute.name !== 'login') {
    if (getRemember() && getRefreshToken()) {

    return doRequest(error)
    } else {

    Message.error('登陆过期请重新登陆!')
    setToken('')
    router.push({
    name: 'login'
    })
    }
    }
    }
    }
    2⃣️ 异常码处理方式?怎么实现前端拦截后得到401码
    HttpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  3. 退出
  4. 鉴权中clientId的作用
    授权时作为第三方进行使用(微信授权登陆时,需要先在微信端申请为可信应用)
  5. BasicAuthenticationFilter默认登录HttpSecurity.httpBasic()
  6. AbstractTokenGranter查看校验validateGrantType与clientDetails.getAuthorizedGrantTypes校验
    TokenGranter.grant(grantType, tokenRequest);

参考

鉴权专题
鉴权demo
refresh token的使用-参考1
refresh token的使用-参考2
refresh token的使用-参考3
设置返回码为401

断点调试

pdb 调试

python -y pdb test_pdb.py

命令 解释
break或 b 设置断点
例如
‘b 12’表示在第12行下端点
‘b a.py:12’表示在a.py这个文件的第12行下断点
continue 或 c 继续执行程序,运行到下一个断点
list 或 l 查看当前行的代码段 ,显示断点周围的源代码
step 或 s 进入函数,步进,一步步的执行
return 或 r 执行代码直到从当前函数返回
exit 或 q 中止并退出
next 或 n 执行下一行
pp 打印变量的值
help 帮助

参考

Jupyter notebook 断点调试快捷键