centos

vnc Server

  • sudo yum install tigervnc-server

  • sudo cp /lib/systemd/system/vncserver@.service /etc/systemd/system/vncserver@.service

  • sudo vim /etc/systemd/system/vncserver@.service

  • sudo systemctl daemon-reload

  • sudo systemctl enable vncserver@:1.service

  • sudo vncpasswd ~/.vnc/paawd

  • sudo firewall-cmd –state

  • sudo firewall-cmd –zone=public –add-port=5901/tcp –permanent

  • sudo firewall-cmd –zone=public –add-port=6001/tcp –permanent

  • sudo firewall-cmd –reload

  • sudo firewall-cmd –list-all

Centos 关闭selinux 和防火墙

  • vim /etc/selinux/config

  • 查看防火墙状态

    1
    firewall-cmd --state1

    停止firewall

    1
    systemctl stop firewalld.service1

    禁止firewall开机启动

    1
    systemctl disable firewalld.service

github-reinitialize

删除github上的commit历史记录

  1. 创建新的分支
    1
    2
    3
    git checkout  --orphan  new
    git add -A
    git commit -am "Re-init"
  2. 删除原master分支, 重命名master, 并提交
    git branch  -D master
    git branch -m master
    git push origin master  -f
    

现在你再去GitHub上去看提交分支的记录,会发现只有一次提交了

mongodb

MongoDB

  • 查看所有数据库

    show dbs

  • 创建或切换数据库

    use DB-Name

  • 删除当前数据库

    1
    db.dropDatabase()
  • 集合(表)

    • 创建

      1
      2
      3
      4
      5
      6
      db.createCollection(name, options)
      > use test
      switched to db test
      > db.createCollection("runoob")
      { "ok" : 1 }
      >
    • 查询

      使用 show collectionsshow tables 命令

      1
      2
      3
      > show collections
      runoob
      system.indexes
    • 在 MongoDB 中,你不需要创建集合。当你插入一些文档时,MongoDB 会自动创建集合。

      1
      2
      3
      4
      > db.mycol2.insert({"name" : "菜鸟教程"})
      > show collections
      mycol2
      ...
    • 删除集合

      1
      2
      3
      4
      5
      6
      7
      8
      > use runoob
      switched to db runoob
      > db.createCollection("runoob") # 先创建集合,类似数据库中的表
      > show tables
      runoob
      > db.runoob.drop()
      true
      > show tables

shell

移动光标

  • ctrl+b: 前移一个字符(backward)
  • ctrl+f: 后移一个字符(forward)
  • alt+b: 前移一个单词
  • alt+f: 后移一个单词
  • ctrl+a: 移到行首(a是首字母)
  • ctrl+e: 移到行尾(end)
  • ctrl+xx: 行首到当前光标替换

