def check_known_environment(): """ See that we run on a supported box. """ n = uname("-a").lower() if not ("debian" in n or "ubuntu" in n): sys.exit("This script has been tested only with Ubuntu/Debian environments")
def extract_config(): def git_sha(base=''): try: return str(sh.git('rev-parse', 'HEAD', _cwd=base)).strip() except Exception: return 'NA' config = c = {} versions = v = {} v['bloscpack'] = bp.__version__ v['numpy'] = np.__version__ v['joblib'] = jb.__version__ v['conda'] = str(sh.conda('--version', _tty_in=True)).strip() v['python'] = str(sh.python('--version', _tty_in=True)).strip() hashes = h = {} h['bloscpack'] = git_sha(os.path.dirname(bp.__file__)) h['joblib'] = git_sha(jb.__path__[0]) h['numpy'] = git_sha(np.__path__[0]) h['benchmark'] = git_sha() c['uname'] = str(sh.uname('-a')).strip() c['hostname'] = str(sh.hostname()).strip() c['whoami'] = str(sh.whoami()).strip() c['date'] = str(sh.date()).strip() c['versions'] = versions c['hashes'] = hashes return config
def __init__(self): self.parser = ConfigParser() # No option conversion, since we're using the key as a regex here self.parser.optionxform = str self.ostype = sh.uname().strip() cpath = os.path.realpath(__file__) self.parser.read([os.path.join(os.path.dirname(cpath), '%s.privacy.conf' % self.ostype), './%s.privacy.conf' % self.ostype])
def extract_config(): def git_sha(base=''): try: return str(sh.git('rev-parse', 'HEAD', _cwd=base)).strip() except Exception: return 'NA' config = c = {} versions = v = {} v['bloscpack'] = bp.__version__ v['blosc'] = blosc.__version__ v['numpy'] = np.__version__ v['joblib'] = jb.__version__ v['tables'] = tables.__version__ v['conda'] = str(sh.conda('--version', _tty_in=True)).strip() v['python'] = str(sh.python('--version', _tty_in=True)).strip() hashes = h = {} h['bloscpack'] = git_sha(os.path.dirname(bp.__file__)) h['joblib'] = git_sha(jb.__path__[0]) h['blosc'] = git_sha(blosc.__path__[0]) h['numpy'] = git_sha(np.__path__[0]) h['tables'] = git_sha(tables.__path__[0]) h['benchmark'] = git_sha() c['uname'] = str(sh.uname('-a')).strip() c['hostname'] = str(sh.hostname()).strip() c['whoami'] = str(sh.whoami()).strip() c['date'] = str(sh.date()).strip() c['versions'] = versions c['hashes'] = hashes return config
def main(): dpkg_output = dpkg('-l', 'linux-image-[0-9]*', 'linux-headers-[0-9]*', _env={'COLUMNS': '200'}) uname_output = uname('-r').strip() # like 4.4.0-79-generic kernel_version = uname_output.rsplit('-', 1)[0] print('kernel version:', kernel_version) removed_packages = filter_packages(dpkg_output, kernel_version) print('\n'.join(removed_packages))
def pipeline(*args): ''' pipeline defines main method for executing of tasks ''' print(sh.uname('-v')) for method in args: if not isinstance(method, Command): raise Exception('unable to validate method') method.run()
def get_distribution_codename(): codename = sh.uname().lower().strip() if codename == "linux": # lets try to be more specific using lsb_release try: output = sh.lsb_release("-c") # pylint: disable=E1101 _, codename = output.split("\t") except sh.CommandNotFound as e: pass codename = codename.strip() return codename
def os_properties(self): namespace = PropertyNamespace('os', _('Operating system')) if LSB: namespace.add_property('is_lsb', _('LSB OS'), True, True) namespace.add_property('distributor_id', _('Distributor ID'), lsb_release('-i', '-s'), True) namespace.add_property('description', _('Description'), lsb_release('-d', '-s'), True) namespace.add_property('release', _('Release'), lsb_release('-r', '-s'), True) namespace.add_property('codename', _('Codename'), lsb_release('-c', '-s'), True) namespace.add_property('sysinfo', _('System info'), uname('-a'), True) else: namespace.add_property('is_lsb', _('LSB OS'), False) namespace.add_property('architecture', _('OS architecture'), platform.architecture(), report=True) namespace.add_property('python_version', _('Python version'), platform.python_version(), report=True) namespace.add_property('hostname', _('Hostname'), platform.node()) namespace.add_property('platform', _('Platform'), sys.platform, report=True) namespace.add_property('machine', _('Machine'), platform.machine(), report=True) namespace.add_property('processor', _('Processor'), platform.processor(), report=True) namespace.add_property('cpus', _('Number of CPUs'), psutil.cpu_count(), report=True) namespace.add_property('total_phymem', _('Total physical memory'), pretty_size(psutil.virtual_memory().total), report=True) namespace.add_property( 'disk_partitions', _('Disk partitions'), '; '.join([ '%s %s %s %s' % (partition.device, partition.mountpoint, partition.fstype, partition.opts) for partition in psutil.disk_partitions() ]))
def cli(is_json): """ See the aeriscloud version information """ versions = { 'aeriscloud': {'version': ac_version}, 'ansible': {'version': ansible_version}, 'vagrant': {'version': vagrant_version()}, 'virtualbox': {'version': virtualbox_version()}, 'ruby': _ruby_version(), 'python': {'version': _python_version()}, 'git': {'version': str(sh.git('--version'))[12:].strip()} } # aeriscloud get information if os.path.exists(os.path.join(aeriscloud_path, '.git')): repo = Repo(aeriscloud_path) rev = str(repo.head.commit)[:8] branch = str(repo.active_branch) versions['aeriscloud']['revision'] = rev versions['aeriscloud']['branch'] = branch # operating system linux_version = _linux_version() if linux_version: versions['linux'] = linux_version else: try: # this is for osx sw_vers = dict([map(unicode.strip, line.split(':')) for line in sh.sw_vers()]) versions['osx'] = { 'name': sw_vers['ProductName'], 'version': sw_vers['ProductVersion'], 'build': sw_vers['BuildVersion'] } except sh.CommandNotFound: pass try: uname = str(sh.uname('-sr')).strip() versions['kernel'] = {'version': uname} except sh.CommandNotFound: pass if is_json: click.echo(json.dumps(versions)) else: click.echo(render_cli('version', **versions))
def build_sigar_python(target): target.pushd(os.path.join(target.dirname, target.buildpath)) target.pushd('bindings') target.pushd('python') tmpenv = os.environ.copy() if "Darwin" in sh.uname('-a'): tmpenv['CPPFLAGS'] = '-Qunused-arguments' tmpenv['CFLAGS'] = '-Qunused-arguments' try: tmpenv['LDFLAGS'] = '-L' + target.prefix + '/lib -L' + target.prefix + '/lib64' sh.python("setup.py", "--with-sigar="+target.prefix, "install", "--prefix="+target.prefix, _env=tmpenv) except sh.ErrorReturnCode,ex: print "Unable to build SIGAR python extensions: %s" % ex.stderr raise ex
def pybuild(self): if not self.do_build: return self.pushd(os.path.join(self.dirname, self.buildpath)) tmpenv = os.environ.copy() target = '.'.join(platform.python_version().split('.')[0:2]) # OS X workaround: prevent error on unrecognized arguments. if "Darwin" in sh.uname('-a'): tmpenv['CPPFLAGS'] = '-Qunused-arguments' tmpenv['CFLAGS'] = '-Qunused-arguments' # Set appropriate python path. tmpenv['PYTHONPATH'] = self.prefix + '/lib/python' + target + '/site-packages:' + \ self.prefix + '/lib64/python' + target + '/site-packages' try: sh.python("setup.py", "install", "--prefix=" + self.prefix, _env=tmpenv) except sh.ErrorReturnCode,ex: print "Unable to build: %s" % ex.stderr raise ex
def gather_sysctl(self): matcher = ExcludeInfoMatcher() if not matcher.enabled('sysctl'): return self.sysctl = dict() try: sysctl = sh.sysctl.bake(_cwd='.') except sh.CommandNotFound: sysctl = sh.Command('/sbin/sysctl').bake(_cwd='.') last = "" os_name = sh.uname().strip() for line in sysctl('-a', _iter=True): if os_name == "Linux": if " = " in line: res = line.split(" = ") self.sysctl[res[0].strip()] = res[1].strip() last = res[0] elif last != "": self.sysctl[last] += line.strip() elif os_name == "Darwin": if " = " in line: res = line.split(" = ") self.sysctl[res[0].strip()] = res[1].strip() last = res[0].strip() elif ": " in line: res = line.split(": ") self.sysctl[res[0].strip()] = res[1].strip() last = res[0].strip() elif last != "": self.sysctl[last] += line.strip() elif os_name == "FreeBSD": if ": " in line: res = line.split(": ") self.sysctl[res[0].strip()] = res[1].strip() last = res[0].strip() elif last != "": self.sysctl[last] += line.strip() # Post-process: filter gathered data based on rules defined in gather.conf for entry in self.sysctl.keys(): if not matcher.match(entry, self.sysctl[entry], 'sysctl'): del self.sysctl[entry]
def gather_modules(self): matcher = ExcludeInfoMatcher() if not matcher.enabled('modules'): return if(sh.uname().strip() != "Linux"): return self.modules = [] lsmod = sh.Command('/sbin/lsmod') skipped = False for line in lsmod(_iter=True): if not skipped: skipped = True continue self.modules.append(line.split(' ')[0]) # Post-process: filter gathered data based on rules defined in gather.conf for entry in self.modules: if not matcher.match(entry, entry, 'modules'): del self.modules[entry]
def main(argv): opts, args = getopt.getopt(argv,"ht:v:",["type=","version="]) kernel_type = 'stable' for opt, arg in opts: if opt == '-h': print 'kerenelcompile.py -type <stable|mainline|lts> -v <version>' sys.exit() elif opt in ("-t", "--type"): kernel_type = arg elif opt in ("-v", "--version"): version = arg call("apt-get install git-core kernel-package fakeroot build-essential libncurses5-dev python-pip wget xz-utils",shell=True) call("pip install feedparser sh",shell=True) from functions.functions import * from sh import cp,make,uname BUILD_DIR="/usr/src" testing='' if kernel_type == 'mainline': kernel_version=GetReleaseCandidateVersion() rc = kernel_version.find('-rc') if rc>0: testing = '/testing' else: kernel_version=GetStableVersion() cpuCount=getCpuCount() print("cpu count:%s\n" % cpuCount) print("compiling kernel %s\n" % kernel_version) chdir(BUILD_DIR) call("wget --continue http://kernel.org/pub/linux/kernel/v3.x%s/linux-%s.tar.xz" % (testing,kernel_version),shell=True) call("tar -Jxf linux-%s.tar.xz" % kernel_version,shell=True) chdir("linux-%s" % kernel_version) current_kernel=uname("-r").rstrip('\n') cp("/boot/config-%s"%current_kernel,"./.config") call("make nconfig",shell=True) call("make-kpkg clean",shell=True) new_env = os.environ.copy() os.environ["CONCURENCY_LEVEL"] = "%s"% cpuCount call("fakeroot make-kpkg -j3 --initrd --append-to-version=-xtreme-reload kernel_image kernel_headers" ,shell=True) call("make clean",shell=True) Install(kernel_version)
def os_properties(self): namespace = PropertyNamespace('os', _('Operating system')) if LSB: namespace.add_property('is_lsb', _('LSB OS'), True, True) namespace.add_property('distributor_id', _('Distributor ID'), lsb_release('-i', '-s'), True) namespace.add_property('description', _('Description'), lsb_release('-d', '-s'), True) namespace.add_property('release', _('Release'), lsb_release('-r', '-s'), True) namespace.add_property('codename', _('Codename'), lsb_release('-c', '-s'), True) namespace.add_property('sysinfo', _('System info'), uname('-a'), True) else: namespace.add_property('is_lsb', _('LSB OS'), False) namespace.add_property('architecture', _('OS architecture'), platform.architecture(), report=True) namespace.add_property('python_version', _('Python version'), platform.python_version(), report=True) namespace.add_property('hostname', _('Hostname'), platform.node()) namespace.add_property('platform', _('Platform'), sys.platform, report=True) namespace.add_property('machine', _('Machine'), platform.machine(), report=True) namespace.add_property('processor', _('Processor'), platform.processor(), report=True) namespace.add_property('cpus', _('Number of CPUs'), psutil.cpu_count(), report=True) namespace.add_property('total_phymem', _('Total physical memory'), pretty_size(psutil.virtual_memory().total), report=True) namespace.add_property('disk_partitions', _('Disk partitions'), '; '.join(['%s %s %s %s' % (partition.device, partition.mountpoint, partition.fstype, partition.opts) for partition in psutil.disk_partitions()]))
from sh import uname, dpkg # Current kernel version. You could also get this information by reading from the file # /proc/sys/kernel/osrelease uname_output = uname('-r').strip() # like 4.4.0-79-generic kernel_version = uname_output.rsplit('-', 1)[0] print('kernel version:', kernel_version) packages_output = dpkg('-l', 'linux-image-[0-9]*', 'linux-headers-[0-9]*', _env={'COLUMNS': '200'}) packages_list = packages_output.strip().splitlines() installed_lines = filter(lambda line: line.startswith('ii'), packages_list) package_names = [line.split()[1] for line in installed_lines] remove_packages = filter(lambda package: kernel_version not in package, package_names) print('\n'.join(remove_packages))
from sh import uname, sed, dpkg, awk, grep # Get our current kernel version # $(uname -r | sed -r 's/-[a-z]+//') kernel_version = sed(uname('-r'), '-r', 's/-[a-z]+//').strip() print('kernel version:', kernel_version) # get & filter package list packages = \ grep( awk( dpkg('-l', 'linux-image-[0-9]*', 'linux-headers-[0-9]*', _env={'COLUMNS': '200'}), '/ii/{print $2}' ), '-ve', kernel_version ) print(packages.strip())
print('-' * 50) from sh import ls, glob print(ls('-ld', glob('/etc/pr*'))) print('-' * 50) w = sh.who() print(w) print('-' * 50) disk_usage = sh.df('-h') print(disk_usage) print('-' * 50) from sh import uname print(uname()) print(uname('-a')) print(uname(a=True)) print('-' * 50) from sh import grep, wc # grep 'sh' /etc/passwd | wc -l print(grep('sh', '/etc/passwd')) print(wc(grep('sh', '/etc/passwd'), l=True)) print('-' * 50) from sh import tr fruits = 'apple banana mango orange'.split() print(tr("[:lower:]", "[:upper:]", _in=fruits))
db.session.commit() except Exception, e: db.session.rollback() for obj in app_globals.ip_data: try: connect = libvirt.open("remote+ssh://" + obj + "/system") except Exception, e: print "SSH Daemon either not running or the port is not open" raise e if not PhysicalMachines.query.filter_by( username=obj.split('@')[0], ip_addr=obj.split('@')[1]).all(): try: if str(uname('-m')).rsplit()[0] == 'x86_64': hardware = 64 else: hardware = 32 os.system("ssh " + obj + " nproc > proc.txt") with open("proc.txt") as data_file: vcpu = int( str(data_file.read().splitlines()[0]).split()[0]) os.system("ssh " + obj + " 'free -m | head -n2 | tail -n1' > proc.txt") with open("proc.txt") as data_file: ram = int(str(data_file.read().splitlines()[0].split()[1]))
def menu(): global status_summary global instances_cache global key_cache global table global servers page_start() rows = 5 table_start('CM - Cloud Mesh', rows) bar = Bar('Processing', max=10) bar.next() _refresh_servers() bar.next() _get_keynames() bar.next() table_two_col_row(['Last Refresh', '%s' % str(datetime.now())], rows) table_two_col_row(['Keynames', '%s' % ','.join(key_cache)], rows) table_two_col_row(['Thread pool size', '%s' % maxparallel], rows) table_two_col_row(['Image', '%s' % image_name], rows) bar.next() _status() bar.next() table_two_col_row(['Summary', '%s' % str(status_summary)], rows) bar.next() table_header('%s Virtual Machines' % len(servers), 5) cloudname = 'india' if DISPLAY_HTML: table += \ '<tr><td><b><i>Cloud</i></b></td><td><b><i>ID</i></b></td><td><b><i>Name</i></b></td><td><b><i>Status</i></b></td><td><b><i>IPs</i></b></td><tr>\n' for index in servers: server = servers[index] table += \ '<tr><td>%(cloud)s</td><td>%(id)s</td><td>%(name)s</td><td>%(status)s</td><td>%(ip)s</td></tr>\n' \ % server else: tab = PrettyTable(['Cloud', 'ID', 'Name', 'Status', 'IPs']) if len(servers) == 0: None else: for index in servers: server = servers[index] tab.add_row([ '%(cloud)s' % server, '%(id)s' % server, '%(name)s' % server, '%(status)s' % server, '%(ip)s' % server ]) table += tab.get_string() table = table.replace( 'ACTIVE', '%s%s%s' % (term.green, 'ACTIVE', term.black)) table = table.replace('ERROR', '%s%s%s' % (term.red, 'ERROR', term.black)) table = table.replace('BUILD', '%s%s%s' % (term.blue, 'BUILD', term.black)) table += '\n' bar.next() commands = \ """ <b><i>STARTING:</i></b> start:i - reindex - par:n - fix <b><i>TESTING:</i></b> test:i <b><i>DELETING:</i></b> delete:i - clean - kill - killwait <b><i>STATUS:</i></b> status - ls - list - flavor - created - limits - rc""" if not DISPLAY_HTML: commands = commands.replace('<b>', term.bold) commands = commands.replace('</b>', term.normal) commands = commands.replace('<i>', term.italic) commands = commands.replace('</i>', term.normal) # commands = commands.replace("\n","") bar.next() table_header('Help', 4) if DISPLAY_HTML: table_two_col_row(['Commands', '%s' % commands], rows) else: table_row(['%s' % commands]) table_end() page_end() bar.next() try: os.mkdir('/tmp/%s' % prefix) except: None bar.next() # DISPLAY THE PAGE if DISPLAY_HTML: filename = '/tmp/%s/cm.html' % prefix f = open(filename, 'w+') print >> f, table f.close() if uname().strip() == 'Darwin': os.system( 'osascript -e \'tell application "Safari" to open location "file://%s"\'' % filename) else: print 'OS not yet tested' os.system('firefox file://%s' % filename) else: os.system('clear') print table bar.next() bar.finish() if env.debug: print servers
#!/usr/bin/python from sh import uname print(uname('-n'))
except Exception, e: db.session.rollback() for obj in app_globals.ip_data: try: connect = libvirt.open("remote+ssh://" + obj + "/system") except Exception, e: print "SSH Daemon either not running or the port is not open" raise e if not PhysicalMachines.query.filter_by( username=obj.split('@')[0], ip_addr=obj.split('@')[1]).all(): try: if str(uname('-m')).rsplit()[0]=='x86_64': hardware=64 else: hardware=32 os.system("ssh " + obj + " nproc > proc.txt") with open("proc.txt") as data_file: vcpu = int(str(data_file.read().splitlines()[0]).split()[0]) os.system("ssh " + obj + " 'free -m | head -n2 | tail -n1' > proc.txt") with open("proc.txt") as data_file: ram = int(str(data_file.read().splitlines()[0].split()[1])) os.system("ssh " + obj + " 'df -h' > proc.txt") with open("proc.txt") as data_file:
def sysInfo(self): mLoad = re.sub(".*averages: ", "", sh.uptime().strip()).split(" ")[0] mVersion = sh.uname("-r").strip() return mVersion + " <" + mLoad + ">"
def main(): os_type = sh.uname().strip() for p in OP_PACKAGE[os_type]: for info in install_package(p, os_type): sys.stdout.flush() print info
except IndexError: yield image_line yield Style.RESET_ALL if __name__ == '__main__': # This is an example configuration that can be modified or used as-is. The # commands are called through the sh module (amoffat.github.io/sh). # 'fortune' messages - only short ones though - fortune = sh.fortune('-s') # 'uname' output, including kernel name (-s), hostname (-n) and kernel # version (-r) uname = sh.uname('-snr').rstrip() # number of pacman updates available, counted through the 'checkupdates' # script included with pacman. Note: # a) This (obviously) only works in distros using pacman and # b) The checkupdates script is kinda slow (3-6 seconds in my experience), # so, if the script takes a long time to run, try disabling this part. repo_update_count = sh.wc(sh.checkupdates(), '-l').rstrip() # The path the ASCII image. image_path = '~/.motd_image' # The color in which the image will be printed. This can be any string, but # you will probably want to pass either one of the constants in # colorama.Fore, such as Fore.RED, or a color format string such as # '\033[92m' (for red). image_color = Fore.BLUE
def menu(): global status_summary global instances_cache global key_cache global table global servers page_start() rows = 5 table_start('CM - Cloud Mesh', rows) bar = Bar('Processing', max=10) bar.next() _refresh_servers() bar.next() _get_keynames() bar.next() table_two_col_row(['Last Refresh', '%s' % str(datetime.now())], rows) table_two_col_row(['Keynames', '%s' % ','.join(key_cache)], rows) table_two_col_row(['Thread pool size', '%s' % maxparallel], rows) table_two_col_row(['Image', '%s' % image_name], rows) bar.next() _status() bar.next() table_two_col_row(['Summary', '%s' % str(status_summary)], rows) bar.next() table_header('%s Virtual Machines' % len(servers), 5) cloudname = 'india' if DISPLAY_HTML: table += \ '<tr><td><b><i>Cloud</i></b></td><td><b><i>ID</i></b></td><td><b><i>Name</i></b></td><td><b><i>Status</i></b></td><td><b><i>IPs</i></b></td><tr>\n' for index in servers: server = servers[index] table += \ '<tr><td>%(cloud)s</td><td>%(id)s</td><td>%(name)s</td><td>%(status)s</td><td>%(ip)s</td></tr>\n' \ % server else: tab = PrettyTable(['Cloud', 'ID', 'Name', 'Status', 'IPs']) if len(servers) == 0: None else: for index in servers: server = servers[index] tab.add_row(['%(cloud)s' % server, '%(id)s' % server, '%(name)s' % server, '%(status)s' % server, '%(ip)s' % server]) table += tab.get_string() table = table.replace('ACTIVE', '%s%s%s' % (term.green, 'ACTIVE', term.black)) table = table.replace('ERROR', '%s%s%s' % (term.red, 'ERROR', term.black)) table = table.replace('BUILD', '%s%s%s' % (term.blue, 'BUILD', term.black)) table += '\n' bar.next() commands = \ """ <b><i>STARTING:</i></b> start:i - reindex - par:n - fix <b><i>TESTING:</i></b> test:i <b><i>DELETING:</i></b> delete:i - clean - kill - killwait <b><i>STATUS:</i></b> status - ls - list - flavor - created - limits - rc""" if not DISPLAY_HTML: commands = commands.replace('<b>', term.bold) commands = commands.replace('</b>', term.normal) commands = commands.replace('<i>', term.italic) commands = commands.replace('</i>', term.normal) # commands = commands.replace("\n","") bar.next() table_header('Help', 4) if DISPLAY_HTML: table_two_col_row(['Commands', '%s' % commands], rows) else: table_row(['%s' % commands]) table_end() page_end() bar.next() try: os.mkdir('/tmp/%s' % prefix) except: None bar.next() # DISPLAY THE PAGE if DISPLAY_HTML: filename = '/tmp/%s/cm.html' % prefix f = open(filename, 'w+') print >> f, table f.close() if uname().strip() == 'Darwin': os.system('osascript -e \'tell application "Safari" to open location "file://%s"\'' % filename) else: print 'OS not yet tested' os.system('firefox file://%s' % filename) else: os.system('clear') print table bar.next() bar.finish() if env.debug: print servers
def main(argv): opts, args = getopt.getopt(argv, "ht:v:b:", ["help", "type=", "version=", "build_method="]) kernel_type = 'stable' build_method = 'debian' kernel_version = None for opt, arg in opts: if opt in ("-h", "--help"): print 'kernelcompile.py [-type <stable|mainline|longterm>] [-v <version>] [-b <normal|debian>]' sys.exit() elif opt in ("-t", "--type"): isValidKernelType = validate_kernel_type(arg) if (isValidKernelType == True): kernel_type = arg else: print("Invalid or No Kernel type entered") print( "Valid options for the 'type' argument are : 'stable' or 'mainline' or 'longterm'\n" ) sys.exit() elif opt in ("-v", "--version"): kernel_version = arg elif opt in ("-b", "--build_method"): isValidBuildMethod = validate_build_method(arg) if (isValidBuildMethod == True): build_method = arg else: print("Invalid build_method entered") print( "Valid options for the 'build_method' argument are : 'debian' or 'normal'\n" ) sys.exit() call( "apt-get install git-core kernel-package fakeroot build-essential libncurses5-dev python-pip wget xz-utils", shell=True) call("pip install feedparser sh", shell=True) from sh import cp, make, uname BUILD_DIR = "/usr/src" testing = '' if kernel_type == 'mainline': if kernel_version == None: # no version was suplied as arg kernel_version = GetReleaseCandidateVersion() rc = kernel_version.find('-rc') if rc > 0: testing = '/testing' else: if kernel_version == None: kernel_version = GetStableVersion() cpuCount = getCpuCount() print("cpu count:%s\n" % cpuCount) print("compiling kernel %s\n" % kernel_version) chdir(BUILD_DIR) call( "wget --continue http://kernel.org/pub/linux/kernel/v4.x%s/linux-%s.tar.xz" % (testing, kernel_version), shell=True) call("tar -Jxf linux-%s.tar.xz" % kernel_version, shell=True) chdir("linux-%s" % kernel_version) current_kernel = uname("-r").rstrip('\n') print("current kernel version is : %s\n" % current_kernel) # Start by cleaning up call("make distclean; make mrproper", shell=True) cp("/boot/config-%s" % current_kernel, "./.config") call("make nconfig", shell=True) if (build_method == 'debian'): print("Building by the Debian method") call("make-kpkg clean", shell=True) new_env = os.environ.copy() os.environ["CONCURENCY_LEVEL"] = "%s" % cpuCount call( "fakeroot make-kpkg --initrd --append-to-version=-vanillaice kernel_image kernel_headers", shell=True) call("make clean", shell=True) Install(kernel_version) else: print("Building by the Normal method") # The below commands can be merged into one call("make", shell=True) call("make modules_install", shell=True) call("make install", shell=True) print("Done installing the Kernel\n")
def ui_command_uname(self): """ Displays the system uname information.. """ print sh.uname('-a')
def main(argv): opts, args = getopt.getopt(argv,"ht:v:b:",["help","type=","version=","build_method="]) kernel_type = 'stable' build_method = 'debian' kernel_version = None for opt, arg in opts: if opt in ("-h", "--help"): print 'kernelcompile.py [-type <stable|mainline|longterm>] [-v <version>] [-b <normal|debian>]' sys.exit() elif opt in ("-t", "--type"): isValidKernelType = validate_kernel_type(arg) if(isValidKernelType == True): kernel_type = arg else: print("Invalid or No Kernel type entered") print("Valid options for the 'type' argument are : 'stable' or 'mainline' or 'longterm'\n") sys.exit() elif opt in ("-v", "--version"): kernel_version = arg elif opt in ("-b", "--build_method"): isValidBuildMethod = validate_build_method(arg) if(isValidBuildMethod == True): build_method = arg else: print("Invalid build_method entered") print("Valid options for the 'build_method' argument are : 'debian' or 'normal'\n") sys.exit() call("apt-get install git-core kernel-package fakeroot build-essential libncurses5-dev python-pip wget xz-utils",shell=True) call("pip install feedparser sh",shell=True) from sh import cp,make,uname BUILD_DIR="/usr/src" testing='' if kernel_type == 'mainline': if kernel_version == None: # no version was suplied as arg kernel_version=GetReleaseCandidateVersion() rc = kernel_version.find('-rc') if rc>0: testing = '/testing' else: if kernel_version == None: kernel_version=GetStableVersion() cpuCount=getCpuCount() print("cpu count:%s\n" % cpuCount) print("compiling kernel %s\n" % kernel_version) chdir(BUILD_DIR) call("wget --continue http://kernel.org/pub/linux/kernel/v3.x%s/linux-%s.tar.xz" % (testing,kernel_version),shell=True) call("tar -Jxf linux-%s.tar.xz" % kernel_version,shell=True) chdir("linux-%s" % kernel_version) current_kernel=uname("-r").rstrip('\n') print("current kernel version is : %s\n" % current_kernel) # Start by cleaning up call("make distclean; make mrproper", shell=True) cp("/boot/config-%s"%current_kernel,"./.config") call("make nconfig",shell=True) if(build_method == 'debian'): print("Building by the Debian method") call("make-kpkg clean",shell=True) new_env = os.environ.copy() os.environ["CONCURENCY_LEVEL"] = "%s"% cpuCount call("fakeroot make-kpkg --initrd --append-to-version=-vanillaice kernel_image kernel_headers" ,shell=True) call("make clean",shell=True) Install(kernel_version) else: print("Building by the Normal method") # The below commands can be merged into one call("make", shell=True) call("make modules_install", shell=True) call("make install", shell=True) print("Done installing the Kernel\n")