コード例 #1
0
ファイル: ntk_utils.py プロジェクト: hengenlab/neuraltoolkit
def check_ping_status(ip_system):
    '''
    Check whether a system is up using ping

    check_ping_status(ip_system)
    status = check_ping_status("127.0.0.1")
    ip_system : ip of the system

    return 1 if up or 0 if down
    '''

    from platform import system as system_name
    import subprocess

    if system_name().lower() == 'windows':
        command = str('ping -n 3 ') + str(ip_system)
    elif system_name().lower() == 'linux':
        command = str('ping -c 3 ') + str(ip_system)
    elif system_name().lower() == 'darwin':
        command = str('ping -c 3 ') + str(ip_system)
    try:
        _ = subprocess.check_output(command, shell=True)
        # print(output)
        return 1
    except subprocess.CalledProcessError as e:
        if 0:  # debug
            print(e)
        return 0
コード例 #2
0
def ping(host):
    param = "-n" if system_name().lower() == "windows" else "-c"
    command = ["ping", param, "1", host]
    if system_name().lower() == "windows":
        retcode = system_call(command, creationflags=0x00000008)
        return retcode == 0
    else:
        retcode = system_call(command)
コード例 #3
0
    def run_iperf3(self, upload=False):
        self.done = False
        self.progress_bar["value"] = 0
        self.progress_bar["maximum"] = int(self.duration.get())
        self.meter.max_val = 0
        self.meter.set(0)
        self.meter.show_max = self.max_options.index(self.max_mode_value.get(
        ))  #get index of item selected in max options
        fname = tempfile.NamedTemporaryFile()
        if system_name().lower() == 'windows':
            iperf_command = '%s -c %s -p %s -P %s -O 1 -t %s %s --logfile %s' % (
                self.arg.iperf_exec, self.server.get(), self.server_port.get(),
                self.threads.get(), self.duration.get(),
                '' if upload else '-R', fname.name)
        else:
            iperf_command = '%s -c %s -p %s -P %s -O 1 -t %s %s ' % (
                self.arg.iperf_exec, self.server.get(), self.server_port.get(),
                self.threads.get(), self.duration.get(),
                '' if upload else '-R')

        self.print("command: %s" % iperf_command)
        message = 'Attempting connection - Please Wait'
        if upload:
            self.upload_label.config(text=message)
        else:
            self.download_label.config(text=message)
        self.update_idletasks()
        try:
            self.p = subprocess.Popen(iperf_command.split(),
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.STDOUT)
        except Exception as e:
            self.msg_label.config(text='%s:' % sys.exc_info()[0].__name__)
            self.ping_label.config(text='(%s) %s' % (self.arg.iperf_exec, e))
            print('Error in command: %s\r\n%s' % (iperf_command, e))
            return []

        message = 'Testing'
        if upload:
            self.upload_label.config(text=message)
        else:
            self.download_label.config(text=message)

        with fname:
            results_list = self.progress(
                fname if system_name().lower() == 'windows' else self.p.stdout,
                upload)

        try:
            self.p.terminate()
            self.setmeter(0)
            self.update_idletasks()
        except (tk.TclError, AttributeError):
            pass
        self.print('End of Test')
        return results_list
