|
将文件在 PATH 下保存成 slackfiles.py 并 chmod +x 就好~ 其实这个 python 脚本功能很单一,关键是要和 shell 脚本联动~
这里给几个常用的用法:
# 在 "/var/tmp/slackfile/db.pkl" 建立数据库
tail -n+19 /var/log/packages/* | slackfiles.py --creat-db
# 在 ~/db 建立数据库
tail -n+19 /var/log/packages/* | slackfiles.py --creat-db ~/db
# 根据数据库 "/var/tmp/slackfile/db.pkl" 在 /usr/lib64 下面找没有被包管理的文件
cd /
find usr/lib64 -type f | slackfiles.py
# 根据数据库 ~/db 在 /usr/lib64 下面找没有被包管理的文件
cd /
find usr/lib64 -type f | slackfiles.py --use-db ~/db
# 以上方法都没有考虑链接
欢迎提意见,拍砖~;)
源码:
- #!/usr/bin/env python
- import sys, cPickle
- import os
- def_db = "/var/tmp/slackfile/db.pkl"
- def print_help(outfile=sys.stdout):
- outfile.write(
- '''slackfiles.py [--use-db <db-name> | [--creat-db | --add-db] [db-name]]
- If no arguments, it eqauls to "slackfile.py --use-db /var/tmp/slackfile/db.pkl"
- Default database name is "/var/tmp/slackfile/db.pkl"
- ''')
- def check_dir(name):
- if not os.path.isdir(name):
- try:
- os.makedirs(name)
- except:
- sys.stderr.write('Could not make dir: ' + name + '\n')
- def load_set(name):
- try:
- return cPickle.load(open(name, 'rb'))
- except IOError:
- sys.stderr.write(name + 'does not exist or \
- you don\'t have a read permission.\n\
- Please creat the datebase first\n')
- sys.exit(1)
- def build_set(se, infile):
- for i in infile:
- se.add(i)
- def build_db(filename, instream=sys.stdin, add=False):
- check_dir(os.path.split(filename)[0])
- if add == False:
- se = set()
- else:
- se = load_set(filename)
- build_set(se, instream)
- try:
- dbfile = open(filename, 'wb')
- except IOError:
- sys.stderr.write('Could not write to ' + filename + '\n')
- sys.exit(1)
- cPickle.dump(se, dbfile, -1)
- dbfile.close()
- def search_set(se, infile):
- for i in infile:
- if i not in se:
- print i[:-1] # strip one trailing \n manually.
- def search_db(filename, instream=sys.stdin):
- se = load_set(filename)
- search_set(se, instream)
- def main(args):
- i = 1 # skip the first arg(program name)
- while i < len(args):
- if args[i] == '--use-db':
- if i + 1 > len(args):
- print_help()
- sys.stderr.write('\nPlease specify the database name.\n')
- sys.exit(2)
- search_db(args[i + 1])
- sys.exit(0)
- elif args[i] == '--creat-db':
- if i + 1 < len(args):
- name = args[i + 1]
- else:
- name = def_db
- build_db(name)
- sys.exit(0)
- elif args[i] == '--add-db':
- if i + 1 < len(args):
- name = args[i + 1]
- else:
- name = def_db
- build_db(name, add=True)
- sys.exit(0)
- i += 1
- search_db(def_db)
- if __name__ == '__main__':
- main(sys.argv)
复制代码
不过需要注意的是根据创建数据库的方法不同,有的已经被包管理的文件可能会被误认为是没有被包管理,也可能被其他文件用到。删除文件时需慎重!! |
|