编辑命令

  • alt+.: 粘帖最后一次命令最后的参数(通常用于mkdir long-long-dir后, cd配合着alt+.
  • alt+d: 删除当前光标到临近右边单词开始(delete)
  • ctrl+u: 删除光标左边所有
  • ctrl+h: 删除光标前一个字符(相当于backspace)
  • ctrl+d: 删除光标后一个字符(相当于delete)
  • ctrl+w: 删除当前光标到临近左边单词结束(word)
  • ctrl+k: 删除光标右边所有
  • ctrl+l: 清屏
  • ctrl+shift+c: 复制(相当于鼠标左键拖拽)
  • ctrl+shift+v: 粘贴(相当于鼠标中键)

其它

  • ctrl+n: 下一条命令
  • ctrl+p: 上一条命令
  • alt+n: 下一条命令(例如输入ls, 然后按’alt+n’, 就会找到历史记录下的ls命令)
  • alt+p: 上一条命令(跟alt+n相似)
  • shift+PageUp: 向上翻页
  • shift+PageDown: 向下翻页
  • ctrl+r: 进入历史查找命令记录, 输入关键字。 多次按返回下一个匹配项

Vim

移动光标

  • b: 向前移动一个单词
  • w: 向后移动一个单词

删除

  • dw: 从当前光标开始删除到下一个单词头
  • de: 从当前光标开始删除到单词尾

收藏

收藏

1. markdown

2. url

3. Docker

  1. Docker自带的如下ARG参数,可以在其他指令中直接引用:

    • HTTP_PROXY
    • http_proxy
    • HTTPS_PROXY
    • https_proxy
    • FTP_PROXY
    • ftp_proxy
    • NO_PROXY
    • no_proxy
  2. vim 在插入模式粘贴代码缩进办法

    :set paste 粘贴完成是 set nopaste

  3. shell 自动补全忽略大小写

    add file ~/.inputrc

    set completion-ignore-case on

docker-compose

  1. 什么是Docker-Compose

Compose项目来源于之前的fig项目,使用python语言编写,与docker/swarm配合度很高。

Compose 是 Docker 容器进行编排的工具,定义和运行多容器的应用,可以一条命令启动多个容器,使用Docker Compose不再需要使用shell脚本来启动容器。

Compose 通过一个配置文件来管理多个Docker容器,在配置文件中,所有的容器通过services来定义,然后使用docker-compose脚本来启动,停止和重启应用,和应用中的服务以及所有依赖服务的容器,非常适合组合使用多个容器进行开发的场景。

docker-compose默认的模板文件是 docker-compose.yml,其中定义的每个服务都必须通过 image 指令指定镜像或 build 指令(需要 Dockerfile)来自动构建。

其它大部分指令都跟 docker run 中的类似。

如果使用 build 指令,在 Dockerfile 中设置的选项(例如:CMD, EXPOSE, VOLUME, ENV 等) 将会自动被获取,无需在 docker-compose.yml 中再次设置。
使用Compose 基本上分为三步:

1.Dockerfile 定义应用的运行环境
2.docker-compose.yml 定义组成应用的各服务
3.docker-compose up 启动整个应用

2.安装Compose

两种docker-compose安装方式

1.从github上下载docker-compose二进制文件安装

下载最新版的docker-compose文件

$ sudo curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s-uname -m` -o /usr/local/bin/docker-compose
添加可执行权限
$ sudo chmod +x /usr/local/bin/docker-compose
测试安装结果

$ docker-compose –version
docker-compose version 1.16.1, build 1719ceb
2.pip安装

2.1、安装python-pip

yum -y install epel-release
yum -y install python-pip
2.2、安装docker-compose
pip install docker-compose
待安装完成后,执行查询版本的命令,即可安装docker-compose

[root@swarm01 fendo]# docker-compose version
docker-compose version 1.21.2, build a133471
docker-py version: 3.3.0
CPython version: 2.7.5
OpenSSL version: OpenSSL 1.0.2k-fips 26 Jan 2017
3.docker-compose.yml 配置文件详解

docker-compose文件结构,官方提供了一个 yaml Docker Compose 配置文件的标准例子

version: “3”
services:

redis:
image: redis:alpine
ports:
- “6379”
networks:
- frontend
deploy:
replicas: 2
update_config:
parallelism: 2
delay: 10s
restart_policy:
condition: on-failure

db:
image: postgres:9.4
volumes:
- db-data:/var/lib/postgresql/data
networks:
- backend
deploy:
placement:
constraints: [node.role == manager]

vote:
image: dockersamples/examplevotingapp_vote:before
ports:
- 5000:80
networks:
- frontend
depends_on:
- redis
deploy:
replicas: 2
update_config:
parallelism: 2
restart_policy:
condition: on-failure

result:
image: dockersamples/examplevotingapp_result:before
ports:
- 5001:80
networks:
- backend
depends_on:
- db
deploy:
replicas: 1
update_config:
parallelism: 2
delay: 10s
restart_policy:
condition: on-failure

worker:
image: dockersamples/examplevotingapp_worker
networks:
- frontend
- backend
deploy:
mode: replicated
replicas: 1
labels: [APP=VOTING]
restart_policy:
condition: on-failure
delay: 10s
max_attempts: 3
window: 120s
placement:
constraints: [node.role == manager]

visualizer:
image: dockersamples/visualizer:stable
ports:
- “8080:8080”
stop_grace_period: 1m30s
volumes:
- “/var/run/docker.sock:/var/run/docker.sock”
deploy:
placement:
constraints: [node.role == manager]

networks:
frontend:
backend:

volumes:
db-data:
一份标准配置文件应该包含 version、services、networks 三大部分,其中最关键的就是 services 和 networks 两个部分

3.1、文件配置

compose 文件是一个定义服务、 网络和卷的 YAML 文件 。Compose 文件的默认路径是 ./docker-compose.yml

服务定义包含应用于为该服务启动的每个容器的配置,就像传递命令行参数一样 docker container create。同样,网络和卷的定义类似于 docker network create 和 docker volume create。

正如 docker container create 在 Dockerfile 指定选项,如 CMD、 EXPOSE、VOLUME、ENV,在默认情况下,你不需要再次指定它们docker-compose.yml。

可以使用 Bash 类 ${VARIABLE} 语法在配置值中使用环境变量。

提示: 可以是用 .yml 或 .yaml 作为文件扩展名

3.2、版本

Compose目前为止有三个版本分别为Version 1,Version 2,Version 3,Compose区分Version 1和Version 2(Compose 1.6.0+,Docker Engine 1.10.0+)。Version 2支持更多的指令。Version 1没有声明版本默认是”version 1”。Version 1将来会被弃用。

3.3、配置选项

1.bulid

服务除了可以基于指定的镜像,还可以基于一份 Dockerfile,在使用 up 启动之时执行构建任务,这个构建标签就是 build,它可以指定 Dockerfile 所在文件夹的路径。Compose 将会利用它自动构建这个镜像,然后使用这个镜像启动服务容器
build: /path/to/build/dir
也可以是相对路径

build: ./dir
设定上下文根目录,然后以该目录为准指定 Dockerfile

build:
context: ../
dockerfile: path/of/Dockerfile

  1. context

context 选项可以是 Dockerfile 的文件路径,也可以是到链接到 git 仓库的url,当提供的值是相对路径时,它被解析为相对于撰写文件的路径,此目录也是发送到 Docker 守护进程的 context

build:
context: ./dir
3. dockerfile

使用此 dockerfile 文件来构建,必须指定构建路径
build:
context: .
dockerfile: Dockerfile-alternate
4.image

services:
web:
image: nginx
在 services 标签下的第二级标签是 web,这个名字是用户自己自定义,它就是服务名称。
image 则是指定服务的镜像名称或镜像 ID。如果镜像在本地不存在,Compose 将会尝试拉取这个镜像。
例如下面这些格式都是可以的:
image: redis
image: ubuntu:14.04
image: tutum/influxdb
image: a4bc65fd

  1. args

添加构建参数,这些参数是仅在构建过程中可访问的环境变量
首先, 在Dockerfile中指定参数:
ARG fendo
ARG password

RUN echo “Build number: $fendo”
RUN script-requiring-password.sh “$password”
然后指定 build 下的参数,可以传递映射或列表

build:
context: .
args:
fendo: 1
password: fendo

build:
context: .
args:
- fendo=1
- password=fendo
指定构建参数时可以省略该值,在这种情况下,构建时的值默认构成运行环境中的值

args:

  • fendo
  • password
    6.command

使用 command 可以覆盖容器启动后默认执行的命令。

command: bundle exec thin -p 3000
该命令也可以是一个列表,方法类似于 dockerfile:

command: [“bundle”, “exec”, “thin”, “-p”, “3000”]
7.container_name

Compose 的容器名称格式是:<项目名称><服务名称><序号>

虽然可以自定义项目名称、服务名称,但是如果你想完全控制容器的命名,可以使用这个标签指定:

container_name: app
这样容器的名字就指定为 app 了。

8.depends_on

在使用 Compose 时,最大的好处就是少打启动命令,但是一般项目容器启动的顺序是有要求的,如果直接从上到下启动容器,必然会因为容器依赖问题而启动失败。

例如在没启动数据库容器的时候启动了应用容器,这时候应用容器会因为找不到数据库而退出,为了避免这种情况我们需要加入一个标签,就是 depends_on,这个标签解决了容器的依赖、启动先后的问题。

例如下面容器会先启动 redis 和 db 两个服务,最后才启动 web 服务:

version: ‘3’
services:
web:
build: .
depends_on:
- db
- redis
redis:
image: redis
db:
image: postgres
注意的是,默认情况下使用 docker-compose up web 这样的方式启动 web 服务时,也会启动 redis 和 db 两个服务,因为在配置文件中定义了依赖关系。

9.pid

pid: “host”
将PID模式设置为主机PID模式,跟主机系统共享进程命名空间。容器使用这个标签将能够访问和操纵其他容器和宿主机的名称空间。

10.ports

映射端口的标签。

使用HOST:CONTAINER格式或者只是指定容器的端口,宿主机会随机映射端口。

ports:

  • “3000”
  • “8000:8000”
  • “49100:22”
  • “127.0.0.1:8001:8001”
    注意:当使用HOST:CONTAINER格式来映射端口时,如果你使用的容器端口小于60你可能会得到错误得结果,因为YAML将会解析xx:yy这种数字格式为60进制。所以建议采用字符串格式。
    11.extra_hosts

添加主机名的标签,就是往/etc/hosts文件中添加一些记录,与Docker client的–add-host类似:

extra_hosts:

  • “somehost:162.242.195.82”
  • “otherhost:50.31.209.229”
    启动之后查看容器内部hosts:

162.242.195.82 somehost
50.31.209.229 otherhost

12.volumes

挂载一个目录或者一个已存在的数据卷容器,可以直接使用 [HOST:CONTAINER] 这样的格式,或者使用 [HOST:CONTAINER:ro] 这样的格式,后者对于容器来说,数据卷是只读的,这样可以有效保护宿主机的文件系统。
Compose的数据卷指定路径可以是相对路径,使用 . 或者 .. 来指定相对目录。

数据卷的格式可以是下面多种形式:

volumes:
// 只是指定一个路径,Docker 会自动在创建一个数据卷(这个路径是容器内部的)。

  • /var/lib/mysql

    // 使用绝对路径挂载数据卷

  • /opt/data:/var/lib/mysql

    // 以 Compose 配置文件为中心的相对路径作为数据卷挂载到容器。

  • ./cache:/tmp/cache

    // 使用用户的相对路径(~/ 表示的目录是 /home/<用户目录>/ 或者 /root/)。

  • ~/configs:/etc/configs/:ro

    // 已经存在的命名的数据卷。

  • datavolume:/var/lib/mysql
    如果你不使用宿主机的路径,你可以指定一个volume_driver。

volume_driver: mydriver
原文:https://blog.csdn.net/u011781521/article/details/80464826

runner.py

runner.py

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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pexpect
import os
try:
import urlparse
except Exception:
import urllib.parse as urlparse
import logging
import argparse
try:
import ConfigParser
except Exception:
import configparser as ConfigParser
import yaml
import sys
import time

from configobj import ConfigObj, ConfigObjError


class Logger(object):
"""
my logger tools
"""
default_formatter = logging.Formatter(
fmt='%(asctime)s %(levelname)-8s: %(name)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)

def __init__(self):
pass

@staticmethod
def add_stream_handler(stream=sys.stdout, level=logging.INFO, formatter=default_formatter):
logger = logging.getLogger("")
handler = logging.StreamHandler(stream)
handler.setFormatter(formatter)
handler.setLevel(level)
logger.addHandler(handler)

@staticmethod
def add_file_handler(logfile=None, level=logging.DEBUG, formatter=default_formatter):
if logfile is not None:
logger = logging.getLogger("")
handler = logging.FileHandler(logfile, "w")
handler.setFormatter(formatter)
handler.setLevel(level)
logger.addHandler(handler)

@staticmethod
def log_test(stream=sys.stdout, stream_level=logging.INFO, logfile=None, logfile_level=logging.DEBUG, formatter=default_formatter):
Logger.add_file_handler(logfile, logfile_level, formatter)
Logger.add_stream_handler(stream, stream_level, formatter)
logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)


Logger.log_test(logfile="test.log")
cli_servers = ["telnet", "ssh", "raw", "tio"]
log = logging.getLogger("runner")


class log_pexpect(pexpect.spawn):
def __init__(self, *args, **kwargs):
super(log_pexpect, self).__init__(*args, **kwargs)
self.log_test = False

def expect(self, *args, **kwargs):
_e = super(log_pexpect, self).expect(*args, **kwargs)
if self.log_test:
log.info(self.before)
return _e

# I did not find a way to make the telnet client not echo back our
# commands. This workaround consumes the echo and allows this pattern:
# sendline("print 42")
# expect("42") # match command output and not the command itself
# expect(prompt)
# Without this patch, expect("42") will match the echo first (print 42),
# and leave the real output untouched
def sendline(self, s='', expect_echo=True):
n = super(log_pexpect, self).sendline(s)
if expect_echo:
if s:
self.expect_exact(s)
self.expect_exact(os.linesep)
return n

def set_logfile(self, logfile):
# logfile_read contains the whole session but has the advantage over
# logfile that it is not obfuscated by duplicated lines
if logfile:
self.logfile_read = open(logfile, "w")
self.livelog = open(logfile, "r")


def validate_cli(url):
assert url.scheme in cli_servers, "bad console type \"%s\"" % url.scheme
assert url.netloc != "", "console server is missing"


def parse_cli_url(string):
"""Check that the argument is a supported console URL"""
url = urlparse.urlparse(string)
try:
validate_cli(url)
except AssertionError:
log.error("%s is not a valid console URL" % string)
raise
return url


class TelnetCLI(log_pexpect):
def __init__(self, cli_url, logfile=None, do_spawn=True):
self.cli_url = parse_cli_url(cli_url)
if not do_spawn:
self.closed = True
return
cmd = " ".join(self.cmd())
super(TelnetCLI, self).__init__(cmd)
self.set_logfile(logfile)

self.uboot_prompt = "=> "
self.linux_prompt = "[rO]\S+ *[$#] |[rO]\S+ .*\][$#] "
self.prompt = self.uboot_prompt
# Match the last line of the telnet banner
self.expect("Escape character is ")
# Wait a little to make sure the connection is really open. Far away or
# slow servers take about 1.15 seconds to reply.
index = self.expect(["Connection closed",
pexpect.EOF,
pexpect.TIMEOUT], timeout=1.3)
if index == 0 or self.eof():
log.error("connection failed")
raise pexpect.EOF(self.before + self.after)

def cmd(self):
host, port = self.cli_url.netloc.split(":")
return ["telnet", host, port]

def set_uboot_prompt(self, prompt=None):
if not prompt:
self.prompt = self.uboot_prompt
else:
self.prompt = prompt

def set_linux_prompt(self, prompt=None):
if not prompt:
self.prompt = self.linux_prompt
else:
self.prompt = prompt

def close(self):
# close() in pexpect.py has one bug, it can not close telnet properly
# in some situations, see https://bugzilla.redhat.com/show_bug.cgi?id=89653,
# so override close() here
if not self.closed:
self.sendcontrol("]")
self.expect(">", 3)
self.sendline("quit", expect_echo=False)
super(TelnetCLI, self).close()


class PromptNotFound(Exception):
"""An error from trying to convert a command line string to a type."""
pass


def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("config", nargs='+', help="configuration for the test")

args = parser.parse_args()
return args


def send_cmd(cli, cmd='', timeout=30, check_prompt=False, check_ret=False,
expect_echo=True):
""" Uboot command wrapper that allows multiple types of checks.

:param cli: command line interface object
:param cmd: command string
:param timeout: expect timeout while waiting for prompt
:param check_prompt: verify prompt after command execution
:type check_prompt: boolean
:param check_ret: verify command return code (raise error if not 0)
:type check_ret: boolean
:param expect_echo: expect the command echo before continuing, in order
to avoid timeouts when incomplete echo is displayed
:type expect_echo: boolean
:return: command output as string (when using check_prompt or check_ret)
"""
if not timeout:
timeout = 30
log.info("Sending: %s, timeout=%s, prompt=%s, ret=%s, echo=%s" % (cmd, timeout, check_prompt, check_ret, expect_echo))
cli.sendline(cmd, expect_echo=expect_echo)
cmd_output = None

# These codes are workaround for unstability of LS2 simulator.
# Comment out, or else lars needs to wait for each command 2 seconds.
"""
# check whether the cmd has been fully sent out,
# if not, will retry 3 times
re_send = 3
while re_send > 0:
re_send -= 1
if not valid_uboot_cmd(cli):
log.info("Resend cmd %s" % cmd)
cli.sendline(cmd, expect_echo=expect_echo)
else:
break
"""

if check_prompt or check_ret:
try:
cli.expect(cli.prompt, timeout)
except pexpect.TIMEOUT:
log.error("Prompt not found after \"%s\"! Command output:\n%s" %
(cmd, cli.before))
raise PromptNotFound("Prompt not found after \"%s\"!" % cmd)
cmd_output = cli.before
if check_ret:
log.debug("Return code check")
cli.sendline("echo $?") #check ret code
try:
cli.expect('^0', timeout=2)
except pexpect.TIMEOUT:
log.error("Command retcode non-zero for \"%s\"! Command output:\n%s" %
(cmd, cmd_output))
raise Exception("Command retcode non-zero for \"%s\"!" % cmd)
cli.expect(cli.prompt, timeout=2)
return cmd_output


def send_uboot_cmd(cli, cmd='', timeout=30, check_prompt=False, check_ret=False,
expect_echo=True):
""" Uboot command wrapper that allows multiple types of checks.

:param cli: command line interface object
:param cmd: command string
:param timeout: expect timeout while waiting for prompt
:param check_prompt: verify prompt after command execution
:type check_prompt: boolean
:param check_ret: verify command return code (raise error if not 0)
:type check_ret: boolean
:param expect_echo: expect the command echo before continuing, in order
to avoid timeouts when incomplete echo is displayed
:type expect_echo: boolean
:return: command output as string (when using check_prompt or check_ret)
"""
if not timeout:
timeout = 30
log.info("Sending: %s, timeout=%s, prompt=%s, ret=%s, echo=%s" % (cmd, timeout, check_prompt, check_ret, expect_echo))
cli.sendline(cmd, expect_echo=expect_echo)
cmd_output = None

if check_prompt or check_ret:
try:
n = cli.expect([cli.prompt, "Hit any key to stop autoboot:"], timeout)
if n == 1:
cli.sendline("\n")
except pexpect.TIMEOUT:
log.error("Prompt not found after \"%s\"! Command output:\n%s" %
(cmd, cli.before))
raise PromptNotFound("Prompt not found after \"%s\"!" % cmd)
cmd_output = cli.before

else:
n = cli.expect([cli.prompt, "Hit any key to stop autoboot:"], timeout=300)
if n == 1:
cli.sendline("\n")
if check_ret:
log.debug("Return code check")
cli.sendline("echo $?") #check ret code
try:
cli.expect('^0', timeout=2)
except pexpect.TIMEOUT:
log.error("Command retcode non-zero for \"%s\"! Command output:\n%s" %
(cmd, cmd_output))
raise Exception("Command retcode non-zero for \"%s\"!" % cmd)
cli.expect(cli.prompt, timeout=2)
return cmd_output


def config_shell(cli, columns=2000):
"""Configures shell with default values - removes dependency on rootfs.
Use this before first operation in linux console to ensure a fixed prompt
and a convenient raw length for long commands

:param cli: command line interface object
:param columns: longest command line should be lower than this to avoid
command echo issues
"""
log.info("Configuring shell")

try:
send_cmd(cli, "which stty", check_ret=True)
except Exception:
log.warning("NO stty! Please enable CONFIG_BUSYBOX_CONFIG_STTY!")
else:
send_cmd(cli, "stty columns 2000", check_ret=True)

send_cmd(cli, "export TERM=linux", check_ret=True)

send_cmd(cli, "export EXTRACT_UNSAFE_SYMLINKS=1", check_ret=True)
send_cmd(cli, "alias ls='ls --color=never'", check_ret=True)
send_cmd(cli, "alias grep='grep --color=never'", check_ret=True)
send_cmd(cli, "mkdir -p /media/ram", check_ret=True)
send_cmd(cli, "mount -t tmpfs tmpfs /media/ram/", check_ret=True, timeout=2)


def check_boot(cli, timeout=300):
"""Checks for successful login. Verifies the kernel bootlog and logs
warnings and errors. By default, when a fatal error is encountered
it raises an exception

:param cli: command line interface object
:param cfg: board object (or any dict containing the necessary info)
:param cont_on_error: if ``True``, continue if an error keyword is found
:param dump_kernel_cfg: if ``True``, execute zcat /proc/config.gz cmd
:param timeout: timeout of linux startup
"""
fatal_errors = [
"(?i)kernel panic",
"(?i)Internal error: Oops:",
"(?i)rebooting in * seconds",
"ramdisk - allocation error"
]
warnings = [
"(?i)failed",
"(?i)warning",
"(?i)call trace[\s\S]*end trace"
]
password = "root"
match_list = ["login:", cli.prompt, "press Control-D to continue"] + fatal_errors + warnings
cli.set_linux_prompt()
log.debug("linux_prompt as %s" % cli.prompt)

while True:
found = cli.expect(match_list, timeout=timeout)
if found == 0:
# do login
cli.sendline("root")
found = cli.expect(["Password:", cli.prompt], timeout=30)
if found == 0:
cli.sendline(password, expect_echo=False)
cli.sendline(" ")
cli.expect(cli.prompt)
cli.sendline(" ")
config_shell(cli)
break


def parse_command(cmd):
cmds = {
'cmd': '',
'timeout': None,
'check_prompt': 'False',
'check_ret': 'False',
'expect_echo': 'True'
}
if '@@' not in cmd:
cmds['cmd'] = cmd
else:
plist = cmd.split('@@')
cmds['cmd'] = plist[0]
for i in plist[1:]:
if '==' in i:
k, v = i.split('==')
if k in cmds:
cmds[k] = v
else:
log.warning('%s is ignored in command %s' % (i, cmd))
else:
log.warning('%s is ignored in command %s' % (i, cmd))
if cmds['timeout']:
cmds['timeout'] = int(cmds['timeout'])
if cmds['check_prompt'].lower() == "false":
cmds['check_prompt'] = False
else:
cmds['check_prompt'] = True

if cmds['check_ret'].lower() == "false":
cmds['check_ret'] = False
else:
cmds['check_ret'] = True

if cmds['expect_echo'].lower() == "false":
cmds['expect_echo'] = False
else:
cmds['expect_echo'] = True

return cmds


def run_uboot_script(cli, commands):
cli.set_uboot_prompt()
for cmd in commands:
commands = parse_command(cmd)
if commands["cmd"] == "boot":
cli.sendline("boot")
check_boot(cli)
else:
send_uboot_cmd(cli, **commands)


def run_linux_script(cli, commands):
cli.set_linux_prompt()
for cmd in commands:
commands = parse_command(cmd)
send_uboot_cmd(cli, **commands)


def get_cli(url):
cli = TelnetCLI(url, logfile="cli.log")
return cli

def run_config_file(yaml_file):

with open(yaml_file, 'r') as fp:
data_dic = yaml.safe_load(fp)
log.info("load yaml config successfully, [%s]." % yaml_file)

log.debug("yaml config file: %s" % yaml_file)
url = data_dic.get("url")
log.info("board connect url: %s" % url)
#run_scripts(data_dic)
try:
cli = get_cli(url)
uboot_cmds = data_dic.get("uboot_commands", None)
kernel_commands = data_dic.get("kernel_commands", None)
if uboot_cmds:
run_uboot_script(cli, uboot_cmds)
if kernel_commands:
run_linux_script(cli, kernel_commands)

finally:
if cli:
cli.close()
def main():
args = parse_args()
log.info(args)
print(args.config)
for config in args.config:
run_config_file(config)


if __name__ == "__main__":
main()

Yaml Config

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
uboot_commands:
- reboot
- pci enum
- setenv serverip 192.168.1.1
- setenv ethact FM1@DTSEC5
- dhcp
# - dhcp a0000000 xxx/lsdk2004/OOBE-lsdk2004/images/firmware_ls1046afrwy_uboot_qspiboot.img
# - sf probe 0:0; sf erase 0 +$filesize; sf update a0000000 0 $filesize @@timeout==900@@check_ret==true
- dhcp a0000000 xxxx/lsdk2004/OOBE-lsdk2004/images/firmware_ls1046afrwy_uboot_sdboot.img
- mmc write a0000000 8 1fff8 @@timeout==900@@check_ret==true
- reset

- setenv serverip 192.168.1.1
- setenv ethact FM1@DTSEC5
- dhcp a0000000 xxxx/lsdk2004/OOBE-lsdk2004/images/firmware_ls1046afrwy_uboot_sdboot.img
- mmc write a0000000 8 1fff8 @@timeout==900@@check_ret==true
- reset

# tftp kernel
- setenv serverip 192.168.1.1
- setenv ethact FM1@DTSEC5
- dhcp
- setenv othbootargs console=ttyS0,115200 earlycon=uart8250,mmio,0x21c0500 ramdisk_size=0x40000000
- setenv bootargs root=/dev/ram0 rw $othbootargs ip=dhcp
- tftpboot a0000000 xxxx/lsdk2004/OOBE-lsdk2004/images/lsdk2004_yocto_tiny_LS_arm64.itb @@timeout==900@@check_ret==true
- setenv bootcmd "bootm a0000000#ls1046afrwy"
- boot
kernel_commands:
- uname -a
- cat /proc/cmdline
- ping 192.168.1.2 -c 3
- echo "nameserver 192.168.1.1" > /etc/resolv.conf
- flex-installer -v
- flex-installer -i pf -F -d /dev/mmcblk0 @@timeout==900@@check_ret==true

url: "telnet://192.168.1.3:9999"