コード例 #4
0
ファイル: IQAM.py プロジェクト: MarkNBroadhead/IQAM
def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    Remember that some hosts may not respond to a ping request even if the host name is valid.
    """
    parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"
    cmd = subprocess.Popen("ping " + parameters + " " + host,
                           shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    throwaway = cmd.stdout.readline()
    err = cmd.stderr.readline().decode('UTF-8').strip()
    line = cmd.stdout.readline().decode('UTF-8').strip()
    latency = 0
    timeout = 0
    had_no_route = 0
    if len(err) > 0:
        if "Request timeout" in err:
            timeout = 1
        if "No route to host" in err or "Destination Host Unreachable" in err:
            had_no_route = 1
    if "time=" in line:
        latency = line.split(" ")[-2][5:]
    if timeout == 0.0 and latency == 0 and had_no_route == 0:
        timeout = 1
    return latency, host, timeout, had_no_route
コード例 #5
0
def ping(myhost):

    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
    """
    # Ping command count option as function of OS
    param = '-n 1 -w 2' if system_name().lower()=='windows' else '-c 1 -w 2'
    command = "ping %s %s" % (param,myhost)
    ping_response = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read() 
    #print("ping resp : %s" % ping_response)

    #will be something like this :
    #Pinging 192.168.0.147 with 32 bytes of data:
    #Reply from 192.168.0.147: bytes=32 time<1ms TTL=64
    #Ping statistics for 192.168.0.147:
    #    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
    #Approximate round trip times in milli-seconds:
    #    Minimum = 0ms, Maximum = 0ms, Average = 0ms

    #print("ping response :>"+ping_response+"<")
    if ping_response == "":
      return False
    pingOK = True
    if ((b'100% loss' in ping_response.lower()) or 
        (b'100% packet loss' in ping_response.lower()) or 
        (b'unreachable' in ping_response.lower()) or 
        (b'request timed out' in ping_response.lower())
        ):
        pingOK = False

    return pingOK
コード例 #6
0
	def clear(self):
		"""
		Helpful code to clear the screen from StackOverflow
		https://stackoverflow.com/questions/18937058/clear-screen-in-shell/31871439
		"""
		command = "cls" if system_name().lower()=="windows" else "clear"
		system_call(command)
コード例 #7
0
    def ping(self):
        import os
        import subprocess
        from platform   import system as system_name  # Returns the system/OS name
        """
        Returns True if host (str) responds to a ping request.
        Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
        """

        # Ping command count option as function of OS
        param = '-n' if system_name().lower()=='windows' else '-c'

        # Building the command. Ex: "ping -c 1 google.com"
        command = ['ping', param, '3', self.ip]

        # Pnging
        with open(os.devnull, 'w') as DEVNULL:
            try:
                subprocess.check_call(
                    command,
                    stdout=DEVNULL,  # suppress output
                    stderr=DEVNULL
                )
                is_up = True
            except subprocess.CalledProcessError:
                is_up = False

            return is_up
コード例 #8
0
def ping_host(host, pings):
    # Ping parameters as function of OS
    parameters = "-n " if system_name().lower() == "windows" else "-A -w15 -c "
    # Pinging
    result = shell("ping " + parameters + str(pings) + " " + host + " >" +
                   devnull + " 2>&1") == 0
    return result
コード例 #9
0
def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
    """

    print system_name().lower()

    # Ping command count option as function of OS
    param = '-n' if system_name().lower() == 'windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '1', host]

    # Pinging
    return system_call(command) == 0
コード例 #10
0
def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
    """

    # Ping command count option as function of OS
    param = '-n' if system_name().lower() == 'windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '1', '-t', '1', host]

    # output = subprocess.check_output(command)
    result = 1
    response = 0
    try:
        output = subprocess.check_output(command).split()
        for element in output:
            if 'time' in element.lower():
                print element
                response = element.split('=')[1]
                result = 0
    except:
        result = 2
        response = 0

    return result, response
コード例 #11
0
ファイル: util.py プロジェクト: privatez/python-
def ping(host: str, count: int = 1):
    param = '-n' if system_name().lower() == 'windows' else '-c'
    command = ['ping', param, str(count), host]

    return subprocess.Popen(
        command, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE).stdout.read().decode('utf8')
コード例 #12
0
def ping(host):
    # Ping command count option as function of OS
    param = '-n' if system_name().lower() == 'windows' else '-c'
    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '1', host]
    # Pinging
    return system_call(command) == 0
コード例 #13
0
 def execute_ping(self, start=0):
     with open(os.devnull, 'w') as DEVNULL:
         if system_name().lower() == "windows":
             try:
                 subprocess.check_call(
                     ['ping', '-n', '1', self.ip_to_check],
                     stdout=DEVNULL,  # suppress output
                     stderr=DEVNULL)
             except subprocess.CalledProcessError:
                 return False
         else:
             try:
                 subprocess.check_call(
                     [
                         'timeout', '1.5', 'ping', '-c', '1',
                         self.ip_to_check
                     ],
                     stdout=DEVNULL,  # suppress output
                     stderr=DEVNULL)
                 return True
             except subprocess.CalledProcessError:
                 if start == 3:
                     return False
                 else:
                     return self.execute_ping(start + 1)
