一起學Python吧~Aansible批量部署與管理(自動化運維必備)

#!/bin/env python3
#-*- coding:utf8 -*-
#學Python3的第十六天
#-----ansible-----
"""如果你鏈接遠程主機是個普通用戶,怎麼執行管理任務?
#vim ansible.cfg
[defaults]
inventory = inventory
remote_user = csdnak

[priviledge_escalation] #提權
become = yes            #需要切換用戶
become_method = sudo    #切換方式是sudo(另一種方式是su)
become_user = root      #切換成管理員
become_ask_pass = no    #不詢問切換密碼

#被管理的非要我要去,需要配置sudo
#visudo
csdnak ALL=(ALL) NOPASSWD: ALL #設置給csdnak所有sudo權限且不需要輸入密碼
"""
#***********ansible-cmdb*************
"""將ansible收集的主機信息轉換成web頁面
# 收集遠程主機的信息
(csdnak) [root@room8pc16 myansible]# ansible all -m setup --tree /tmp/csdnakout

# 安裝ansible-cmdb
(csdnak) [root@room8pc16 myansible]# pip install /var/ftp/pub/zzg_pypkgs/ansible-cmdb_pkgs/*
# 或在線安裝
(csdnak) [root@room8pc16 myansible]# pip install ansible-cmdb

# 生成web頁面(hosts文件不能有x權限)
(csdnak) [root@room8pc16 myansible]# ansible-cmdb /tmp/csdnakout > /tmp/hosts.html
(csdnak) [root@room8pc16 myansible]# firefox /tmp/hosts.html &
"""
#****************Git******************
"""
-分佈式軟件控制系統
"""
"""git配置
#安裝
[root@localhost ~]# yum -y install git
#配置基本信息
[root@localhost ~]# git config --global user.name "Mr.Wang"
[root@localhost ~]# git config --global user.email "[email protected]"
[root@localhost ~]# git config --global core.editor vim  #配置編輯器用vim
#查看剛纔配置的信息
[root@localhost ~]# git config --list
user.name=Mr.Wang
[email protected]
core.editor=vim
#or
[root@localhost ~]# cat ~/.gitconfig 
[user]
	name = Mr.Wang
	email = [email protected]
[core]
	editor = vim
"""
"""git的重要工作區域
工作區: 編寫代碼的工作目錄
暫存區: .git/index,工作區和版本庫之間的緩衝地帶
版本庫: 工作區中的.git目錄
"""
#******git應用
"""創建版本庫,方法一:編寫項目之初創建
[root@localhost ~]# git init csdnak
初始化空的 Git 版本庫於 /root/csdnak/.git/
[root@localhost ~]# ls -A csdnak/
.git
"""
"""創建版本庫,方法二:在已存在的項目中創建版本庫
[root@localhost ~]# mkdir ak
[root@localhost ~]# echo "<marquee><font color=red><h1>csdnak</h1>" > ak/test.html
[root@localhost ~]# ls ak/
test.html
[root@localhost ~]# cd ak/
[root@localhost ak]# git init
初始化空的 Git 版本庫於 /root/ak/.git/
[root@localhost ak]# ls -A
.git  test.html
"""
"""查看當前庫狀態
[root@localhost ak]# git status
# 位於分支 master
#
# 初始提交
#
# 未跟蹤的文件:
#   (使用 "git add <file>..." 以包含要提交的內容)
#
#	test.html
提交爲空,但是存在尚未跟蹤的文件(使用 "git add" 建立跟蹤)
[root@localhost ak]# git status -s
?? test.html   #??表示未知
"""
"""添加文件
[root@localhost ak]# git status -s
?? test.html
[root@localhost ak]# git add .
[root@localhost ak]# git status -s
A  test.html     #A表示已添加到暫存區
[root@localhost ak]# git status
# 位於分支 master
#
# 初始提交
#
# 要提交的變更:
#   (使用 "git rm --cached <file>..." 撤出暫存區)
#
#	新文件:    test.html
#
[root@localhost ak]# 
"""
"""從暫存區撤除test.html
[root@localhost ak]# git rm --cached test.html
rm 'test.html'
[root@localhost ak]# git status -s
?? test.html
[root@localhost ak]# git status
# 位於分支 master
#
# 初始提交
#
# 未跟蹤的文件:
#   (使用 "git add <file>..." 以包含要提交的內容)
#
#	test.html
提交爲空,但是存在尚未跟蹤的文件(使用 "git add" 建立跟蹤)
"""
"""創建.gitignore,忽略不需要加入到版本庫的文件
[root@localhost ak]# git status -s
?? passwd
?? test.html
[root@localhost ak]# ls
passwd  test.html
[root@localhost ak]# echo passwd >> .gitignore  #把不需要加入版本倉庫的文件放進.gitignore
[root@localhost ak]# echo .gitignore >> .gitignore #.gitignore自己也要放進去
[root@localhost ak]# cat .gitignore 
passwd
.gitignore
[root@localhost ak]# ls
passwd  test.html
[root@localhost ak]# git status -s
?? test.html           #不再顯示passwd的狀態
"""
"""commit提交
[root@localhost ak]# git add .
[root@localhost ak]# git commit -m test   #-m後跟註釋(必須寫)
[master(根提交) 89868df] test
 1 file changed, 1 insertion(+)
 create mode 100644 test.html
[root@localhost ak]# git status -s     #沒有未知狀態文件了
"""
"""刪除工作區文件並恢復
1)單個
[root@localhost ak]# rm -f test.html 
[root@localhost ak]# git status
# 位於分支 master
# 尚未暫存以備提交的變更:
#   (使用 "git add/rm <file>..." 更新要提交的內容)
#   (使用 "git checkout -- <file>..." 丟棄工作區的改動)
#
#	刪除:      test.html
#
修改尚未加入提交(使用 "git add" 和/或 "git commit -a")
[root@localhost ak]# git checkout test.html
[root@localhost ak]# git status
# 位於分支 master
無文件要提交,乾淨的工作區
[root@localhost ak]# ls
passwd  test.html
2)批量
[root@localhost ak]# rm -rf *
[root@localhost ak]# ls
[root@localhost ak]# git status
# 位於分支 master
# 要提交的變更:
#   (使用 "git reset HEAD <file>..." 撤出暫存區)
#
#	新文件:    1
#	新文件:    2
#	新文件:    3
#
# 尚未暫存以備提交的變更:
#   (使用 "git add/rm <file>..." 更新要提交的內容)
#   (使用 "git checkout -- <file>..." 丟棄工作區的改動)
#
#	刪除:      1
#	刪除:      2
#	刪除:      3
#	刪除:      test.html
# 
[root@localhost ak]# git checkout -- *
[root@localhost ak]# ls
1  2  3  test.html
[root@localhost ak]# 
"""
"""徹底刪除
[root@localhost ak]# git commit -m "rm -f 1 2 3"
# 位於分支 master
# 尚未暫存以備提交的變更:
#   (使用 "git add/rm <file>..." 更新要提交的內容)
#   (使用 "git checkout -- <file>..." 丟棄工作區的改動)
#
#	刪除:      1
#	刪除:      2
#	刪除:      3
#
修改尚未加入提交(使用 "git add" 和/或 "git commit -a")
[root@localhost ak]# ls
test.html
[root@localhost ak]# git checkout -- *
[root@localhost ak]# ls
test.html
"""
"""切換到某一版本的狀態
[root@localhost ak]# git log    #查看日誌
commit ccd8a8ebb79aabdf7e264a259853ed39906eb608
Author: Mr.Wang <[email protected]>
Date:   Mon Nov 18 11:51:59 2019 +0800

    rm -f 1 2 3

commit 89868df637aa420bb5e80aee0f93bbea833cf9c0
Author: Mr.Wang <[email protected]>
Date:   Mon Nov 18 11:31:46 2019 +0800

    test
[root@localhost ak]# git checkout ccd8a8ebb79aabdf7e264a259853ed39906eb608
D	1
D	2
D	3
Note: checking out 'ccd8a8ebb79aabdf7e264a259853ed39906eb608'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD 目前位於 ccd8a8e... rm -f 1 2 3
[root@localhost ak]# ls
1  2  3  test.html
"""
#*******Git TAG標記
"""
-tag可以爲某一次提交設置標記
-如果某一次提交設置爲軟件的版本號
"""
"""
查看tag
[root@localgit ak]# git tag
爲某一次提交設置tag標記
[root@localgit ak]# git tag 1.0
[root@localgit ak]# git tag
1.0
"""
"""分枝管理
#創建分支
[root@localgit ak]# git branch b1
#查看分支
[root@localgit ak]# git branch 
* (分離自 89868df)
  b1
  master

#在master分之上編寫代碼並提交
[root@localgit csdnak]# cp /etc/passwd .
[root@localgit csdnak]# git add .
[root@localgit csdnak]# git commit -m 'add passwd'
[master(根提交) a7f0724] add passwd
 1 file changed, 21 insertions(+)
 create mode 100644 passwd
[root@localgit csdnak]# ls
passwd
#切換到b1分支
[root@localgit csdnak]# ls
passwd
[root@localgit csdnak]# git checkout b1
切換到分支 'b1'
[root@localgit csdnak]# ls
#切換到master
[root@localgit csdnak]# git checkout master
切換到分支 'master'
#合併分支,將b1匯入主幹
[root@localgit csdnak]# git branch
  b1
* master
[root@localgit csdnak]# git merge b1   #在跳出的vim中寫入日誌
Already up-to-date.
[root@localgit csdnak]# ls
1  2  3  passwd  shadow  test.html
#分支不需要時可以刪除
[root@localgit ak]# git help  branch  #查看幫助
[root@localgit ak]# git branch 
  b1
* master
[root@localgit ak]# git branch -d b1
已刪除分支 b1(曾爲 89868df)。
[root@localgit ak]# git branch 
* master
"""
#*********gitlab服務器***********
"""配置環境
-安裝docker並啓動
#虛擬機必須3.5G~4G
[root@gitserver ~]# yum -y install docker
[root@gitserver ~]# systemctl restart docker
[root@gitserver ~]# systemctl enable docker
-將鏡像導入
[root@gitserver ~]# ls
gitlab_zh.tar
[root@gitserver ~]# docker load -i gitlab_zh.tar 
a94e0d5a7c40: Loading layer 116.5 MB/116.5 MB
88888b9b1b5b: Loading layer 15.87 kB/15.87 kB
52f389ea437e: Loading layer 14.85 kB/14.85 kB
52a7ea2bb533: Loading layer 5.632 kB/5.632 kB
db584c622b50: Loading layer 3.072 kB/3.072 kB
62786ff6a243: Loading layer 75.85 MB/75.85 MB
71bc04f4b7c7: Loading layer 2.048 kB/2.048 kB
26e083d332d8: Loading layer 2.048 kB/2.048 kB
2c02e58e96b8: Loading layer 2.048 kB/2.048 kB
589c7a23de2a: Loading layer 15.87 kB/15.87 kB
44474d2cdcd1: Loading layer 1.359 GB/1.359 GB
41c94e16b901: Loading layer 16.78 MB/16.78 MB
04cafa6a1534: Loading layer   160 MB/160 MB
Loaded image: gitlab_zh:latest
[root@gitserver ~]# docker images 
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
gitlab_zh           latest              1f71f185271a        20 months ago       1.627 GB
# 將docker宿主機ssh端口號改爲2022
[root@gitserver ~]# vim /etc/ssh/sshd_config 
Port 2022
[root@gitserver ~]# systemctl restart sshd
# 再次連接時,需要指定端口號
[root@room8pc16 ~]# ssh -p2022 gitserver
# 啓動容器
[root@gitserver ~]# docker run -d -h gitlab --name gitlab -p 443:443 -p 80:80 -p 22:22 --restart always -v /srv/gitlab/config:/etc/gitlab -v /srv/gitlab/logs:/var/log/gitlab -v /srv/gitlab/data:/var/opt/gitlab gitlab_zh:latest 
[root@gitserver ~]# docker ps   #STATUS必須出現healthy(啓動時間有點長)
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                   PORTS                                                          NAMES
099a45dc7052        gitlab_zh:latest    "/assets/wrapper"   4 minutes ago       Up 4 minutes (healthy)   0.0.0.0:22->22/tcp, 0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   gitlab
[root@room9pc01 ~]# firefox http://192.168.1.30 #起來以後即可訪問虛擬機ip
"""
#*******gitlab應用*****
"""
1.登錄服務器http://192.168.1.30,設置root密碼
2.gitlab重要的概念
    1.羣組group:對應一個開發團隊
    2.用戶,成員member:對應用戶賬戶,可以將用戶加入到組或項目
    3.項目:對應軟件項目
-創建名爲devops的組,類型爲公開
-創建一個用戶賬號,新建用戶時,不能設置密碼.創建完成後,可以在編輯,以設置密碼.
-創建項目:爲devops組創建項目,項目名爲myweb,類型爲公開。
 	爲項目授權:點擊項目左邊欄的設置。將前一步創建的普通用戶加入項目,成爲主程序員。

#切換爲普通用戶,上傳代碼

- 新用戶首次登陸時,需要改密碼
- 點擊項目,因爲項目是空的,它將提示你如何操作
  - 創建新版本庫:適用於你本地沒有任何文件
  - 已存在的文件夾:適用於你已經創建了基目目錄,但是沒有執行過git init實現初始化
  - 已存在的 Git 版本庫:適用於你已經使用git管理的項目目錄
"""
"""
[root@node4 ~]# cd myweb/
# 創建倉庫,該倉庫與一個gitlab項目的url關聯
[root@node4 myweb]# git remote add origin http://192.168.4.5/devops/myweb.git
# 推送本地代碼到gitlab
[root@node4 myweb]# git push -u origin --all
Username for 'http://192.168.4.5': zzg
Password for 'http://[email protected]': 
# 推送tag到gitlab
[root@node4 myweb]# git push -u origin --tags
Username for 'http://192.168.4.5': zzg
Password for 'http://[email protected]': 

# 如果在add時,有輸入錯誤,可以把它刪掉
[root@node4 myweb]# git remote remove origin
"""
"""通過ssh免密上傳代碼
1. 點擊頁面右上角用戶->設置
2. 把你的公鑰複製到“SSH密鑰” (左邊欄->ssh密鑰)
"""
"""
[root@node4 myweb]# ssh-keygen -t rsa -C "[email protected]" -b 4096
[root@node4 myweb]# cat ~/.ssh/id_rsa.pub 
"""
"""通過ssh上傳代碼
# 將http的方式刪除
[root@node4 myweb]# git remote remove origin
# 更新上傳方式爲ssh
[root@node4 myweb]# git remote add origin [email protected]:devops/myweb.git
# 上傳代碼
[root@node4 myweb]# echo 'how are you?' > aaa.html
[root@node4 myweb]# git add .
[root@node4 myweb]# git commit -m 'create aaa.html'
[root@node4 myweb]# git push

# 通過http下載
[root@node4 myweb]# cd /tmp/
[root@node4 tmp]# git clone http://192.168.4.5/devops/myweb.git
[root@node4 tmp]# ls -A myweb/
aaa.html  .git  hi.txt  passwd

# 同步代碼
[root@node4 tmp]# cd myweb/
[root@node4 myweb]# git pull
Already up-to-date.
"""

