You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

347 lines
13 KiB

  1. #-*- coding: utf-8 -*-
  2. # Copyright 2008-2010 Mir Calculate. http://www.calculate-linux.org
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import re
  16. import os
  17. import types
  18. import cl_utils
  19. import cl_base
  20. class fillVars(object, cl_base.glob_attr):
  21. def get_os_net_domain(self):
  22. ''' Определим домен'''
  23. domain=self._runos("hostname -d 2>&1")
  24. if not domain:
  25. print _("Error:") + " " +_("Not found domain name")
  26. print _("Command 'hostname -d' returns an empty value")
  27. cl_base.exit(1)
  28. elif re.search("^hostname: ",domain):
  29. return "local"
  30. else:
  31. return domain
  32. def get_os_linux_shortname(self):
  33. '''Получить переменную короткого названия системы'''
  34. path = '/etc/calculate/calculate.ini'
  35. if os.path.exists(path):
  36. FD = open(path)
  37. data = FD.readlines()
  38. FD.close()
  39. shortNameList = filter(lambda y:y,
  40. map(lambda x:\
  41. len(x.split("="))==2 and\
  42. x.split("=")[0]=="calculate" and\
  43. x.split("=")[1].strip(), data))
  44. if shortNameList:
  45. return shortNameList[0]
  46. gentooFile = "/etc/gentoo-release"
  47. shortName = "Linux"
  48. if os.path.exists(gentooFile):
  49. shortName = "Gentoo"
  50. return shortName
  51. def get_os_linux_name(self):
  52. """полное название системы"""
  53. linuxShortName = self.Get("os_linux_shortname")
  54. if linuxShortName:
  55. dictLinuxName = {"CLD":"Calculate Linux Desktop",
  56. "CLDX":"Calculate Linux Desktop",
  57. "CLDG":"Calculate Linux Desktop",
  58. "CDS":"Calculate Directory Server",
  59. "Gentoo":"Gentoo"}
  60. if linuxShortName in dictLinuxName.keys():
  61. return dictLinuxName[linuxShortName]
  62. else:
  63. return "Linux"
  64. else:
  65. return "Linux"
  66. def get_os_linux_subname(self):
  67. """постфикс к названию системы"""
  68. linuxShortName = self.Get("os_linux_shortname")
  69. if linuxShortName:
  70. dictLinuxSubName = {"CLD":"KDE", "CLDX":"XFCE", "CLDG":"GNOME"}
  71. if linuxShortName in dictLinuxSubName.keys():
  72. return dictLinuxSubName[linuxShortName]
  73. else:
  74. return ""
  75. else:
  76. return ""
  77. def get_os_linux_ver(self):
  78. '''Получить версию системы'''
  79. path = '/etc/calculate/calculate.ini'
  80. if os.path.exists(path):
  81. FD = open(path)
  82. data = FD.readlines()
  83. FD.close()
  84. shortNameList = filter(lambda y:y,
  85. map(lambda x:\
  86. len(x.split("="))==2 and\
  87. x.split("=")[0]=="linuxver" and\
  88. x.split("=")[1].strip(), data))
  89. if shortNameList:
  90. return shortNameList[0]
  91. gentooFile = "/etc/gentoo-release"
  92. systemVersion = ""
  93. flagGentoo = False
  94. if os.path.exists(gentooFile):
  95. gentooLink = "/etc/make.profile"
  96. if os.path.islink(gentooLink):
  97. systemVersion = os.readlink(gentooLink).rpartition("/")[2]
  98. flagGentoo = True
  99. if not flagGentoo:
  100. kernelVersion=self._runos("uname -r")
  101. if kernelVersion:
  102. systemVersion = kernelVersion.partition("-")[0]
  103. return systemVersion
  104. def get_os_net_hostname(self):
  105. '''Считать имя компьютера net_host'''
  106. hostname=self._runos("hostname -s 2>&1")
  107. if not hostname:
  108. return ""
  109. if re.search("^hostname: ",hostname):
  110. hostname=self._runos("hostname 2>&1")
  111. if not hostname:
  112. return ""
  113. if re.search("^hostname: ",hostname):
  114. return self.Get('os_linux_shortname')
  115. else:
  116. if hostname=='livecd':
  117. return self.Get('os_linux_shortname')
  118. return hostname
  119. # все ip
  120. def get_os_net_ip(self):
  121. """все ip компьютера, разделитель запятая"""
  122. IPs = []
  123. netInterfaces=cl_utils.getdirlist("/sys/class/net/")
  124. for i in netInterfaces:
  125. res = self._runos("/sbin/ifconfig %s"%i)
  126. if not res:
  127. break
  128. for line in res:
  129. searchIP = re.search('addr:([0-9\.]+).+Bcast:', line)
  130. if searchIP:
  131. # ip адрес
  132. ip = searchIP.groups()[0]
  133. IPs.append(ip)
  134. return ",".join(IPs)
  135. # Разрешенные сети (в данном случае все сети)
  136. def get_os_net_allow(self):
  137. """Разрешенные сети разделитель запятая"""
  138. def getNet(ip, mask):
  139. """По ip и маске получаем сеть"""
  140. octetsMult = (0x1, 0x100, 0x10000, 0x1000000)
  141. octetsIp = map(lambda x: int(x), ip.split("."))
  142. octetsMask = map(lambda x: int(x), mask.split("."))
  143. ipNumb = 0
  144. for i in octetsMult:
  145. ipNumb += octetsIp.pop()*i
  146. maskNumb = 0
  147. for i in octetsMult:
  148. maskNumb += octetsMask.pop()*i
  149. startIpNumber = maskNumb&ipNumb
  150. x = startIpNumber
  151. nMask = lambda y: len(filter(lambda x: y >> x &1 ,range(32)))
  152. return "%s.%s.%s.%s/%s"\
  153. %(x>>24, x>>16&255, x>>8&255, x&255, nMask(maskNumb))
  154. networks=[]
  155. netInterfaces=cl_utils.getdirlist("/sys/class/net/")
  156. flagError = False
  157. for i in netInterfaces:
  158. res = self._runos("/sbin/ifconfig %s"%i)
  159. if not res:
  160. flagError = True
  161. break
  162. for j in res:
  163. s_ip=re.search('addr:([0-9\.]+).+Bcast:.+Mask:([0-9\.]+)' ,j)
  164. if s_ip:
  165. ip, mask = s_ip.groups()
  166. networks.append(getNet(ip, mask))
  167. if flagError:
  168. return ""
  169. return ",".join(networks)
  170. def get_os_locale_locale(self):
  171. """локаль (прим: ru_RU.UTF-8)"""
  172. if os.environ.has_key("LANG"):
  173. return os.environ["LANG"]
  174. else:
  175. return "en_US.UTF-8"
  176. def get_os_locale_lang(self):
  177. """язык (прим: ru_RU)"""
  178. locale = self.Get("os_locale_locale")
  179. if locale:
  180. return locale.split(".")[0]
  181. return ""
  182. def get_os_locale_language(self):
  183. """язык (прим: ru)"""
  184. lang = self.Get("os_locale_lang")
  185. if lang:
  186. return lang.split("_")[0]
  187. return ""
  188. def get_os_locale_xkb(self):
  189. """раскладка клавиатуры для X"""
  190. path = '/etc/conf.d/keymaps'
  191. mapDict={"by":"us,by",
  192. "be-latin1":"be,us",
  193. "br-abnt2":"br,us",
  194. "cf":"ca,us",
  195. "dk-latin1":"dk,us",
  196. "fr-latin9":"fr,us",
  197. "de-latin1":"de,us",
  198. "is-latin1":"is,us",
  199. "it":"it,us",
  200. "no-latin1":"no,us",
  201. "pl":"pl,us",
  202. "-u ru4":"us,ru(winkeys)",
  203. "es euro2":"es,us",
  204. "sv-latin1":"se,us",
  205. "ua-utf":"us,ua(winkeys)",
  206. "uk":"gb,us",
  207. "us":"us"}
  208. if os.path.exists(path):
  209. FD = open(path)
  210. data = FD.readlines()
  211. FD.close()
  212. shortNameList = filter(lambda y:y,
  213. map(lambda x:\
  214. len(x.split("="))==2 and\
  215. x.split("=")[0]=="KEYMAP" and\
  216. x.split("=")[1].replace('"',"").strip(),\
  217. data))
  218. if shortNameList:
  219. if shortNameList[0] in mapDict.keys():
  220. return mapDict[shortNameList[0]]
  221. lang = self.Get("os_locale_lang")
  222. # Языки:
  223. # Португальский - pt_BR
  224. # Французский - fr_FR
  225. # Немецкий - de_DE
  226. # Итальянский - it_IT
  227. # Польский - pl_PL
  228. # Русский - ru_RU
  229. # Испанский - es_ES
  230. # Украинский - uk_UA
  231. # Английский - en_US
  232. xkbDict = {'pt_BR':'br,us',
  233. 'fr_FR':'fr,us',
  234. 'de_DE':'de,us',
  235. 'it_IT':'it,us',
  236. 'pl_PL':'pl,us',
  237. 'ru_RU':'us,ru(winkeys)',
  238. 'es_ES':'es,us',
  239. 'uk_UA':'us,ua(winkeys)',
  240. 'en_US':'us'}
  241. if lang:
  242. if xkbDict.has_key(lang):
  243. return xkbDict[lang]
  244. return ""
  245. def get_os_locale_xkbname(self):
  246. """названия используемых раскладок клавиатуры для X"""
  247. localeXkb = self.Get("os_locale_xkb")
  248. if localeXkb:
  249. return localeXkb.split("(")[0]
  250. return ""
  251. def get_os_arch_machine(self):
  252. """архитектура процессора"""
  253. march = self._runos("uname -m")
  254. if not march:
  255. return ""
  256. return march
  257. def get_os_root_dev(self):
  258. """корневой раздел файловой системы"""
  259. for record in open('/proc/cmdline','rb').readlines():
  260. re_res=re.search('^root=(\/dev\/[a-z]+[0-9]).*',record.strip())
  261. if re_res:
  262. return re_res.group(1)
  263. else:
  264. mountLunes = self._runos("mount")
  265. if not mountLunes:
  266. return ""
  267. if type(mountLunes) == types.ListType:
  268. root_dev = mountLunes[0].split("on / type")[0].strip()
  269. if root_dev:
  270. return root_dev
  271. return ""
  272. def get_os_root_type(self):
  273. """тип носителя (ram, hdd, livecd)"""
  274. mountLunes = self._runos("mount")
  275. if not mountLunes:
  276. return ""
  277. rootType = "hdd"
  278. if type(mountLunes) == types.ListType:
  279. flagCD = False
  280. for line in mountLunes:
  281. if "/dev/loop0 on / type" in line:
  282. rootType = "ram"
  283. break
  284. elif "/dev/loop0 on /newroot/mnt/livecd type" in line:
  285. rootType = "ram"
  286. flagCD = True
  287. break
  288. if rootType == "ram":
  289. if os.path.exists("/mnt/livecd") or flagCD:
  290. rootType = "livecd"
  291. return rootType
  292. rootDev = self.Get("os_root_dev")
  293. if rootType != "ram" and rootDev:
  294. slpRootDev = rootDev.split("/dev/")
  295. if len(slpRootDev) == 2:
  296. rDev = slpRootDev[1]
  297. devLines = self._runos("ls -la /dev/disk/by-id/", None,
  298. {"LANG":"C"})
  299. if not devLines:
  300. return ""
  301. if type(devLines) == types.ListType:
  302. for line in devLines:
  303. if rDev in line and "usb-" in line:
  304. rootType = "usb-hdd"
  305. break
  306. if rootType == "ram":
  307. rootType = "hdd"
  308. return rootType
  309. else:
  310. return ""
  311. def get_hr_virtual(self):
  312. """Название виртуальной машины (virtualbox, vmware, qemu)"""
  313. pciLines = self._runos("/usr/sbin/lspci")
  314. if not pciLines:
  315. return False
  316. virtSysDict = {'VirtualBox':'virtualbox',
  317. 'VMware':'vmware',
  318. 'Qumranet':'qemu'}
  319. virtName = ''
  320. for vName in virtSysDict.keys():
  321. if filter(lambda x: vName in x, pciLines):
  322. virtName = virtSysDict[vName]
  323. break
  324. return virtName