def tell_system_status(self):
import psutil
import platform
import datetime
os, name, version, _, _, _ = platform.uname()
version = version.split('-')[0]
cores = psutil.cpu_count()
cpu_percent = psutil.cpu_percent()
memory_percent = psutil.virtual_memory()[2]
disk_percent = psutil.disk_usage('/')[3]
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
running_since = boot_time.strftime("%A %d. %B %Y")
response = "I am currently running on %s version %s. " % (os, version)
response += "This system is named %s and has %s CPU cores. " % (name, cores)
response += "Current disk_percent is %s percent. " % disk_percent
response += "Current CPU utilization is %s percent. " % cpu_percent
response += "Current memory utilization is %s percent. " % memory_percent
response += "it's running since %s." % running_since
return response
python类uname()的实例源码
def doFingerprints(self, nomfichier) :
try :
fichier = open(nomfichier, "w")
except IOError :
print "No such file " + nomfichier
sys.exit(-1)
print "++ Begin Generating Fingerprints in " + nomfichier
fichier.write("# Generating Fingerprints for :\n# ")
for i in platform.uname():
fichier.write(i + " ")
fichier.write('\n')
temps = strftime('%c', gmtime())
fichier.write("# " + temps + '\n')
self.ssyscalls.doFingerprints(fichier)
fichier.close()
print "++ Keep this fingerprints in safe !"
print "++ End Generating Fingerprints"
def __init__(self, base_dir, config, backup_time, seed_uri, argv=None):
StateBase.__init__(self, base_dir, config)
self.base_dir = base_dir
self.state['backup'] = True
self.state['completed'] = False
self.state['name'] = backup_time
self.state['method'] = config.backup.method
self.state['path'] = base_dir
self.state['cmdline'] = argv
self.state['config'] = config.dump()
self.state['version'] = config.version
self.state['git_commit'] = config.git_commit
self.state['host'] = {
'hostname': platform.node(),
'uname': platform.uname(),
'python': {
'build': platform.python_build(),
'version': platform.python_version()
}
}
self.state['seed'] = {
'uri': seed_uri.str(),
'replset': seed_uri.replset
}
self.init()
def on_cluster(pattern=["tars-"]):
"""Used to check if we are on a cluster
"tars-" is the name of a cluster's hostname.
Change or append the argument **pattern** with your cluster's hostname
:param str pattern: a list of names (strings) or a string
"""
if isinstance(pattern, str):
pattern = [pattern]
for this in pattern:
if platform.uname().node.startswith(this):
return True
else:
return False
def lootme_windows(outfiles):
try:
import winreg
# to be filled later
except:
print('winreg module not present')
hostloot = ((platform.uname()[1])+"_loot.txt")
outfiles.append(hostloot)
with open(hostloot, 'w') as outFile:
# gather machine info
machine_info(outFile)
# gather extended machine info
machine_info_extra_win(outFile)
# gather user info
user_info_win(outFile)
# gather network info
network_info_win(outFile)
# gather log file IPs
logfile_ips(outFile)
return outfiles
### lootme_windows --end--
### lootme_linux --start--
def userfiles_list_lin(outfiles):
userdirs = os.listdir('/home/')
userfiles = (platform.uname()[1]+'_userFiles.txt')
outfiles.append(userfiles)
with open(userfiles, 'w') as ufs:
ufs.write('\nFiles discovered:')
for d in userdirs:
for path, subdirs, files in os.walk('/home/'+d):
for name in files:
# search user directories for specified filetypes:
# pdf, txt, doc(x)
if re.search('[.]*\.pdf', name) or re.search('[.]*\.txt', name) or re.search('[.]*\.doc[.]{1}', name):
ufs.write('\n'+os.path.join(path, name)+'\n')
return outfiles
### User files list --end--
### Log file IPs --start--
def get_arch():
machine = platform.uname()[4]
if machine in ['aarch64']:
return 'aarch64'
if machine in ['amd64', 'AMD64', 'x86_64', 'i86pc']:
return 'amd64'
if machine in ['sun4v', 'sun4u', 'sparc64']:
return 'sparcv9'
if machine == 'i386' and get_os() == 'darwin':
try:
# Support for Snow Leopard and earlier version of MacOSX
if subprocess.check_output(['sysctl', '-n', 'hw.cpu64bit_capable']).strip() == '1':
return 'amd64'
except OSError:
# sysctl is not available
pass
abort('unknown or unsupported architecture: os=' + get_os() + ', machine=' + machine)
def get_platform(self):
"""
Get the OS name, hostname and kernel
"""
try:
osname = " ".join(platform.linux_distribution())
uname = platform.uname()
if osname == ' ':
osname = uname[0]
data = {'osname': osname, 'hostname': uname[1], 'kernel': uname[2]}
except Exception as err:
print err
data = str(err)
return data
# ----------------end: ???????????-----------------
# ----------------start: ???????????????-----------------
perf_events_test.py 文件源码
项目:avocado-misc-tests
作者: avocado-framework-tests
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def setUp(self):
'''
Install the packages
'''
# Check for basic utilities
smm = SoftwareManager()
detected_distro = distro.detect()
kernel_ver = platform.uname()[2]
deps = ['gcc', 'make']
if 'Ubuntu' in detected_distro.name:
deps.extend(['linux-tools-common', 'linux-tools-%s'
% kernel_ver])
# FIXME: "redhat" as the distro name for RHEL is deprecated
# on Avocado versions >= 50.0. This is a temporary compatibility
# enabler for older runners, but should be removed soon
elif detected_distro.name in ['rhel', 'SuSE', 'fedora', 'redhat']:
deps.extend(['perf'])
else:
self.cancel("Install the package for perf supported by %s"
% detected_distro.name)
for package in deps:
if not smm.check_installed(package) and not smm.install(package):
self.cancel('%s is needed for the test to be run' % package)
def setUp(self):
"""
Verify it is baremetal
Install the cpupower tool
"""
if not os.path.exists('/proc/device-tree/ibm,opal/power-mgt'):
self.cancel("Supported only on Power Non Virutalized environment")
smm = SoftwareManager()
detected_distro = distro.detect()
if 'Ubuntu' in detected_distro.name:
deps = ['linux-tools-common', 'linux-tools-%s'
% platform.uname()[2]]
else:
deps = ['kernel-tools']
for package in deps:
if not smm.check_installed(package) and not smm.install(package):
self.cancel('%s is needed for the test to be run' % package)
def test_uname_win32_ARCHITEW6432(self):
# Issue 7860: make sure we get architecture from the correct variable
# on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
# using it, per
# http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
try:
with support.EnvironmentVarGuard() as environ:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'foo')
environ['PROCESSOR_ARCHITEW6432'] = 'bar'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'bar')
finally:
platform._uname_cache = None
def test_special_pid(self):
p = psutil.Process(4)
self.assertEqual(p.name(), 'System')
# use __str__ to access all common Process properties to check
# that nothing strange happens
str(p)
p.username()
self.assertTrue(p.create_time() >= 0.0)
try:
rss, vms = p.memory_info()[:2]
except psutil.AccessDenied:
# expected on Windows Vista and Windows 7
if not platform.uname()[1] in ('vista', 'win-7', 'win7'):
raise
else:
self.assertTrue(rss > 0)
def test_uname_win32_ARCHITEW6432(self):
# Issue 7860: make sure we get architecture from the correct variable
# on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
# using it, per
# http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
try:
with test_support.EnvironmentVarGuard() as environ:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'foo')
environ['PROCESSOR_ARCHITEW6432'] = 'bar'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'bar')
finally:
platform._uname_cache = None
def test_uname_win32_ARCHITEW6432(self):
# Issue 7860: make sure we get architecture from the correct variable
# on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
# using it, per
# http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
try:
with test_support.EnvironmentVarGuard() as environ:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'foo')
environ['PROCESSOR_ARCHITEW6432'] = 'bar'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'bar')
finally:
platform._uname_cache = None
def test_uname_win32_ARCHITEW6432(self):
# Issue 7860: make sure we get architecture from the correct variable
# on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
# using it, per
# http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
try:
with support.EnvironmentVarGuard() as environ:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'foo')
environ['PROCESSOR_ARCHITEW6432'] = 'bar'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'bar')
finally:
platform._uname_cache = None
test_excel.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def test_read_from_file_url(self):
# FILE
if sys.version_info[:2] < (2, 6):
raise nose.SkipTest("file:// not supported with Python < 2.6")
localtable = os.path.join(self.dirpath, 'test1' + self.ext)
local_table = read_excel(localtable)
try:
url_table = read_excel('file://localhost/' + localtable)
except URLError:
# fails on some systems
import platform
raise nose.SkipTest("failing on %s" %
' '.join(platform.uname()).strip())
tm.assert_frame_equal(url_table, local_table)
test_parsers.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def test_file(self):
# FILE
if sys.version_info[:2] < (2, 6):
raise nose.SkipTest("file:// not supported with Python < 2.6")
dirpath = tm.get_data_path()
localtable = os.path.join(dirpath, 'salary.table')
local_table = self.read_table(localtable)
try:
url_table = self.read_table('file://localhost/' + localtable)
except URLError:
# fails on some systems
raise nose.SkipTest("failing on %s" %
' '.join(platform.uname()).strip())
tm.assert_frame_equal(url_table, local_table)
def _init(self):
try:
log.info('dataplicity %s', __version__)
log.info('uname=%s', ' '.join(platform.uname()))
self.remote = jsonrpc.JSONRPC(self.rpc_url)
self.serial = self._read(constants.SERIAL_LOCATION)
self.auth_token = self._read(constants.AUTH_LOCATION)
self.poll_rate_seconds = 60
self.disk_poll_rate_seconds = 60 * 60
self.next_disk_poll_time = time.time()
log.info('m2m=%s', self.m2m_url)
log.info('api=%s', self.rpc_url)
log.info('serial=%s', self.serial)
log.info('poll=%s', self.poll_rate_seconds)
self.m2m = M2MManager.init(self, m2m_url=self.m2m_url)
self.port_forward = PortForwardManager.init(self)
except:
log.exception('failed to initialize client')
raise
def test_uname_win32_ARCHITEW6432(self):
# Issue 7860: make sure we get architecture from the correct variable
# on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
# using it, per
# http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
try:
with test_support.EnvironmentVarGuard() as environ:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'foo')
environ['PROCESSOR_ARCHITEW6432'] = 'bar'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'bar')
finally:
platform._uname_cache = None
def test_uname_win32_ARCHITEW6432(self):
# Issue 7860: make sure we get architecture from the correct variable
# on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
# using it, per
# http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
try:
with support.EnvironmentVarGuard() as environ:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'foo')
environ['PROCESSOR_ARCHITEW6432'] = 'bar'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'bar')
finally:
platform._uname_cache = None
def test_uname_win32_ARCHITEW6432(self):
# Issue 7860: make sure we get architecture from the correct variable
# on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
# using it, per
# http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
try:
with test_support.EnvironmentVarGuard() as environ:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'foo')
environ['PROCESSOR_ARCHITEW6432'] = 'bar'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'bar')
finally:
platform._uname_cache = None
def get_sys_info():
info = """
Machine: {}\nVersion: {}
Platform: {}\nNode: {}\nUname: {}\nSystem: {}
Processor: {}\n\nHost Name: {}\nFQDN: {}\n
""".format(
platform.machine(),
platform.version(),
platform.platform(),
platform.node(),
platform.uname(),
platform.system(),
platform.processor(),
socket.gethostname(),
socket.getfqdn()
)
return info
def uptime_string(startup_time_in_seconds, last_error_time):
# Machine info
uname = platform.uname()
uptime_seconds = uptime.uptime()
# Delta uptime in human readable format
uptime_message = str(timedelta(seconds=uptime_seconds))
# Time now
now = time.time()
delta = now - startup_time_in_seconds
bot_uptime = str(timedelta(seconds=int(delta)))
# Make messsge
message = ""
message += "\U0001F4BB Running on " + uname[0] + " " + uname[2] + " " + uname[4] + "\n"
message += "\U0000231B Machine Uptime: " + uptime_message + "\n"
message += "\U0001F916 Bot uptime: " + bot_uptime + "\n"
return message
def test_special_pid(self):
p = psutil.Process(4)
self.assertEqual(p.name(), 'System')
# use __str__ to access all common Process properties to check
# that nothing strange happens
str(p)
p.username()
self.assertTrue(p.create_time() >= 0.0)
try:
rss, vms = p.memory_info()[:2]
except psutil.AccessDenied:
# expected on Windows Vista and Windows 7
if not platform.uname()[1] in ('vista', 'win-7', 'win7'):
raise
else:
self.assertTrue(rss > 0)
def test_special_pid(self):
p = psutil.Process(4)
self.assertEqual(p.name(), 'System')
# use __str__ to access all common Process properties to check
# that nothing strange happens
str(p)
p.username()
self.assertTrue(p.create_time() >= 0.0)
try:
rss, vms = p.memory_info()[:2]
except psutil.AccessDenied:
# expected on Windows Vista and Windows 7
if not platform.uname()[1] in ('vista', 'win-7', 'win7'):
raise
else:
self.assertTrue(rss > 0)
def test_uname_win32_ARCHITEW6432(self):
# Issue 7860: make sure we get architecture from the correct variable
# on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
# using it, per
# http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
try:
with support.EnvironmentVarGuard() as environ:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'foo')
environ['PROCESSOR_ARCHITEW6432'] = 'bar'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'bar')
finally:
platform._uname_cache = None
def _get_os_type():
os_type = OSType.unknown[0]
# Figure out the general OS type
uname = platform.system().strip().strip('"').strip("'").strip().lower()
if 'beos' in uname or 'haiku' in uname:
os_type = OSType.BeOS[0]
elif 'bsd' in uname or 'gnu/kfreebsd' in uname:
os_type = OSType.BSD[0]
elif 'cygwin' in uname:
os_type = OSType.Cygwin[0]
elif 'darwin' in uname:
os_type = OSType.MacOS[0]
elif 'linux' in uname:
os_type = OSType.Linux[0]
elif 'solaris' in uname or 'sunos' in uname:
os_type = OSType.Solaris[0]
elif 'windows' in uname:
os_type = OSType.Windows[0]
return os_type
def __str__(self):
"""Print out the environment"""
s = []
s.append("BUILD_CPU:")
s.append(self.env['build_cpu'])
s.append("HOST_CPU:")
s.append(self.env['host_cpu'])
s.append("\nBUILD_OS: ")
s.append(self.env['build_os'])
s.append("\nHOST_OS: ")
s.append(self.env['host_os'])
s.append("\nUNAME: ")
s.append(str(self.env['uname']))
s.append("\nHOSTNAME: ")
s.append(self.env['hostname'])
s.append("\nSYSTEM: ")
s.append(self.env['system'])
s.append("\nDICTIONARY:\n")
for k,v in iter(self.env.items()):
s.append("\t")
s.append(k)
s.append("->")
s.append(str(v))
s.append("\n")
return ''.join(s)
def verbose_startup(self):
if self._emitted_startup_msg:
return
self._emitted_startup_msg = True
if verbose(1):
msgb("INVOKED", " ".join(sys.argv))
msgb("START TIME", self.env['start_time_str'])
msgb("CURRENT DIRECTORY", os.getcwd())
msgb('UNAME', str(self.env['uname']).replace(':','_'))
msgb('SYSTEM', self.env['system'])
msgb('HOSTNAME', self.env['hostname'])
msgb("BUILD_OS", self.env['build_os'])
msgb("BUILD_CPU", self.env['build_cpu'])
msgb("HOST_OS", self.env['host_os'])
msgb("HOST_CPU", self.env['host_cpu'])
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())
))