コード例 #14
0
def ping_ip(ip, timeout):
    """
    Ping an IP address
    https://stackoverflow.com/questions/2953462/pinging-servers-in-python
    
    Args:
        ip (str): ip address
        timeout (int, optional): length of time for the function to return
        timeout status. 
    
    Returns:
        str: OFFLINE if the device is OFFLINE
             ONLINE if the device is ONLINE 
    """
    if system_name().lower() == "windows":
        #  -w is timeout -n is number of packets
        params = "-w {} -n 1".format(
            timeout * 1000
        )  # convert seconds to mills for non-windows

    else:
        #  -W is timeout -c is number of packets
        params = "-W {} -c 1".format(timeout)

    response = system_call("ping " + params + " " + ip)

    # logger.debug(str(response))

    if response != 0:
        return "OFFLINE"
    else:
        return "ONLINE"
コード例 #15
0
ファイル: pdf_grep.py プロジェクト: keeganridgley107/SerPeNT
def get_pdf_dir():
    """get path to dir containing pdfs"""

    # do a quick OS check then append dir path to home
    if system_name().lower() == 'windows':
        # else if windows path equals
        desktop = os.path.join(os.path.join(os.environ['USERPROFILE']),
                               'Desktop')
    else:
        # if unix desktop path equals
        desktop = os.path.join(os.path.join(os.path.expanduser('~')),
                               'Desktop')
    dir_name = input("[?] Enter name of pdf_dir on desktop: ")
    dir_path = desktop + "\\" + dir_name
    try:
        # check if dir exists
        dir_check = os.path.isdir(dir_path)
        # check if the dir has any pdf files in it
        pdf_check = os.path.exists(dir_path + "\\*.pdf")
        print("[!] Dir exists: %s, dir has files: %s" % (dir_check, pdf_check))
        dir_files = [
            f for f in os.listdir(dir_path) if isfile(join(dir_path, f))
        ]
        print("[+] Folder contains %d files" % len(dir_files))
    except Exception as e:
        # exit DEBUG
        print("[-] Error: Input: %s" % dir_path)
        print("[-] Exception: ", e)
        exit(0)
    return dir_path
コード例 #16
0
def ICMP_Ping_Flood(host, cmds):
    """
	Sends a flood of pings n pings set by amount using the ICMP protocols.
	Remember that a host may not respond to a ping (ICMP) request even if 		the host name is valid.
	"""
    # defaults amount to 1 if user didn't specify an amount of pings
    try:
        amount = int(cmds[2])
    except IndexError:
        amount = 1
    except Exception as e:
        print('in ping flood: ')
        print('something was wrong with arguments: ', cmds)
        print('\n', e)
        return
    try:
        amount = int(amount)
        # Ping command count option as function of OS
        param = '-n' if system_name().lower() == 'windows' else '-c'
        for i in range(0, amount):
            # Building the command. Ex: "ping -c 1 google.com"
            # <cmd> <os> <num packets> <hosts>
            command = ['ping', param, '1', host]
            # Pinging
            print(system_call(command))
    except Exception as e:
        print('something went wrong in ping flood ', e)
        print('host and number of pings set: ', cmds)
コード例 #17
0
def ping(host, quant):
    if (system_name().upper() == "WINDOWS"):
        parametros = ("-n %s" % quant)
    else:
        parametros = ("-c %s" % quant)

    return system_call("ping " + parametros + " " + host) == 0
