Linux系統(tǒng)管理之技巧
【引自年年歳歲的博客】項目完成了一個階段性的任務(wù),在這里小結(jié)一下幾個小技巧:
1. 授權(quán)研發(fā)人員權(quán)限越級(sudo)
- $ cat public
- User_Alias A4 = public
- A4 ALL=(ALL) NOPASSWD: /usr/bin/vim,/bin/cat,/usr/bin/tail #這里你自己定義
- $ ansible all -m copy -a 'src=public dest=/etc/sudoers.d' -s
2. 批量memcached清除緩存(flush_all)
- echo 'flush_all' | nc -z -w 1 $IP $PORT
如果有很多,可以向下羅列,批量清除,如果你覺得很low,可以使用數(shù)組declare -a,或者循環(huán)while,
寫python當(dāng)然也行,附上自己的過程,請參考:
- $ cat clear_memcached.py
- from pymemcache.client.base import Client
- import sys
- def read_log(path):
- with open(path) as f:
- yield from f
- def HP(path):
- for line in read_log(path):
- ret = line.strip().split()
- ret[1] = int(ret[1])
- ret = tuple(ret)
- print(ret)
- yield ret
- def clear_mem(path):
- for hp in HP(path):
- c.flush_all()
- c.close()
- if __name__ == "__main__":
- clear_mem(sys.argv[1])
- $ cat mall_mem.txt
- $IP1 $PORT1
- $IP1 $PORT2
- ...
3. 遠程快速校驗多臺主機不同目錄下的文件內(nèi)容一致性(擴容時發(fā)揮作用很大)
- $ ssh -t $ip 'find $dir1 $dir2 ... -type f -exec md5sum {} \;' > $ip.md5 # 注意$dir1..等使用絕對路徑
- $ doc2unix $ip.md5 #(這個很隱秘,多了windows的回車符)
- $ ssh -tt $ip.other 'md5sum -c --quiet' < $ip.md5
- # 如果一致,什么也不反回;不一致的會告訴NOT MATCH的文件
哎,非逼自己用python去寫,實現(xiàn)了find + sha256sum,但想將其保存到特定文件中,這一點卻沒實現(xiàn)。這一版,只是想回顧“裝飾器”,這里沒起到作用。
- #!/usr/bin/env python
- import os, os.path, sys
- import hashlib
- from functools import wraps
- def search(fn):
- @wraps(fn)
- def wrap(*args, **kwargs):
- paths = list(args)
- ret = fn(*args, **kwargs)
- #paths.pop()
- for path in paths:
- print(path)
- for pathname in os.listdir(path):
- pathname = os.path.join(path, pathname)
- if os.path.isfile(pathname):
- with open(pathname, 'rb') as f:
- m = hashlib.sha256(f.read())
- # hashfile = path + '.sha256'
- # print(hashfile)
- # with open(hashfile, 'a+') as f:
- # f.write('{} {}\n'.format(m.hexdigest(), pathname))
- print('%s %s' % (m.hexdigest(), pathname))
- #ret.write('aaa')
- #ret.write('%s %s' % (m.hexdigest(), pathname))
- #ret.close()
- if os.path.isdir(pathname):
- wrap(pathname)
- return wrap
- @search
- def write(*args, **kwargs):
- pass
- #hashfile = list(args).pop()
- #print(hashfile)
- #hashfile = '10.255.201.10'
- #f = open(hashfile, 'a+')
- #return f
- if __name__ == '__main__':
- write(*sys.argv[1:])
4. 配置Open-falcon HostGroups時,根據(jù)hostname綁定template,快速獲取平臺的主機名
- $ ansible $group1 -m setup -a 'filter=ansible_hostname' -o | awk -F'[ :|"{}]' '{print $17}'
5. 關(guān)閉遠程Nginx\Tomcat進程,啟動服務(wù)就不寫了
- $ cat marketapi_stop.sh
- #!/bin/bash
- kill -QUIT $(cat /home/aspire/config/nginx/nginx.pid)
- $ ansible $group1 -m script -a 'marketapi_stop.sh' -s
- -------
- $ cat tomcat_stop.sh
- #!/bin/bash
- kill -9 $(ps aux | awk '/tomat808[0]\/conf/{print $2}')
- $ ansible $group1 -m script -a 'tomcat_stop.sh' -s
6. 遠程tail -f 查看日志滾動
- $ ssh -t $IP 'tail -f xxxx.log'