#****************複習*******************
# #*********time-module*******
# import time
#
# t = time.localtime() #返回當前時間的九元組
# time.gmtime() #返回格林威治0時區 當前時間的九元組
# time.time() #常用, 與1970-1-1 8:00之間的秒數,時間戳
# time.mktime(t) #吧九元組時間轉成時間戳
# time.sleep(1)  #睡1秒
# time.asctime() #如果有參數,是九元組形式
# time.ctime() #返回當前時間,參數是時間戳,常用
# time.strftime('%Y-%m-%d')  #常用
# time.strptime('2018-07-20', '%Y-%m-%d') #返回九元組時間格式
# time.strftime('%H:%M:%S')
################################
# from datetime import datetime
# from datetime import timedelta
# datetime.today() #返回當前時間的datetime對象
# datetime.now() #同上,可以用時區作爲參數
# datetime.strptime("2018/06/30", '%Y/%m/%d') #返回datetime對象
# dt = datetime.today()
# datetime.ctime(dt)
# datetime.strftime(dt, "%Y%m%d")
#
# days = timedelta(days=90,hours=3)  #常用
# dt2 = dt + days
# print(dt2.year)
# print(dt2.month)
# print(dt2.day)
# print(dt2.hour)

#*********os模塊常用方法
# import os
#
# os.getcwd() #pwd (顯示當前路徑)
# os.listdir() #ls -a
# os.listdir('/tmp')  #ls -a /tmp
# os.mkdir('/tmp/mydemo') #mkdir /tmp/demo
# os.chdir('/tmp/mydemo') #cd /tmp/demo
# os.listdir()
# os.mknod('test.txt')  #touch test.txt
# os.symlink('/etc/hosts', 'zhuji') #ln -s /etc/hosts zhuji
# os.path.isfile('test.txt') #判斷test.txt 是不是文件
# os.path.islink('zhuji') #判斷zhuji是不是軟連接
# os.path.isdir('/etc') #判斷/etc是不是目錄
# os.path.exists('/tmp') #判斷/tmp是否存在
# os.path.basename('/tmp/abc/aaa.txt') #判斷是不是系統變量名
# os.path.dirname('/tmp/abc/aaa.txt')  #判斷目錄名是否存在
# os.path.split('/tmp/abc/aaa.txt') #分離
# os.path.join('tmp/abc/', 'aaa.txt') #合併
# os.path.abspath('test.txt') #返回當前目錄test.txt的絕對路徑(/tmp/mydemo/test.txt)

