def validate_platform(self):
"""Validates the platform and distribution to make sure it is supported.
Raises:
NotImplementedError: Unsupported System/OS.
"""
system = platform.system()
if system != 'Linux':
self.log.error('Unsupported System/OS: {0}'.format(system))
raise NotImplementedError
self.dist = platform.dist()[0]
if self.dist == 'Ubuntu':
self.log.debug('Distribution: Ubuntu')
elif self.dist == 'centos':
self.log.debug('Distribution: centos')
else:
self.log.error('Unsupported Distribution: {0}'.format(self.dist))
raise NotImplementedError
python类dist()的实例源码
def getos():
dagitim=platform.dist()
dagitim=dagitim[0]
mimari=platform.machine()
osys=platform.system()
unumber = os.getuid()
zaman=time.ctime()
if unumber==0:
kulanici="root"
else:
kulanici="No root"
bilgi="""
============================
CPU: {}
OS: {}
DAGITIM: {}
KULANICI: {}
ZAMAN: {}
============================""".format(mimari,osys,dagitim,kulanici,zaman)
print(bilgi)
def get_distribution():
''' return the distribution name '''
if platform.system() == 'Linux':
try:
supported_dists = platform._supported_dists + ('arch','alpine')
distribution = platform.linux_distribution(supported_dists=supported_dists)[0].capitalize()
if not distribution and os.path.isfile('/etc/system-release'):
distribution = platform.linux_distribution(supported_dists=['system'])[0].capitalize()
if 'Amazon' in distribution:
distribution = 'Amazon'
else:
distribution = 'OtherLinux'
except:
# FIXME: MethodMissing, I assume?
distribution = platform.dist()[0].capitalize()
else:
distribution = None
return distribution
def system_info():
import constructor, sys, platform
import conda.exports, conda.config
out = {'constructor': constructor.__version__,
'conda': conda.__version__,
'platform': sys.platform,
'python': sys.version,
'python_version': tuple(sys.version_info),
'machine': platform.machine(),
'platform_full': platform.version()}
if sys.platform == 'darwin':
out['extra'] = platform.mac_ver()
elif sys.platform.startswith('linux'):
out['extra'] = platform.dist()
elif sys.platform.startswith('win'):
out['extra'] = platform.win32_ver()
prefix = os.environ.get('CONDA_PREFIX', conda.config.default_prefix)
prefix_records = conda.exports.linked_data(prefix).values()
nsis_prefix_rec = next(
(rec for rec in prefix_records if rec.name == 'nsis'), None)
if nsis_prefix_rec:
out['nsis'] = nsis_prefix_rec.version
return out
def nmap(self):
"""
"""
print("[+] Checking if Nmap exist in the current OS ... ")
status = system("which nmap")
if status == '0':
print("[-] Nmap exist!")
else:
print("[-] Nmap didn't exist ...")
print("[+] Downloading Nmap to {0} ...".format(self.DIRECTORY))
system("cd src/bin/ && wget https://nmap.org/dist/nmap-7.01.tar.bz2")
system("cd src/bin/ && tar xjf nmap-7.01.tar.bz2")
system("cd src/bin/nmap-7.01/ && ./configure && make && make install")
print("[+] Cleaning ...")
system("rm -r src/bin/nmap-7.01 && rm src/bin/nmap-7.01.tar.bz2")
print("[-] Done.")
def enforce_selinux_context(output_directory):
if platform.dist()[0] in ['fedora', 'centos', 'redhat']:
if os.path.exists('/sbin/semanage'):
FNULL = open(os.devnull, 'w')
# Set new selinux so it is persistent over reboot
command = 'semanage fcontext -a -t cert_t %s(/.*?)' % (
output_directory
)
p = subprocess.Popen(command.split(), stdout=FNULL,
stderr=subprocess.STDOUT)
p.wait()
# Ensure file have the right context applied
command = 'restorecon -Rv %s' % output_directory
p = subprocess.Popen(command.split(), stdout=FNULL,
stderr=subprocess.STDOUT)
p.wait()
def parse_distribution_file_Coreos(self, name, data, path, collected_facts):
coreos_facts = {}
# FIXME: pass in ro copy of facts for this kind of thing
dist = platform.dist()
distro = dist[0]
if distro.lower() == 'coreos':
if not data:
# include fix from #15230, #15228
# TODO: verify this is ok for above bugs
return False, coreos_facts
release = re.search("^GROUP=(.*)", data)
if release:
coreos_facts['distribution_release'] = release.group(1).strip('"')
else:
return False, coreos_facts # TODO: remove if tested without this
return True, coreos_facts
def dump_info():
"""Dumps some info regarding the environment we are running in.
The intended use is to ask the user to paste this info for
troubleshooting steps.
"""
print("Python version: {}".format(platform.python_version()))
print("\n ")
print("System's release version: {}".format(platform.version()))
print("\n ")
print("Platform: {}".format(platform.platform()))
print("\n ")
print("OS environment: {}".format(platform.os.environ))
print("\n ")
print("Platform architecture: {}".format(platform.architecture()))
print("\n ")
print("Linux distrubition name: {}".format(platform.dist()))
print("\n ")
print("System/OS name: {}".format(platform.system()))
def _get_ubuntu_version():
"""
Gets the "major" Ubuntu version.
If an unsupported OS/Ubuntu version is found a warning is printed and
``None`` is returned.
"""
import platform
distname, version, _ = platform.dist()
if distname.lower() != 'ubuntu':
logger.warning('You are running on a non-Ubuntu system. Skipping S2E '
'dependencies - please install them manually')
return None
major_version = int(version.split('.')[0])
if major_version not in CONSTANTS['required_versions']['ubuntu_major_ver']:
logger.warning('You are running an unsupported version of Ubuntu. '
'Skipping S2E dependencies - please install them '
'manually')
return None
return major_version
def get_canonical_os_name():
"""
Return a standardized, lower case version of the name of the OS. This is
useful to avoid the ambiguity of OS marketing names.
"""
psl = platform.system().lower()
if psl in ['sunos', 'darwin', 'windows', 'aix']:
return psl
if psl == 'linux':
# add distro information for Linux
return 'linux_{0}'.format(platform.dist()[0])
# Workaround for python bug 1082, on Vista, platform.system()
# returns 'Microsoft'
prl = platform.release().lower()
if psl == 'microsoft' or prl == 'vista' or prl == 'windows':
return 'windows'
return 'unknown'
def show_platform():
''' Show information on platform'''
swrite('\n=== SYSTEM ===\n\n')
try:
linux_distribution = platform.linux_distribution()
except:
linux_distribution = "N/A"
swrite("""
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
memory: %s
number of CPU: %s
""" % (
str(platform.dist()),
linux_distribution,
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
psutil.virtual_memory(),
str(psutil.cpu_count())
))
def compute_all_scores(solution, prediction):
''' Compute all the scores and return them as a dist'''
missing_score = -0.999999
scoring = {'BAC (multilabel)':nbac_binary_score,
'BAC (multiclass)':nbac_multiclass_score,
'F1 (multilabel)':f1_binary_score,
'F1 (multiclass)':f1_multiclass_score,
'Regression ABS ':a_metric,
'Regression R2 ':r2_metric,
'AUC (multilabel)':auc_metric,
'PAC (multilabel)':npac_binary_score,
'PAC (multiclass)':npac_multiclass_score}
# Normalize/sanitize inputs
[csolution, cprediction] = normalize_array (solution, prediction)
solution = sanitize_array (solution); prediction = sanitize_array (prediction)
# Compute all scores
score_names = sorted(scoring.keys())
scores = {}
for key in score_names:
scoring_func = scoring[key]
try:
if key=='Regression R2 ' or key=='Regression ABS ':
scores[key] = scoring_func(solution, prediction)
else:
scores[key] = scoring_func(csolution, cprediction)
except:
scores[key] = missing_score
return scores
def get_distro_id_base():
"""
Wrapper around platform.dist to simulate distro.id
platform.dist is deprecated and will be removed in python 3.7
Use the 'distro' package instead.
"""
# pylint: disable=deprecated-method
return platform.dist()[0]
def run(self):
if not self.distribution.dist_files:
raise DistutilsOptionError("No dist file created in earlier command")
for command, pyversion, filename in self.distribution.dist_files:
self.upload_file(command, pyversion, filename)
def run(self):
if not self.distribution.dist_files:
raise DistutilsOptionError("No dist file created in earlier command")
for command, pyversion, filename in self.distribution.dist_files:
self.upload_file(command, pyversion, filename)
def show_platform():
''' Show information on platform'''
swrite('\n=== SYSTEM ===\n\n')
try:
linux_distribution = platform.linux_distribution()
except:
linux_distribution = "N/A"
swrite("""
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
memory: %s
number of CPU: %s
""" % (
str(platform.dist()),
linux_distribution,
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
psutil.virtual_memory(),
str(psutil.cpu_count())
))
def compute_all_scores(solution, prediction):
''' Compute all the scores and return them as a dist'''
missing_score = -0.999999
scoring = {'BAC (multilabel)':nbac_binary_score,
'BAC (multiclass)':nbac_multiclass_score,
'F1 (multilabel)':f1_binary_score,
'F1 (multiclass)':f1_multiclass_score,
'Regression ABS ':a_metric,
'Regression R2 ':r2_metric,
'AUC (multilabel)':auc_metric,
'PAC (multilabel)':npac_binary_score,
'PAC (multiclass)':npac_multiclass_score}
# Normalize/sanitize inputs
[csolution, cprediction] = normalize_array (solution, prediction)
solution = sanitize_array (solution); prediction = sanitize_array (prediction)
# Compute all scores
score_names = sorted(scoring.keys())
scores = {}
for key in score_names:
scoring_func = scoring[key]
try:
if key=='Regression R2 ' or key=='Regression ABS ':
scores[key] = scoring_func(solution, prediction)
else:
scores[key] = scoring_func(csolution, cprediction)
except:
scores[key] = missing_score
return scores
def install_requirements(self):
"""Install Ubuntu Requirements"""
print('Installing Requirements')
if platform.dist()[0] in ['Ubuntu', 'LinuxMint']:
command = 'sudo apt-get install apache2 bcftools build-essential cpanminus curl git libbz2-dev libcurl4-openssl-dev liblocal-lib-perl liblzma-dev libmysqlclient-dev libpng12-dev libpq-dev libssl-dev manpages mysql-client openssl perl perl-base pkg-config python3-dev python3-pip python3-setuptools sed tabix unzip vcftools vim wget zlib1g-dev' # lamp-server^
sts = call(command, shell=True)
try:
subprocess.call(['java', '-version'])
except:
command = """sudo apt install software-properties-common
sudo add-apt-repository -y ppa:webupd8team/java
sudo apt-get update
echo "oracle-java8-installer shared/accepted-oracle-license-v1-1 select true" | sudo debconf-set-selections
sudo apt-get -y install oracle-java8-installer"""
sts = call(command, shell=True)
elif platform.dist()[0] in ['redhat', 'centos']:
command = 'sudo yum install libcurl-devel sed vcftools bcftools tabix zlib-devel postgresql96-libs perl-local-lib perl-App-cpanminus curl unzip wget'
sts = call(command, shell=True)
command = """sudo yum groupinstall 'Development Tools'"""
sts = call(command, shell=True)
command = """sudo yum install gcc gcc-c++ make openssl-devel"""
sts = call(command, shell=True)
try:
subprocess.call(['java', '-version'])
except:
command = """wget http://javadl.oracle.com/webapps/download/AutoDL?BundleId=225342_090f390dda5b47b9b721c7dfaa008135 -o java.rpm"""
sts = call(command, shell=True)
command = """sudo rpm -i java.rpm"""
sts = call(command, shell=True)
# Perl Requirements
command = "sudo cpanm DBI DBD::mysql File::Copy::Recursive Archive::Extract Archive::Zip LWP::Simple Bio::Root::Version LWP::Protocol::https Bio::DB::Fasta CGI"
sts = call(command, shell=True)
def show_platform():
''' Show information on platform'''
swrite('\n=== SYSTEM ===\n\n')
try:
linux_distribution = platform.linux_distribution()
except:
linux_distribution = "N/A"
swrite("""
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
memory: %s
number of CPU: %s
""" % (
str(platform.dist()),
linux_distribution,
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
psutil.virtual_memory(),
str(psutil.cpu_count())
))
def compute_all_scores(solution, prediction):
''' Compute all the scores and return them as a dist'''
missing_score = -0.999999
scoring = {'BAC (multilabel)':nbac_binary_score,
'BAC (multiclass)':nbac_multiclass_score,
'F1 (multilabel)':f1_binary_score,
'F1 (multiclass)':f1_multiclass_score,
'Regression ABS ':a_metric,
'Regression R2 ':r2_metric,
'AUC (multilabel)':auc_metric,
'PAC (multilabel)':npac_binary_score,
'PAC (multiclass)':npac_multiclass_score}
# Normalize/sanitize inputs
[csolution, cprediction] = normalize_array (solution, prediction)
solution = sanitize_array (solution); prediction = sanitize_array (prediction)
# Compute all scores
score_names = sorted(scoring.keys())
scores = {}
for key in score_names:
scoring_func = scoring[key]
try:
if key=='Regression R2 ' or key=='Regression ABS ':
scores[key] = scoring_func(solution, prediction)
else:
scores[key] = scoring_func(csolution, cprediction)
except:
scores[key] = missing_score
return scores
def getset_packagerepo_commands(self):
"""Gets and sets the system package and repo list commands.
Raises:
NotImplementedError: Unsupported Distribution.
"""
if self.dist == 'Ubuntu':
self.package_command = '/usr/bin/apt list --installed'
self.repo_command = '/bin/cat /etc/apt/sources.list | sed -e "/^#/d" -e "/^$/d"'
elif self.dist == 'centos':
self.package_command = '/usr/bin/yum list installed'
self.repo_command = '/usr/bin/yum -v repolist'
def distro(self):
try:
values = platform.linux_distribution()
except AttributeError:
values = platform.dist()
if len(values) != 0:
return "%s %s %s" % (values[0], values[1], values[2])
else:
return self.readfile('/etc/issue').strip()
def getos():
global bilgi
raw_ip=os.popen('hostname -I').read().split('\n')
proc=platform.processor()
l_ip=raw_ip[0]
dagitim=platform.dist()
dagitim=dagitim[0]
mimari=platform.machine()
osys=platform.system()
unumber = os.getuid()
zaman=time.ctime()
if unumber==0:
kulanici="root"
else:
kulanici="No root"
bilgi="""
============================
CPU: {}
OS: {}
DAGITIM: {}
KULANICI: {}
LOCAL IP: {}
ASISTAN KULANICI ADI: {}
ZAMAN: {}
============================""".format(mimari,osys,dagitim,kulanici,l_ip,shell.user.isim,zaman)
def do_os(self, s):
"""Displays information about your operating system."""
print_say('[!] Operating System Information', self, Fore.BLUE)
print_say('[*] ' + sys(), self, Fore.GREEN)
print_say('[*] ' + release(), self, Fore.GREEN)
print_say('[*] ' + dist()[0], self, Fore.GREEN)
for _ in architecture():
print_say('[*] ' + _, self, Fore.GREEN)
def import_ubuntu_system_ca(common_name, certfile):
import platform
platform_distname = platform.dist()[0]
if platform_distname != 'Ubuntu':
return
pemfile = "/etc/ssl/certs/CA.pem"
new_certfile = "/usr/local/share/ca-certificates/CA.crt"
if not os.path.exists(pemfile) or not CertUtil.file_is_same(certfile, new_certfile):
if os.system('cp "%s" "%s" && update-ca-certificates' % (certfile, new_certfile)) != 0:
logging.warning('install root certificate failed, Please run as administrator/root/sudo')
def import_ubuntu_system_ca(common_name, certfile):
import platform
platform_distname = platform.dist()[0]
if platform_distname != 'Ubuntu':
return
pemfile = "/etc/ssl/certs/CA.pem"
new_certfile = "/usr/local/share/ca-certificates/CA.crt"
if not os.path.exists(pemfile) or not CertUtil.file_is_same(certfile, new_certfile):
if os.system('cp "%s" "%s" && update-ca-certificates' % (certfile, new_certfile)) != 0:
xlog.warning('install root certificate failed, Please run as administrator/root/sudo')
def __init__(self):
logo_filename = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'web_ui', 'favicon.ico')
if platform and appindicator and platform.dist()[0].lower() == 'ubuntu':
self.trayicon = self.ubuntu_trayicon(logo_filename)
else:
self.trayicon = self.gtk_trayicon(logo_filename)
def import_ubuntu_system_ca(common_name, certfile):
import platform
platform_distname = platform.dist()[0]
if platform_distname != 'Ubuntu':
return
pemfile = "/etc/ssl/certs/CA.pem"
new_certfile = "/usr/local/share/ca-certificates/CA.crt"
if not os.path.exists(pemfile) or not CertUtil.file_is_same(certfile, new_certfile):
if os.system('cp "%s" "%s" && update-ca-certificates' % (certfile, new_certfile)) != 0:
xlog.warning('install root certificate failed, Please run as administrator/root/sudo')
def __init__(self):
logo_filename = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'web_ui', 'favicon.ico')
if platform and appindicator and platform.dist()[0].lower() == 'ubuntu':
self.trayicon = self.ubuntu_trayicon(logo_filename)
else:
self.trayicon = self.gtk_trayicon(logo_filename)
def version(self):
# Be aware! Deprecated in Python 2.6!
result = platform.dist()[1]
return result