コード例 #18
0
def ping_node(ip_list):
    """
    Used to get the FQDN of the nodes and ping them, uncomment the line
    ping -c for *nix, uncomment the line ping -n for windows
    """
    out_dict = {}
    if system_name().lower() == "windows":
        ping_cmd = 'ping -n 1 '
        ping_out = ' > NUL'
    else:
        ping_cmd = 'ping -c 1 '
        ping_out = ' > /dev/null'
    for node_ip in ip_list:
        try:
            node_fqdn = (socket.gethostbyaddr(node_ip))[0]
            response = os.system(ping_cmd + node_fqdn + ping_out)
            if response == 0:
                out_dict[node_fqdn] = "Ping succeeded"
            else:
                out_dict[node_fqdn] = "Ping failed"
        except Exception:
            not_found = "Address " + node_ip + " not found in DNS, skipping."
            out_dict[node_ip] = not_found
    hdr1 = "Node FQDN"
    hdr2 = "Ping status"
    sort_order = 1
    return hdr1, hdr2, out_dict, sort_order
コード例 #19
0
def ping(host):
    fn = open(os.devnull, 'w')
    param = '-n' if system_name().lower() == 'windows' else '-c'
    command = ['ping', param, '1', host]
    retcode = system_call(command, stdout=fn, stderr=subprocess.STDOUT)
    fn.close()
    return retcode == 0
コード例 #20
0
def pingHost(host):
    """
    Takes host address and returns True if host (str) responds to a ping request.

    Args: host address (string)

    Returns: Bool

    Note: Host may not respond to a ping (ICMP) request even if the hostname is valid.
    """

    # Ping command count option as function of OS
    param = '-n' if system_name().lower() == 'windows' else '-c'

    # Building the command. "ping -c 1 google.com" for Unix || "ping -n 1 google.com" for windows
    command = ['ping', param, '1', host]

    # Pinging
    # TODO: change to use check_output to not print pinging; only result
    # hostInfo = subprocess.check_output(['ping', param, '1', host], shell=True).decode("utf-8")
    # replyInfo = hostInfo.split("\n")
    # replyInfo = replyInfo[2]

    isHostLive = subprocess.call(command) == 0
    print("\n", flush=True)  # flush is kinda hacky workaround for above fix
    return isHostLive
コード例 #21
0
def pinghost(host):
    try:
        output = str(
            subprocess.Popen(["ping.exe", host],
                             stdout=subprocess.PIPE).communicate()[0])
        if 'unreachable' in output:
            log_error('!!!!!' + host + ' is unreachable!!!!!')
            return False
        else:
            log_info(host + ' is online')
            return True
    except Exception as error:
        log_warn('Current Machine is not running Windows-based OS: ' +
                 str(error))
        # Ping command count option as function of OS
        param = '-n' if system_name().lower() == 'windows' else '-c'
        # Building the command. Ex: "ping -c 1 phlamtecdb-a"
        command = ['ping', param, '1', host]
        # Pinging
        if system_call(command) == 0:
            log_info(host + ' is online')
            return True
        else:
            log_error('!!!!!' + host + ' is OFFLINE!!!!!')
            return False
コード例 #22
0
def ping(host):
    # Ping parameters as function of OS
    # Works with Windows, OS X, or Linux
    parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"

    # Pinging
    return system_call("ping " + parameters + " " + host) == 0
