• easiLinux: 一种基于python的linux功能命令简易化脚本


    开源项目,期待参与。

    代码链接:gitee地址     https://github.com/muzhaoyang90/easilinux/blob/main/easiLinux.pyicon-default.png?t=N7T8https://github.com/muzhaoyang90/easilinux/blob/main/easiLinux.py

    1. 代码链接:https://github.com/muzhaoyang90/easilinux/blob/main/easiLinux.py
    2. 语言:python
    3. 支持环境:linux
    4. 功能:我的easi系列之一(意思是易于使用),易于使用的linux。包括一些有用的、有趣的函数。比如通过easycommon监控多台服务器,通过一个命令查找服务、文件、文件夹,玩游戏,与机器人聊天等等。
    5. ​愿景:build a series that make life or code much easier and intelligence!
    1. #!/usr/bin/python3
    2. """
    3. #time: 2021年9月8日21:51:02
    4. #author: moobc
    5. #function: easi use linux. it can find file, monitor service,and run linux original order directly。and it has a nice frame to easily extend fuction
    6. #update: 2022年2月13日17:48:00 make it more easier to use.
    7. """
    8. import datetime, os, re, subprocess, time
    9. from threading import Timer
    10. # linux need to import the readline below; windows not
    11. import readline
    12. class aiModel():
    13. def __init__(self, *ags):
    14. self.aiDict = {'help': self.aiHelp, 'hello': self.aiHello}
    15. def aiTransfer(self, order):
    16. """
    17. 解析ai命令
    18. :param order: 解析传入到ai类的执行命令
    19. :return: None
    20. """
    21. orderlist = order.split(' ')
    22. length = orderlist.__len__()
    23. try:
    24. fuc = self.aiDict.get(orderlist[0])
    25. if fuc:
    26. fuc()
    27. except (TypeError):
    28. return
    29. def aiHelp(self, *ags):
    30. aiHelpInfo = """
    31. say whatever you what to ask.it will be upgrade later.
    32. """
    33. print(aiHelpInfo)
    34. def aiHello(self, *ags):
    35. """
    36. 随机响应,hello
    37. :param ags:
    38. :return:
    39. """
    40. hello = """
    41. hello,i'm eL, created by bigSea at 13 Sep. 2021.
    42. """
    43. print(hello)
    44. class linuxModule():
    45. def __init__(self, *ags):
    46. """
    47. linux原生的命令处理模块,废弃,当前可以直接使用
    48. :param ags:
    49. """
    50. pass
    51. def beRoot(self):
    52. pass
    53. class usageWarning():
    54. def __init__(self, *ags):
    55. """
    56. 用于查看linux当前系统的资源使用率。包含硬盘、内存、cpu
    57. :param ags: 命令集
    58. """
    59. self.usageDict = {'help': self.usageHelp, 'disk': self.warnDisk, 'cpu': self.warnCpu, 'memory': self.warnMemory,
    60. 'all': self.warnAll}
    61. def usageTransfer(self, order):
    62. orderlist = order.split(' ')
    63. length = orderlist.__len__()
    64. try:
    65. if length == 2:
    66. self.usageDict.get(orderlist[1])()
    67. elif length == 1:
    68. print('warn Module need more params,see \'warn help\'')
    69. except (TypeError):
    70. return
    71. def usageHelp(self, *ags):
    72. usageHelpInfo = """
    73. 命令 示例 说明
    74. warn :warn disk #打印硬盘使用占用信息。
    75. :warn cpu #打印cpu使用占用信息
    76. :warn memory #打印内存使用占用信息
    77. :warn all #打印cpu、硬盘、内存、系统平均负载
    78. """
    79. print(usageHelpInfo)
    80. def warnCpu(self, *ags):
    81. """
    82. 查询cpu的使用率
    83. :param ags:
    84. :return:
    85. """
    86. cpu_usage = int(self.get_cpu() * 100)
    87. print("CPU使用率(最大100%):" + str(cpu_usage) + "%")
    88. def warnDisk(self, *ags):
    89. """
    90. 查询硬盘使用率
    91. :param ags:
    92. :return:
    93. """
    94. statvfs = os.statvfs('/') # 根目录信息 可根据情况修改
    95. total_disk_space = statvfs.f_frsize * statvfs.f_blocks
    96. free_disk_space = statvfs.f_frsize * statvfs.f_bfree
    97. disk_usage = (total_disk_space - free_disk_space) * 100.0 / total_disk_space
    98. disk_usage = int(disk_usage)
    99. print("硬盘空间使用率(最大100%):" + str(disk_usage) + "%")
    100. def warnMemory(self, *ags):
    101. """
    102. 查询内存使用率
    103. :param ags:
    104. :return:
    105. """
    106. mem_usage = self.get_mem_usage_percent()
    107. mem_usage = int(mem_usage[0])
    108. print("物理内存使用率(最大100%):" + str(mem_usage) + "%")
    109. def warnAll(self, *ags):
    110. """
    111. 查询linux系统常见的3种资源指标使用率
    112. :param ags:
    113. :return:
    114. """
    115. cpu_usage = int(self.get_cpu() * 100)
    116. cpu_tip = "CPU使用率(最大100%):" + str(cpu_usage) + "%"
    117. statvfs = os.statvfs('/') # 根目录信息 可根据情况修改
    118. total_disk_space = statvfs.f_frsize * statvfs.f_blocks
    119. free_disk_space = statvfs.f_frsize * statvfs.f_bfree
    120. disk_usage = (total_disk_space - free_disk_space) * 100.0 / total_disk_space
    121. disk_usage = int(disk_usage)
    122. disk_tip = "硬盘空间使用率(最大100%):" + str(disk_usage) + "%"
    123. mem_usage = self.get_mem_usage_percent()
    124. mem_usage = int(mem_usage[0])
    125. mem_tip = "物理内存使用率(最大100%):" + str(mem_usage) + "%"
    126. load_average = os.getloadavg()
    127. load_tip = "系统负载(三个数值(1分钟、5分钟、15分钟系统平均负载)中有一个超过3就是高):" + str(load_average)
    128. all_tip = cpu_tip + '\r\n' + disk_tip + '\r\n' + mem_tip + '\r\n' + load_tip
    129. print(all_tip)
    130. # 获取CPU负载信息
    131. def get_cpu(self, *ags):
    132. last_worktime = 0
    133. last_idletime = 0
    134. f = open("/proc/stat", "r")
    135. line = ""
    136. while not "cpu " in line: line = f.readline()
    137. f.close()
    138. spl = line.split(" ")
    139. worktime = int(spl[2]) + int(spl[3]) + int(spl[4])
    140. idletime = int(spl[5])
    141. dworktime = (worktime - last_worktime)
    142. didletime = (idletime - last_idletime)
    143. rate = float(dworktime) / (didletime + dworktime)
    144. last_worktime = worktime
    145. last_idletime = idletime
    146. if (last_worktime == 0): return 0
    147. return rate
    148. # 获取内存负载信息
    149. def get_mem_usage_percent(self, *ags):
    150. try:
    151. f = open('/proc/meminfo', 'r')
    152. for line in f:
    153. if line.startswith('MemTotal:'):
    154. mem_total = int(line.split()[1])
    155. elif line.startswith('MemFree:'):
    156. mem_free = int(line.split()[1])
    157. elif line.startswith('Buffers:'):
    158. mem_buffer = int(line.split()[1])
    159. elif line.startswith('Cached:'):
    160. mem_cache = int(line.split()[1])
    161. elif line.startswith('SwapTotal:'):
    162. vmem_total = int(line.split()[1])
    163. elif line.startswith('SwapFree:'):
    164. vmem_free = int(line.split()[1])
    165. else:
    166. continue
    167. f.close()
    168. except:
    169. return None
    170. physical_percent = self.usage_percent(mem_total - (mem_free + mem_buffer + mem_cache), mem_total)
    171. virtual_percent = 0
    172. if vmem_total > 0:
    173. virtual_percent = self.usage_percent((vmem_total - vmem_free), vmem_total)
    174. return physical_percent, virtual_percent
    175. def usage_percent(self, use, total):
    176. try:
    177. ret = (float(use) / total) * 100
    178. except ZeroDivisionError:
    179. raise Exception("ERROR - zero division error")
    180. return ret
    181. # 获取系统占用信息
    182. def sys_info(self, *ags):
    183. load_average = os.getloadavg()
    184. load_tip = "系统负载(三个数值中有一个超过3就是高):" + str(load_average)
    185. return load_tip
    186. # 获取计算机当前时间
    187. def time_info(self, *ags):
    188. now_time = time.strftime('%Y-%m-%d %H:%M:%S')
    189. return "主机的当前时间:%s" % now_time
    190. # 获取计算机主机名称
    191. def hostname_info(self, *ags):
    192. hostnames = os.popen("hostname").read().strip()
    193. return "你的主机名是: %s" % hostnames
    194. # 获取IP地址信息
    195. def ip_info(self, *ags):
    196. ipadd = os.popen("ip a| grep ens192 | grep inet | awk '{print $2}'").read().strip()
    197. return ipadd
    198. # 获取根的占用信息
    199. def disk_info_root(self, *ags):
    200. child = subprocess.Popen(["df", "-h"], stdout=subprocess.PIPE)
    201. out = child.stdout.readlines()
    202. for item in out:
    203. line = item.strip().split()
    204. # 我这里只查看centos的根
    205. if '/dev/mapper/centos-root' in line:
    206. title = [u'-文件系统-', u'--容量-', u'-已用-', u'-可用-', u'-已用-', u'-挂载点--']
    207. content = "\t".join(title)
    208. if eval(line[4][0:-1]) > 60:
    209. line[0] = 'centos-root'
    210. content += '\r\n' + '\t'.join(line)
    211. return content
    212. class gameModule():
    213. def __init__(self, *ags):
    214. """
    215. 用于集成一些常用的小游戏。
    216. :param ags:
    217. """
    218. self.gameDict = {'help': self.gameHelp, 'run': self.gameRun, 'install': self.gameInstall, 'list': self.gameList}
    219. def gameTransfer(self, order=''):
    220. orderlist = order.split(' ')
    221. length = orderlist.__len__()
    222. try:
    223. if length == 2:
    224. self.gameDict.get(orderlist[1])()
    225. elif length >= 3:
    226. self.gameDict.get(orderlist[1])(orderlist[2])
    227. elif length == 1:
    228. print('game need more params,see \'game help\'')
    229. except (TypeError):
    230. return
    231. def gameHelp(self, *ags):
    232. gameHelpInfo = """
    233. 命令 示例 说明
    234. game :nethack #运行nethack
    235. :{game name} #运行{game name}
    236. game :install nethack #安装nethack
    237. :install {game name} #安装{game name}
    238. :list #目前支持的游戏列表
    239. """
    240. print(gameHelpInfo)
    241. def gameList(self, *ags):
    242. print('eL support game(untill now): nethack')
    243. def gameRun(self, gameName=''):
    244. if 'hack' in gameName.lower():
    245. os.system('cd ~ && nh/install/games/nethack')
    246. else:
    247. print('game named {name} not found! check the order or use f for help'.format(name=gameName))
    248. def gameInstall(self, gameName=''):
    249. if 'nethack' in gameName.lower():
    250. shellstr = 'yum groupinstall -y "development tools" && wget https://nethack.org/download/3.6.6/nethack-366-src.tgz && ' \
    251. 'tar -xaf nethack-366-src.tgz && cd NetHack-NetHack-3.6.6_Released/ && sys/unix/setup.sh sys/unix/hints/linux && ' \
    252. 'yum install -y ncurses-devel && make && make install && cd ~'
    253. subprocess.run(shellstr, shell=True, capture_output=True)
    254. print('use game run nethack')
    255. else:
    256. print('game named {name} not found! check the order or use h for help'.format(name=gameName))
    257. class psModel():
    258. def __init__(self, *ags):
    259. """
    260. ps模块,类linux原生模块,但是更简单了。
    261. :param ags:
    262. """
    263. self.psDict = {'help': self.psHelp}
    264. def psTransfer(self, order):
    265. orderlist = order.split(' ')
    266. length = orderlist.__len__()
    267. try:
    268. if length >= 2:
    269. fuc = self.psDict.get(orderlist[1])
    270. if fuc:
    271. fuc()
    272. else:
    273. self.ps(orderlist[1])
    274. elif length == 1:
    275. print('ps need more params, see \'ps help\'')
    276. except (TypeError):
    277. return
    278. def ps(self, applicationName=''):
    279. """
    280. ps核心处理函数
    281. :param applicationName:
    282. :return:
    283. """
    284. # infoStatus 0为正常,256,dead或不存在服务
    285. infoStatus = subprocess.run('ps -ef|grep {application} |grep -v grep'.format(application=applicationName),
    286. shell=True, capture_output=True)
    287. statusInfo = subprocess.run('systemctl status {application}'.format(application=applicationName),
    288. shell=True, capture_output=True)
    289. if statusInfo.returncode == 0:
    290. pid = re.findall('Main PID: (.+?) \(', statusInfo.stdout.decode())
    291. portInfo = subprocess.run('netstat -nap | grep {pid}'.format(pid=pid[0].strip()), shell=True,
    292. capture_output=True)
    293. print(
    294. '{separate}\r\ninfoStatus: {infoStatus}\r\n{separate}\r\nstatusInfo: {statusInfo}\r\n{separate}\r\nportInfo: {portInfo}\r\n{separate}'.format(
    295. infoStatus=infoStatus.stdout.decode(), separate='*-*' * 40, statusInfo=statusInfo.stdout.decode(),
    296. portInfo=portInfo.stdout.decode()))
    297. else:
    298. print('\'systemctl status {application}\' return error'.format(application=applicationName))
    299. def psHelp(self, *ags):
    300. psHelpInfo = """
    301. 命令 示例 说明
    302. ps :ps [applicationName] #查看进程信息。包含ps文件端口、进程占用端口、运行状态查询
    303. """
    304. print(psHelpInfo)
    305. class dogModel():
    306. def __init__(self, *ags):
    307. """
    308. monitor监控实现类。超简单的添加方式。只是定时,便捷添加和移除。
    309. :param ags:
    310. """
    311. self.dogFlag = False # dog标识
    312. self.dogBiteInterval = 120 # 监控间隔,secend
    313. self.timer = ''
    314. self.foodList = ['docker'] #list中的服务,需要满足,能够用systemctl start命令开启
    315. self.dogDict = {
    316. 'help': self.dogHelp,
    317. 'time': self.dogSet, 'settime': self.dogSet,
    318. 'add': self.dogAddService, 'setservice': self.dogAddService,
    319. 'bite': self.dogBite, 'go': self.dogBite, 'start': self.dogBite, 'begin': self.dogBite,
    320. 'sit': self.dogSit, 'stop': self.dogSit, 'quit': self.dogSit, 'q': self.dogSit, 'exit': self.dogSit,
    321. 'list': self.dogList, 'show': self.dogList
    322. }
    323. def dogTransfer(self, order=''):
    324. orderlist = order.split(' ')
    325. length = len(orderlist)
    326. try:
    327. if length == 2:
    328. self.dogDict.get(orderlist[1])()
    329. elif length >= 3:
    330. self.dogDict.get(orderlist[1])(orderlist[2])
    331. elif length == 1:
    332. #print('easiDog: dog need more params,see \'dog help\'')
    333. self.dogHelp()
    334. except TypeError as e:
    335. return False
    336. #用于启动服务
    337. def dogBite(self, *ags):
    338. print('easiDog: dog监控运行中,当前服务list %s' % self.foodList)
    339. for applicationName in self.foodList:
    340. # infoStatus 0为正常,256,dead或不存在服务
    341. #procCheck = subprocess.run('ps -ef|grep {application} |grep -v grep'.format(application=applicationName), shell=True, capture_output=True)
    342. procCheck = subprocess.run('ps -ef|grep {application}'.format(application=applicationName),
    343. shell=True, capture_output=True)
    344. #print('easiDog: {application} 服务运行正常.'.format(application=applicationName))
    345. if procCheck.returncode != 0:
    346. subprocess.run('systemctl start {application}'.format(application=applicationName),
    347. shell=True, capture_output=True)
    348. print('easiDog: {application} 未在线,dog监控已尝试重启此服务.'.format(application=applicationName))
    349. #重置监控间隔时间。
    350. if self.timer != '':
    351. self.timer.cancel()
    352. self.timer = Timer(self.dogBiteInterval, self.dogBite)
    353. self.timer.start()
    354. def dogSit(self, *ags):
    355. if self.timer:
    356. self.timer.cancel()
    357. print('easiDog: dog程序已退出,Husky have return home')
    358. def dogList(self, *ags):
    359. print('easiDog: dog程序当前监控服务列表为 %s '
    360. '当前监控时间间隔为 %s '
    361. '\r\n 可通过dog add 进行添加,详情查看dog help' % (self.foodList, self.dogBiteInterval))
    362. def dogSet(self, second=120):
    363. try:
    364. self.dogBiteInterval = int(second)
    365. print('easiLog: 监控间隔时间已设置为 %s 秒,每 %s 将打印一次监控日志' % second)
    366. except Exception as e:
    367. print('easiLog: 监控间隔时间设置失败,请检查时间参数 %s' % second)
    368. return
    369. def dogAddService(self, service=''):
    370. #校验服务是否可添加内容
    371. if len(service) == 0:
    372. return False
    373. procCheck = subprocess.run('systemctl status {application}'.format(application=service), shell=True, capture_output=True)
    374. if procCheck.returncode != 0:
    375. print('easiLog: {service} 添加失败,请检查服务名,或确认是否适用于systemctl指令' % service)
    376. return False
    377. self.foodList.append(service)
    378. print('easiLog: {service} 已添加成功' % service)
    379. def dogHelp(self, *ags):
    380. dogHelpInfo = """
    381. dogMoudule 主要是用于监控服务进程,通过linux内置命令,可以持续对list中的服务进行监控。
    382. 若服务掉线,将通过命令尝试重启服务。这也要求,使用dog进行监控的服务,需要支持systemctl命令。
    383. 命令 示例 说明
    384. **********************************************************************************
    385. dog :dog time {second}; dog settime {second}; #设置轮询间隔时间。默认为120 s 描述一次。
    386. :dog add {service}; dog setservice {{service}} #添加{service}
    387. :dog bite; dog start; dog go; dog begin #定时监控程序重启。默认为 120s 扫描一次。可通过dog time设置
    388. :dog sit; dog stop; dog exit; dog q; dog quit #将停止dog监控。
    389. :dog list; dog show #将打印dog 当前服务列表。
    390. **********************************************************************************
    391. """
    392. print(dogHelpInfo)
    393. class easiLinux():
    394. def __init__(self):
    395. """
    396. easiLinux主流程类。命令入口。
    397. """
    398. self.flag = True # 程序运行控制标志
    399. self.orderHistory = [] # 存历史执行命令的列表
    400. self.dogM = dogModel() #实例化dog
    401. self.psM = psModel() #实例化ps
    402. self.aiM = aiModel() #实例化ai模块,目前还未完善
    403. self.usageW = usageWarning() #实例化资源监控模块
    404. self.gameM = gameModule() #实例化game模块
    405. self.sysDict = {
    406. 'dog': self.dogM.dogTransfer,
    407. 'ps': self.psM.psTransfer,
    408. 'find': self.find,
    409. 'run': self.run,
    410. 'warn': self.usageW.usageTransfer,
    411. 'exit': self.exit, 'quit': self.exit, 'stop': self.exit,
    412. 'hello': self.aiM.aiTransfer, 'hi': self.aiM.aiTransfer,
    413. 'game': self.gameM.gameTransfer,
    414. 'help': self.help, 'h': self.help,
    415. 'version': self.version, 'v': self.version,
    416. 'history': self.history
    417. }
    418. def mainLinux(self, *args):
    419. subprocess.run('clear', shell=True)
    420. self.version()
    421. while (self.flag):
    422. try:
    423. order = input('[mb@easiLinux ~]$ ')
    424. self.orderHistory.append(order)
    425. order = order.strip() # 提出头部空格
    426. if len(order) == 0:
    427. continue
    428. except KeyboardInterrupt:
    429. continue
    430. #处理命令;按空格分区,而后用首字段来匹配sysDict,调取对应实例。
    431. orderlist = order.split(' ')
    432. module = self.sysDict.get(orderlist[0])
    433. if module:
    434. module(order)
    435. else:
    436. try:
    437. os.system(order)
    438. except BaseException:
    439. continue
    440. def help(self, *args):
    441. helpInfo = """
    442. 命令 示例 说明
    443. **********************************************************************************
    444. dog :dog time {second}; dog settime {second}; #设置轮询间隔时间。默认为120 s 描述一次。
    445. :dog add {service}; dog setservice {{service}} #添加{service}
    446. :dog bite; dog start; dog go; dog begin #定时监控程序重启。默认为 120s 扫描一次。可通过dog time设置
    447. :dog sit; dog stop; dog exit; dog q; dog quit #将停止dog监控。
    448. :dog list; dog show #将打印dog 当前服务列表。
    449. **********************************************************************************
    450. ps :ps [applicationName] #查看进程信息。包含ps文件端口、进程占用端口、运行状态查询
    451. **********************************************************************************
    452. warn :warn disk #打印硬盘使用占用信息。
    453. :warn cpu #打印cpu使用占用信息
    454. :warn memory #打印内存使用占用信息
    455. :warn all #打印cpu、硬盘、内存、系统平均负载
    456. **********************************************************************************
    457. find :find [filename] #查找/usr/local/下文件
    458. **********************************************************************************
    459. version/v :version/v #查看easiLiunx版本信息
    460. **********************************************************************************
    461. game :game run nethack #运行nethack
    462. :game run {game name} #运行{game name}
    463. :game install nethack #安装nethack
    464. :game install {game name} #安装{game name}
    465. :list #目前支持的游戏列表
    466. **********************************************************************************
    467. exit :exit;q,quit #退出easiLinux
    468. """
    469. print(helpInfo)
    470. def exit(self, *args):
    471. self.flag = False
    472. def version(self, *args):
    473. now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    474. print(
    475. 'Welcome to easiLinux ! {date}\r\neasiLinx 1.1.0 ( Aug 29 2021, 01:13:18) \r\nType \"help\" for more information'.format(
    476. date=now))
    477. def history(self, *ags):
    478. num = 0
    479. for item in self.orderHistory:
    480. num += 1
    481. print('{num} {item}'.format(num=num, item=item))
    482. def find(self, fileName=''):
    483. if len(fileName) == 0:
    484. print('needs params: \'fileName\'')
    485. return
    486. proclist = []
    487. try:
    488. procwhich = subprocess.run('which {file}'.format(file=fileName), shell=True, capture_output=True)
    489. proclist.append(procwhich)
    490. procwhereis = subprocess.run('whereis {file}'.format(file=fileName), shell=True, capture_output=True)
    491. proclist.append(procwhereis)
    492. proclocate = subprocess.run('locate {file}'.format(file=fileName), shell=True, capture_output=True)
    493. proclist.append(proclocate)
    494. procfind = subprocess.run('find / -name {file}'.format(file=fileName), shell=True, capture_output=True)
    495. proclist.append(procfind)
    496. for proc in proclist:
    497. if proc.returncode == 0:
    498. print('%-50s\r\n{separate}'.format(separate='*-' * 40) % proc.stdout.decode())
    499. else:
    500. pass
    501. except BaseException:
    502. return
    503. def run(self, order=''):
    504. orderlist = order.split(' ', 1)
    505. return os.system(orderlist[1])
    506. if __name__ == '__main__':
    507. el = easiLinux()
    508. el.mainLinux()

    how to start!(安装第三方库)


    1. install all the package below
    2. import datetime, os, re, subprocess, time from threading import Timer
    3. #linux need to import the readline below; windows not
    4. import readline

    how to use!(如何使用)


    1. #in Liunx ;
    2. ./easiLinux.py
    3. #in windows
    4. python easiLinux.py
    5. #help #use help to see all function and command 
    6. help

     for more! (期望以外的)

    1. #u alse can type hello to it ! although it doesn't show in help. but we did it . we hope it can provide u a nice experience! 
    2. hello

    goal (愿景)

    build a series that make life or code much easier and intelligence!

    hope u can join us!!!!

  • 相关阅读:
    kubernetes集成GPU原理
    2000-2020全要素生产率OP法+LP法+OLS和固定效应法三种方法合集含原始数据和计算过程Stata代码
    一个简单好用安全的开源交互审计系统、轻量级堡垒机系统
    【arduino】I/O端口操作
    jsp+springmvc的校园失物招领管理平台
    Qt+GDAL开发笔记(二):在windows系统msvc207x64编译GDAL库、搭建开发环境和基础Demo
    tkmybatis 权威指南 官方文档
    CSS 实现祥云纹理背景
    东华大学Linux实验一
    PGSQL的on conflict
  • 原文地址:https://blog.csdn.net/i_likechard/article/details/127665863