歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python寫的系統常用命令

Python寫的系統常用命令

日期:2017/3/1 10:13:22   编辑:Linux編程

python寫的系統常用命令,linux和windows通用,用的時候直接from util import *導入即可使用,很方便,本來是一個腳本,分成兩部分發了。

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # 通用功能類封裝
  4. import os,time,sys,string,urllib,httplib,shutil,platform,tarfile
  5. from commands import getstatusoutput as getso
  6. from ConfigParser import *
  7. def wr_log(str_cmd, status=0, result=""):
  8. cur_time = time.strftime("%Y-%m-%d %H:%M:%S")
  9. if status == 0:
  10. fp = open("../log/log.txt",'a+')
  11. fp.write("[%s]\t%s\tdone!\n" % (cur_time, str_cmd))
  12. fp.close()
  13. else:
  14. fp = open("../log/err_log.txt",'a+')
  15. fp.write("[%s]\t%s\tfailed!\n%s\n\n" % (cur_time, str_cmd, result))
  16. fp.close()
  17. sys.exit(-1)
  18. def wget(url, new_name=""):
  19. '''''
  20. wget封裝,需提供下載地址,新文件名參數可省略。
  21. 例子:
  22. wget("http://208.asktao.com/test.txt", "/tmp/test.txt")
  23. '''
  24. try:
  25. file_name = url[url.rfind("/")+1:]
  26. if new_name == "":
  27. new_name = file_name
  28. fp = urllib.urlopen(url)
  29. py_ver = sys.version[:3]
  30. if py_ver == "2.4":
  31. domain = url.split("/")[2]
  32. get_file = "/" + "/".join(url.split("/")[3:])
  33. conn = httplib.HTTPConnection(domain)
  34. conn.request('GET', get_file)
  35. fp_code = conn.getresponse().status
  36. else:
  37. fp_code = fp.getcode()
  38. if fp_code != 200:
  39. raise NameError, '%s not exist.'%file_name
  40. buf_len = 2048
  41. f = open(new_name, 'wb')
  42. size = 0
  43. while 1:
  44. s = fp.read(buf_len)
  45. if not s:
  46. break
  47. f.write(s)
  48. size += len(s)
  49. fp.close()
  50. f.close()
  51. wr_log("wget %s"%url)
  52. except Exception, e:
  53. wr_log("wget %s"%url, 1, e)
  54. def sed(type, file_name, s_str="", d_str=""):
  55. '''''
  56. sed封裝,根據傳入的type參數執行相應操作,type可以為以下幾種:
  57. a 在s_str行後面追加d_str,若s_str為空,則默認在文件尾部追加;
  58. i 在s_str行前面插入d_str,若s_str為空,則默認在文件頭部插入;
  59. d 刪除s_str所在行;
  60. s 將s_str替換為d_str。
  61. type及file_name為必需的參數。
  62. 例子:
  63. 替換字符串:sed("s", "/etc/test.txt", "abc", "123")
  64. '''
  65. try:
  66. fp = open(file_name)
  67. cont = fp.read()
  68. fp.close()
  69. content = cont.split("\n")
  70. content2 = cont.split("\n")
  71. cnt = 0
  72. idx = 0
  73. if type == "a":
  74. str_cmd = "sed -i '/%s/a %s' %s" % (s_str, d_str, file_name)
  75. if not s_str:
  76. content.append(d_str)
  77. else:
  78. for i in content2:
  79. if i.find(s_str) != -1:
  80. x = idx + 1 + cnt
  81. content.insert(x, d_str)
  82. cnt += 1
  83. idx += 1
  84. elif type == "i":
  85. str_cmd = "sed -i '/%s/i %s' %s" % (s_str, d_str, file_name)
  86. if not s_str:
  87. content.insert(0, d_str)
  88. else:
  89. for i in content2:
  90. if i.find(s_str) != -1:
  91. x = idx + cnt
  92. content.insert(x, d_str)
  93. cnt += 1
  94. idx += 1
  95. elif type == "d":
  96. str_cmd = "sed -i '/%s/d' %s" % (s_str, file_name)
  97. for i in content2:
  98. if i.find(s_str) != -1:
  99. idx = content.remove(i)
  100. elif type == "s":
  101. str_cmd = "sed -i 's/%s/%s/g' %s" % (s_str, d_str, file_name)
  102. cont = string.replace(cont, s_str, d_str)
  103. content = cont.split("\n")
  104. fp = open(file_name, "w")
  105. fp.write("\n".join(content))
  106. fp.close()
  107. wr_log(str_cmd)
  108. except Exception, e:
  109. wr_log("modify %s" % file_name, 1, e)
  110. def md(dir_name):
  111. '''''
  112. mkdir封裝,創建傳入的目錄名稱。
  113. '''
  114. try:
  115. if not os.path.exists(dir_name):
  116. os.makedirs(dir_name)
  117. wr_log("mkdir %s"%dir_name)
  118. else:
  119. wr_log("%s is exist."%dir_name)
  120. except Exception, e:
  121. wr_log("mkdir %s"%dir_name, 1, e)
  122. def mv(src, dst):
  123. '''''
  124. mv封裝,移動文件或修改文件名。
  125. '''
  126. try:
  127. try:
  128. os.rename(src, dst)
  129. except OSError:
  130. if os.path.dirname(src) == dst or os.path.dirname(src) == os.path.dirname(dst):
  131. raise Exception, "Cannot move self."
  132. if os.path.isdir(src):
  133. if os.path.abspath(dst).startswith(os.path.abspath(src)):
  134. raise Exception, "Cannot move a directory to itself."
  135. _copy(src, dst)
  136. shutil.rmtree(src)
  137. else:
  138. shutil.copy2(src,dst)
  139. os.unlink(src)
  140. wr_log("mv %s %s"%(src, dst))
  141. except Exception, e:
  142. wr_log("mv %s %s"%(src, dst), 1, e)
  143. def cp(src, dst):
  144. '''''
  145. cp封裝,復制文件或目錄。
  146. '''
  147. try:
  148. _copy(src, dst)
  149. wr_log("cp %s %s"%(src, dst))
  150. except Exception, e:
  151. wr_log("cp %s %s"%(src, dst), 1, e)
  152. def _copy(src, dst):
  153. '''''
  154. copy封裝,供cp調用。
  155. '''
  156. if os.path.isdir(src):
  157. base = os.path.basename(src)
  158. if os.path.exists(dst):
  159. dst = os.path.join(dst, base)
  160. if not os.path.exists(dst):
  161. os.makedirs(dst)
  162. names = os.listdir(src)
  163. for name in names:
  164. srcname = os.path.join(src, name)
  165. _copy(srcname, dst)
  166. else:
  167. shutil.copy2(src, dst)
  168. def touch(src):
  169. '''''
  170. linux適用
  171. touch封裝,新建空白文件。
  172. '''
  173. str_cmd = "/bin/touch %s" % src
  174. status, result = getso(str_cmd)
  175. wr_log(str_cmd, status, result)
  176. def rm(src):
  177. '''''
  178. rm封裝,刪除文件或目錄,非交互式操作���請謹慎操作。
  179. '''
  180. try:
  181. if os.path.exists(src):
  182. if os.path.isfile(src):
  183. os.remove(src)
  184. elif os.path.isdir(src):
  185. shutil.rmtree(src)
  186. wr_log("rm %s" % src)
  187. except Exception, e:
  188. wr_log("rm %s" % src, 1, e)
  189. def chmod(num, file_name):
  190. '''''
  191. linux適用
  192. chmod封裝,修改文件權限。
  193. 需要傳入一個八進制數以及文件名。
  194. 例子:
  195. chmod(644, "/tmp/test.txt")
  196. '''
  197. str_cmd = "/bin/chmod %s %s" % (num, file_name)
  198. status, result = getso(str_cmd)
  199. wr_log(str_cmd, status, result)
  200. def chown(user, file_name, arg=""):
  201. '''''
  202. linux適用
  203. chown封裝,修改文件屬主屬組。
  204. 例子:
  205. chown("nobody.nobody", "/tmp", "r")
  206. '''
  207. if arg == "r":
  208. str_cmd = "/bin/chown -R %s %s" % (user, file_name)
  209. else:
  210. str_cmd = "/bin/chown %s %s" % (user, file_name)
  211. status, result = getso(str_cmd)
  212. wr_log(str_cmd, status, result)
  213. def rar(dst,src):
  214. '''''
  215. windows適用
  216. winrar 壓縮文件 如: rar(c:\dat.rar c:\dat)
  217. '''
  218. try:
  219. if not os.path.exists(src) or not os.path.exists(os.path.dirname(dst)):
  220. raise Exception, "%s or %s not exist!" % (src, os.path.dirname(dst))
  221. os.system(r'C:\Progra~1\WinRAR\rar a %s %s' % (dst,src))
  222. wr_log("rar %s to %s" % (src, dst))
  223. except Exception,e:
  224. wr_log("rar %s to %s" % (src, dst), 1, e)
  225. def unrar(src,dst):
  226. '''''
  227. windows適用
  228. unrar 解壓縮rar文件 到目標路徑 如:unrar(c:\dat.rar c:\)
  229. '''
  230. try:
  231. if not os.path.exists(dst) or not os.path.exists(src):
  232. raise Exception, "%s or %s not exist!" % (src, dst)
  233. os.system(r'C:\Progra~1\WinRAR\rar x %s %s' % (src, dst))
  234. wr_log("unrar %s" % src)
  235. except Exception,e:
  236. wr_log("unrar %s" % src, 1, e)
  237. def tar(dst, src):
  238. '''''
  239. linux適用
  240. tar封裝,壓縮文件。
  241. 例子:
  242. tar("/tmp/test.tgz", "/tmp/test.txt")
  243. '''
  244. str_cmd = "/bin/tar zcf %s %s" % (dst, src)
  245. status, result = getso(str_cmd)
  246. wr_log(str_cmd, status, result)
  247. def untgz(tgz_file, dst="./"):
  248. '''''
  249. tar封裝,解壓縮文件。
  250. 例子:
  251. untgz("/tmp/test.tgz", "/tmp")
  252. '''
  253. try:
  254. tarobj = tarfile.open(tgz_file)
  255. names = tarobj.getnames()
  256. for name in names:
  257. tarobj.extract(name,path=dst)
  258. tarobj.close()
  259. wr_log("untgz %s" % tgz_file)
  260. except Exception, e:
  261. wr_log("untgz %s" % tgz_file, 1, e)
  262. def kill(arg):
  263. '''''
  264. linux中,查找進程並殺死返回的pid。
  265. windows中,查找進程或端口並殺死返回的pid。
  266. '''
  267. pid = get_pid(arg)
  268. os_type = platform.system()
  269. if os_type == "Linux":
  270. if pid:
  271. str_cmd = "/bin/kill -9 %s" % pid
  272. status, result = getso(str_cmd)
  273. wr_log("kill %s" % arg, status, result)
  274. elif os_type == "Windows":
  275. if pid:
  276. try:
  277. import ctypes
  278. for i in pid:
  279. handle = ctypes.windll.kernel32.OpenProcess(1, False, i)
  280. ctypes.windll.kernel32.TerminateProcess(handle,0)
  281. wr_log("kill %s" % arg)
  282. except Exception, e:
  283. wr_log("kill %s" % arg, 1, e)
  284. def get_pid(arg):
  285. '''''
  286. linux中,查找進程並返回pid。
  287. windows中,查找進程或端口返回pid。
  288. '''
  289. os_type = platform.system()
  290. if os_type == "Linux":
  291. str_cmd = "/bin/ps auxww | grep '%s' | grep -v grep | awk '{print $2}'" % arg
  292. status, result = getso(str_cmd)
  293. return result
  294. elif os_type == "Windows":
  295. if type(arg) == int:
  296. str_cmd = "netstat -ano|find \"%s\""%arg
  297. try:
  298. result = os.popen(str_cmd,"r").read()
  299. result = result.split("\n")[0].strip()
  300. if result.find("WAIT") != -1:
  301. return 0
  302. pid = int(result[result.rfind(" "):].strip())
  303. return [pid]
  304. except Exception, e:
  305. return 0
  306. else:
  307. import win32con,win32api,win32process
  308. pids = []
  309. for pid in win32process.EnumProcesses():
  310. try:
  311. hProcess = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid)
  312. hProcessFirstModule = win32process.EnumProcessModules(hProcess)[0]
  313. processName = os.path.splitext(os.path.split(win32process.GetModuleFileNameEx(hProcess, hProcessFirstModule))[1])[0]
  314. if processName == arg:
  315. pids.append(pid)
  316. except Exception, e:
  317. pass
  318. return pids
  319. def grpadd(grp_name):
  320. '''''
  321. linux適用
  322. groupadd封裝,增加組。
  323. '''
  324. str_cmd = "/usr/sbin/groupadd %s" % grp_name
  325. status, result = getso(str_cmd)
  326. wr_log(str_cmd, status, result)
  327. def useradd(user_name, arg=""):
  328. '''''
  329. useradd封裝,添加新用戶;
  330. linux和windows系統分別使用不同方法;
  331. 在linux中,arg填寫新用戶的gid;
  332. windows中,arg填寫新用戶的密碼。
  333. '''
  334. os_type = platform.system()
  335. if os_type == "Linux":
  336. str_cmd = "/usr/bin/id %s" % user_name
  337. status, result = getso(str_cmd)
  338. if status == 0:
  339. return
  340. if not arg:
  341. str_cmd = "/usr/sbin/useradd %s" % user_name
  342. else:
  343. str_cmd = "/usr/sbin/useradd -g %s %s" % (arg, user_name)
  344. status, result = getso(str_cmd)
  345. wr_log(str_cmd, status, result)
  346. elif os_type == "Windows":
  347. try:
  348. import win32netcon,win32net,wmi
  349. for use in wmi.WMI().Win32_UserAccount():
  350. if use.name == user_name:
  351. raise Exception, "user %s is already exists" % user_name
  352. udata = {}
  353. udata["name"] = user_name
  354. udata["password"] = arg
  355. udata["flags"] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
  356. udata["priv"] = win32netcon.USER_PRIV_USER
  357. win32net.NetUserAdd(None, 1, udata)
  358. wr_log("add user %s" % user_name)
  359. except Exception,e:
  360. wr_log("add user %s" % user_name, 1, e)
  361. def userdel(user_name):
  362. '''''
  363. userdel封裝,刪除用戶。
  364. '''
  365. os_type = platform.system()
  366. if os_type == "Linux":
  367. str_cmd = "/usr/bin/id %s" % user_name
  368. status, result = getso(str_cmd)
  369. if status == 0:
  370. str_cmd = "/usr/sbin/userdel -r %s" % user_name
  371. status, result = getso(str_cmd)
  372. wr_log(str_cmd, status, result)
  373. elif os_type == "Windows":
  374. try:
  375. import win32net,wmi
  376. for use in wmi.WMI().Win32_UserAccount():
  377. if use.name == user_name:
  378. win32net.NetUserDel(None,user_name)
  379. wr_log("del user %s" % user_name)
  380. return
  381. wr_log("user %s not exists" % user_name)
  382. except Exception,e:
  383. wr_log("del user %s" % user_name, 1, e)
Copyright © Linux教程網 All Rights Reserved