コード例 #23
0
ファイル: connected.py プロジェクト: acrosman/connected
def ping(host):
    """
    Returns response time in ms if server is up, otherwise an error string.
    Remember that some hosts may not respond to a ping request even if the host
    name is valid.
    """

    # Ping parameters as function of OS
    parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"

    # Pinging
    proc = subprocess.Popen(["ping", parameters, host], stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

    # Parse response
    response = proc.communicate()

    if response[0]:
        tokens = response[0].split()
    else:
        return response[1]

    if tokens[0].decode("utf-8") == 'PING':
        for t in tokens:
            sample = t.decode('utf-8')
            if sample[:5] == 'time=':
                ms = sample.split('=')[1]
                return ms

    return 'down'
コード例 #24
0
 def clear_shell_screen():
     """
     clears the shell screen
     :return: None
     :rtype: None
     """
     cmd = "cls" if system_name().lower() == "windows" else "clear"
     system_call(cmd)
コード例 #25
0
def ping(host):

    # 判断系统
    parameters = "-n 1" if system_name().lower() == "windows" else "-c 1"

    # return popen("ping " + parameters + " " + host).read()
    # return system("ping " + parameters + " " + host) == 0
    return subprocess.call("ping " + parameters + " " + host) == 0
コード例 #26
0
def clear_screen():
    """Clears the terminal screen."""
    if system_name().lower() == "windows":
        command = "cls"
    else:
        command = "clear"

    system_call(command)
コード例 #27
0
def ping_ip(ip: IPAddress) -> bool:
    param = "-n" if system_name().lower() == "windows" else "-c"
    command = ["ping", param, "1", ip]
    reply = subprocess.run(command,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    ip_is_reachable = reply.returncode == 0
    return ip_is_reachable
コード例 #28
0
def clear_screen():
    """
    Clears the terminal screen.
    """
    # Clear command as function of OS
    command = "cls" if system_name().lower() == "windows" else "clear"
    # Action
    system_call(command)
コード例 #29
0
ファイル: 43593.py プロジェクト: Simon0105/exploit-database
def ping_host(host):
    args = "-n 1" if system_name().lower()=="windows" else "-c 1"
    res=subprocess.call("ping " + args + " " + host, shell=True) == 0
    if not res:
        print str(host) + ' down? trying ARP'
        if not arp(host):
            print str(host) + ' unreachable.'
            return
    return res
コード例 #30
0
def clear():
    """
    Limpa a tela comparando sistema operacional
    """
    from platform import system as system_name
    from subprocess import call as system_call

    command = 'cls' if system_name().lower() == 'windows' else 'clear'
    system_call([command])
コード例 #31
0
def ping_ip(ip):
    param = "-n" if system_name().lower() == "windows" else "-c"
    command = ["ping", param, "3", ip]
    reply = subprocess.run(command,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    progress.update(t1, advance=1)
    ip_is_reachable = reply.returncode == 0
    return ip, ip_is_reachable
コード例 #32
0
def ping_host(host):

    """
    Returns True if host (str) responds to a ping request.
    Remember that some hosts may not respond to a ping request even if the host name is valid.
    """

    # Ping parameters as function of OS
    if system_name().lower() == "windows":
        parameters = "-n 1"
        command = 'ping {0} {1}'.format(parameters, host)
    else:
        command = ['ping', '-c', '1', host]

    # Build the command string
    # Pinging
    return subprocess.call(command, stdout=subprocess.PIPE) == 0
コード例 #33
0
ファイル: build.py プロジェクト: adynathos/AugmentedUnreality
# Dirs
dir_opencv_root = os.path.dirname(os.path.realpath(__file__))
dir_src = pp(dir_opencv_root, 'src', 'opencv')
dir_cmake = pp(dir_opencv_root, 'cmake_settings')
dir_plugin_root = pp(dir_opencv_root, '..', '..')

# Platform
platform_dirs = {
	'windows': 'Win64',
	'linux': 'Linux',
	'android': 'Android',
}
platforms = list(platform_dirs.keys())
platforms.sort()

platform_current = system_name().lower()
if platform_current not in platform_dirs:
	print('Warning: unrecognized platform: ', platform_current)
	platform_current = platforms[0]

# OpenCV Modules
MODULES = [
	"opencv_core",
	"opencv_augmented_unreality", # parts of our plugin that are easier to build as a custom OpenCV module
	"opencv_aruco",		# Aruco markers
	"opencv_calib3d",	# camera calibration
	"opencv_features2d", # cv::SimpleBlobDetector for calibration
	"opencv_flann",     # Aruco needs this
	"opencv_imgcodecs",	# imwrite
	"opencv_imgproc",   # Aruco needs this
	"opencv_video",		# Kalman filter
コード例 #34
0
ファイル: sensors.py プロジェクト: jaquinonesg/SMA_exp
def ping(host):
    parameters = "-n 1" if system_name().lower()=="windows" else "-c 1"
    return system_call("ping " + parameters + " " + host) == 0
コード例 #35
0
ファイル: utils.py プロジェクト: rodjjo/loop-builder
def is_windows():
    return system_name() == 'Windows'  # TODO: MELHORAR ISSO
コード例 #36
0
ファイル: 43593.py プロジェクト: Simon0105/exploit-database
def arp(host):
    args = "-a" if system_name().lower()=="windows" else "-e"
    return subprocess.call("arp " + args + " " + host, shell=True) == 0