#**************funcation-group***********
# """
# -定義參數時,參數名前面加上*表示使用元組接收參數
# -定義參數時,參數名前加上**表示使用字典接收參數
# """
# def fun1(*args):
#     print(args)
#
# func1() #()
# func1('hao') #(hao,)
# func1('hao', 123) #('hao', 123)
# func1('hao', 123, 'bob', 'alice')
#
# def func2(**kwargs):
#     print(kwargs)
#
# func2() #{}
# func2(name='bob') #{'name': 'bob'}
# func2(name='bob', age=20) #{'name': 'bob', 'age': 20}
# """
# -傳參時,*表示吧序列對象拆開
# -傳參試,**表示把字典對象拆開
# """
# def fun3(x,y):
#     return x + y
# nums = [10,20]
# func3(*nums) #func3(10,20)  #30
# def func4(name,age):
#     print('%s is %s  years.old.' % (name,age))
#
# adict = {'name':'alice','age': 18}
# func4(**adict)  #func4(name='alice',age=18) -> alice is 18 years old.
#
# #*****匿名函數(忘了單詞只能寫漢字了)************
# def add(x,y):
#     return x + y
# #可以改寫爲
# myadd = lambda x, y:x + y
# add(10, 5)  #15
# myadd(10, 5) #15
# ********(filter and map )funcation******
"""filter-funcation
-它接受兩個參數.filter(func,seq)
-第一個參數是函數,如func
-第二個參數是序列對象
func它必須接受一個參數,返回值必須是True或False
filter函數工作時,將序列對象中的每一個值作爲func的參數進行過濾,結果爲真的保留,爲假的捨棄.
"""
"""map-funcation
-它接受兩個參數.map(func,seq)
-第一個參數是函數,如func
func他必須是一個參數,它將接收到的數據進行處理,然後返回
"""
"""variable
-在函數外面定義的變量是global(全局變量).全局變量從定義開始,到程序結束,任意地方可見可用.
"""
# x = 10
#
#
# def func1():
#     print(x)
#
#
# func1()  # 10
#
#
# # 在函數內定義的變量是局部變量,局部變量只能在函數內部使用.
# def func2():
#     a = 100
#     print(a)
#
#
# func2()  # 100
# print(a)
# """報以下錯誤
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# NameError: name 'a' is not defined
# """
# # 如果局部和全局有同名變量.局部變量將會遮蓋住全局變量.
# x = 10
#
#
# def func3():
#     x = 'hello world'
#     print(x)
#
#
# func3()  # hello world!
# print(x)  # 10 (全局變量x沒有受到影響)
#
#
# # 如果希望通過函數改變全局變量,需要使用關鍵字global
# def func4():
#     global x
#     x = 10000
#     print(x)
#
#
# func4()  # 10000
# print(
#     x  # 10000
# )


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章