Python subprocess.mswindows() Examples

The following are code examples for showing how to use subprocess.mswindows(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: cobra   Author: WhaleShark-Team   File: log.py    MIT License 6 votes vote down vote up
def stdout_encode(data):
    try:
        data = data or ""

        # Reference: http://bugs.python.org/issue1602
        if mswindows:
            output = data.encode(sys.stdout.encoding, "replace")

            if '?' in output and '?' not in data:
                warn = "cannot properly display Unicode characters "
                warn += "inside Windows OS command prompt "
                warn += "(http://bugs.python.org/issue1602). All "
                warn += "unhandled occurances will result in "
                warn += "replacement with '?' character. Please, find "
                warn += "proper character representation inside "
                warn += "corresponding output files. "
                single_time_warn_message(warn)

            ret = output
        else:
            ret = data.encode(sys.stdout.encoding)
    except Exception as e:
        ret = data.encode(UNICODE_ENCODING) if isinstance(data, unicode) else data

    return ret 
Example 2
Project: https-github.com-stamparm-maltrail   Author: hxp2k6   File: update.py    MIT License 5 votes vote down vote up
def _chown(filepath):
    if not subprocess.mswindows and os.path.exists(filepath):
        try:
            os.chown(filepath, int(os.environ.get("SUDO_UID", -1)), int(os.environ.get("SUDO_GID", -1)))
        except Exception, ex:
            print "[x] '%s'" % ex 
Example 3
Project: https-github.com-stamparm-maltrail   Author: hxp2k6   File: common.py    MIT License 5 votes vote down vote up
def check_sudo():
    """
    Checks for sudo/Administrator privileges
    """

    check = None

    if not subprocess.mswindows:
        if getattr(os, "geteuid"):
            check = os.geteuid() == 0
    else:
        import ctypes
        check = ctypes.windll.shell32.IsUserAnAdmin()

    return check 
Example 4
Project: WrapSQLMAP   Author: THSamurai   File: beep.py    GNU General Public License v3.0 5 votes vote down vote up
def beep():
    try:
        if subprocess.mswindows:
            _win_wav_play(BEEP_WAV_FILENAME)
        elif sys.platform == "darwin":
            _mac_beep()
        elif sys.platform == "linux2":
            _linux_wav_play(BEEP_WAV_FILENAME)
        else:
            _speaker_beep()
    except:
        _speaker_beep() 
Example 5
Project: d-rats   Author: DigitalHERMES   File: wl2k.py    GNU General Public License v3.0 5 votes vote down vote up
def run_lzhuf(cmd, data):
    p = platform.get_platform()

    cwd = tempfile.mkdtemp()

    f = file(os.path.join(cwd, "input"), "wb")
    f.write(data)
    f.close()

    kwargs = {}
    if subprocess.mswindows:
        su = subprocess.STARTUPINFO()
        su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        su.wShowWindow = subprocess.SW_HIDE
        kwargs["startupinfo"] = su

    if os.name == "nt":
        lzhuf = "LZHUF_1.EXE"
    elif os.name == "darwin":
        raise Exception("Not supported on MacOS")
    else:
        lzhuf = "lzhuf"

    lzhuf_path = os.path.abspath(os.path.join(p.source_dir(), "libexec", lzhuf))
    shutil.copy(os.path.abspath(lzhuf_path), cwd)
    run = [lzhuf_path, cmd, "input", "output"]
    
    print "Running %s in %s" % (run, cwd)

    ret = subprocess.call(run, cwd=cwd, **kwargs)
    print "LZHUF returned %s" % ret
    if ret:
        return None

    f = file(os.path.join(cwd, "output"), "rb")
    data = f.read()
    f.close()

    return data 
Example 6
Project: d-rats   Author: DigitalHERMES   File: spell.py    GNU General Public License v3.0 5 votes vote down vote up
def __open_aspell(self):
        kwargs = {}
        if subprocess.mswindows:
            su = subprocess.STARTUPINFO()
            su.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            su.wShowWindow = subprocess.SW_HIDE
            kwargs["startupinfo"] = su

        p = subprocess.Popen([self.__aspell, "pipe"],
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             #close_fds=True,
                             **kwargs)
        return p 
Example 7
Project: NoobSec-Toolkit   Author: krintoxi   File: beep.py    GNU General Public License v2.0 5 votes vote down vote up
def beep():
    try:
        if subprocess.mswindows:
            _win_wav_play(BEEP_WAV_FILENAME)
        elif sys.platform == "darwin":
            _mac_beep()
        elif sys.platform == "linux2":
            _linux_wav_play(BEEP_WAV_FILENAME)
        else:
            _speaker_beep()
    except:
        _speaker_beep() 
Example 8
Project: NoobSec-Toolkit   Author: krintoxi   File: beep.py    GNU General Public License v2.0 5 votes vote down vote up
def beep():
    try:
        if subprocess.mswindows:
            _win_wav_play(BEEP_WAV_FILENAME)
        elif sys.platform == "darwin":
            _mac_beep()
        elif sys.platform == "linux2":
            _linux_wav_play(BEEP_WAV_FILENAME)
        else:
            _speaker_beep()
    except:
        _speaker_beep() 
Example 9
Project: NoobSec-Toolkit   Author: krintoxi   File: beep.py    GNU General Public License v2.0 5 votes vote down vote up
def beep():
    try:
        if subprocess.mswindows:
            _win_wav_play(BEEP_WAV_FILENAME)
        elif sys.platform == "darwin":
            _mac_beep()
        elif sys.platform == "linux2":
            _linux_wav_play(BEEP_WAV_FILENAME)
        else:
            _speaker_beep()
    except:
        _speaker_beep() 
Example 10
Project: NoobSec-Toolkit   Author: krintoxi   File: beep.py    GNU General Public License v2.0 5 votes vote down vote up
def beep():
    try:
        if subprocess.mswindows:
            _win_wav_play(BEEP_WAV_FILENAME)
        elif sys.platform == "darwin":
            _mac_beep()
        elif sys.platform == "linux2":
            _linux_wav_play(BEEP_WAV_FILENAME)
        else:
            _speaker_beep()
    except:
        _speaker_beep() 
Example 11
Project: malware   Author: JustF0rWork   File: update.py    MIT License 5 votes vote down vote up
def _chown(filepath):
    if not subprocess.mswindows and os.path.exists(filepath):
        try:
            os.chown(filepath, int(os.environ.get("SUDO_UID", -1)), int(os.environ.get("SUDO_GID", -1)))
        except Exception, ex:
            print "[x] '%s'" % ex 
Example 12
Project: malware   Author: JustF0rWork   File: common.py    MIT License 5 votes vote down vote up
def check_sudo():
    """
    Checks for sudo/Administrator privileges
    """

    check = None

    if not subprocess.mswindows:
        if getattr(os, "geteuid"):
            check = os.geteuid() == 0
    else:
        import ctypes
        check = ctypes.windll.shell32.IsUserAnAdmin()

    return check 
Example 13
Project: tsusen   Author: stamparm   File: common.py    MIT License 5 votes vote down vote up
def check_sudo():
    retval = None

    if not subprocess.mswindows:
        if getattr(os, "geteuid"):
            retval = os.geteuid() == 0
    else:
        import ctypes
        retval = ctypes.windll.shell32.IsUserAnAdmin()

    return retval 
Example 14
Project: ipnoise   Author: stamparm   File: common.py    MIT License 5 votes vote down vote up
def check_sudo():
    retval = None

    if not subprocess.mswindows:
        if getattr(os, "geteuid"):
            retval = os.geteuid() == 0
    else:
        import ctypes
        retval = ctypes.windll.shell32.IsUserAnAdmin()

    return retval 
Example 15
Project: Burp-Addons   Author: SofianeHamlaoui   File: beep.py    GNU General Public License v3.0 5 votes vote down vote up
def beep():
    try:
        if subprocess.mswindows:
            _win_wav_play(BEEP_WAV_FILENAME)
        elif sys.platform == "darwin":
            _mac_beep()
        elif sys.platform == "linux2":
            _linux_wav_play(BEEP_WAV_FILENAME)
        else:
            _speaker_beep()
    except:
        _speaker_beep() 
Example 16
Project: bitdust.public.old   Author: vesellov   File: nonblocking.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def make_nonblocking(self):
        """
        Under Linux use built-in method ``fcntl.fcntl`` to make the pipe
        read/write non blocking.
        """
        if subprocess.mswindows:
            return
        conn, maxsize = self.get_conn_maxsize('stdout', None)
        if conn is None:
            return
        flags = fcntl.fcntl(conn, fcntl.F_GETFL)
        if not conn.closed:
            fcntl.fcntl(conn, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 17
Project: https-github.com-stamparm-maltrail   Author: hxp2k6   File: settings.py    MIT License 4 votes vote down vote up
def _get_total_physmem():
    retval = None

    try:
        if subprocess.mswindows:
            import ctypes

            kernel32 = ctypes.windll.kernel32
            c_ulong = ctypes.c_ulong
            class MEMORYSTATUS(ctypes.Structure):
                _fields_ = [
                    ('dwLength', c_ulong),
                    ('dwMemoryLoad', c_ulong),
                    ('dwTotalPhys', c_ulong),
                    ('dwAvailPhys', c_ulong),
                    ('dwTotalPageFile', c_ulong),
                    ('dwAvailPageFile', c_ulong),
                    ('dwTotalVirtual', c_ulong),
                    ('dwAvailVirtual', c_ulong)
                ]

            memory_status = MEMORYSTATUS()
            memory_status.dwLength = ctypes.sizeof(MEMORYSTATUS)
            kernel32.GlobalMemoryStatus(ctypes.byref(memory_status))

            retval = memory_status.dwTotalPhys
        else:
            retval = 1024 * int(re.search(r"(?i)MemTotal:\s+(\d+)\skB", open("/proc/meminfo").read()).group(1))
    except:
        pass

    if not retval:
        try:
            import psutil
            retval = psutil.virtual_memory().total
        except:
            pass

    if not retval:
        try:
            retval = int(re.search(r"Mem:\s+(\d+)", subprocess.check_output("free -b", shell=True)).group(1))
        except:
            pass

    return retval 
Example 18
Project: learning-python   Author: Akagi201   File: xosVer.py    MIT License 4 votes vote down vote up
def main():
    print (r"                             ")
    print (r"            \ \    / /       ")
    print (r"__  _____  __\ \  / /__ _ __ ")
    print (r"\ \/ / _ \/ __\ \/ / _ \ '__|")
    print (r" >  < (_) \__ \\  /  __/ |   ")
    print (r"/_/\_\___/|___/ \/ \___|_|   ")
    print (r"                             ")

    IS_WIN = subprocess.mswindows
    _      = os.path.normpath(sys.argv[0])
    usage  = "%s%s <options>" % ("python" if not IS_WIN else "", \
         "\"%s\"" % _ if " " in _ else _)
    print ("Version: {0}".format(__version__))
    parser = OptionParser(usage=usage)
    try:
        parser.add_option("--hh", dest="help",
                            action="store_true",
                            help="Show help message and exit")
        parser.add_option("-i", dest="ip",
                            help="Single IP scan  mode  (eg:192.168.1.11)")
        parser.add_option("-p", dest="ips",
                            help="Batch  IP scan  mode  (eg:192.168.1.10/20)")
        parser.add_option("-o", dest="output",
                            help="Save results to a file",
                            default = False)
        parser.add_option("--timeout", dest="timeout", type="int",
                           help="Seconds to wait before timeout connection "
                           "(default 2)", default = 2)
        
        args = []
        for arg in sys.argv:
            args.append(arg)
        (args, _) = parser.parse_args(args)
        if not any((args.ip, args.ips)):
            errMsg = "use -h for help"
            parser.error(errMsg)
        for i in xrange(len(sys.argv)):
            try:
                if sys.argv[i] == '-i':
                    reip = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])')
                    for ip in reip.findall(args.ip):ip				
                    xosVer(ip, args.timeout, args.output)
                elif sys.argv[i] == '-p':
                    reip = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])/\d{1,3}')
                    for ip in reip.findall(args.ips):ip
                    ip   = ip.split('/')
                    exIp = ip[0][:ip[0].rfind('.') + 1]
                    sIp  = int(ip[0][ip[0].rfind('.') + 1:], 10)
                    eIp  = int(ip[1], 10) + 1
                    for i in xrange(sIp, eIp):
                        xosVer(exIp + str(i), args.timeout, args.output)
            except Exception, e:
                    print ("\r\noption %s invalid value: %s" % (sys.argv[i], sys.argv[i + 1]))
                    print ("\r\nuse -h for help")
    except (OptionError,TypeError), e:
        parser.error(e) 
Example 19
Project: malware   Author: JustF0rWork   File: server.py    MIT License 4 votes vote down vote up
def main():

    print("%s (server) #v%s\n" % (NAME, VERSION))

    parser = optparse.OptionParser(version=VERSION)
    parser.add_option("-c", dest="config_file", default=CONFIG_FILE, help="Configuration file (default: '%s')" % os.path.split(CONFIG_FILE)[-1])
    options, _ = parser.parse_args()

    read_config(options.config_file)

    if config.USE_SSL:
        try:
            import OpenSSL
        except ImportError:
            if subprocess.mswindows:
                exit("[!] please install 'pyopenssl' (e.g. 'pip install pyopenssl')")
            else:
                msg, _ = "[!] please install 'pyopenssl'", platform.linux_distribution()[0].lower()
                for distro, install in {("fedora", "centos"): "sudo yum install pyOpenSSL", ("debian", "ubuntu"): "sudo apt-get install python-openssl"}.items():
                    if _ in distro:
                        msg += " (e.g. '%s')" % install
                        break
                exit(msg)

        if not config.SSL_PEM or not os.path.isfile(config.SSL_PEM):
            hint = "openssl req -new -x509 -keyout %s -out %s -days 365 -nodes -subj '/O=%s CA/C=EU'" % (config.SSL_PEM or "server.pem", config.SSL_PEM or "server.pem", NAME)
            exit("[!] invalid configuration value for 'SSL_PEM' ('%s')\n[?] (hint: \"%s\")" % (config.SSL_PEM, hint))

    def update_timer():
        if config.USE_SERVER_UPDATE_TRAILS:
            update_trails()

        update_ipcat()

        thread = threading.Timer(config.UPDATE_PERIOD, update_timer)
        thread.daemon = True
        thread.start()

    if config.UDP_ADDRESS and config.UDP_PORT:
        if check_sudo() is False:
            exit("[!] please run '%s' with sudo/Administrator privileges when using 'UDP_ADDRESS' configuration value" % __file__)

        start_logd(address=config.UDP_ADDRESS, port=config.UDP_PORT, join=False)

    try:
        update_timer()
        start_httpd(address=config.HTTP_ADDRESS, port=config.HTTP_PORT, pem=config.SSL_PEM if config.USE_SSL else None, join=True)
    except KeyboardInterrupt:
        print("\r[x] stopping (Ctrl-C pressed)") 
Example 20
Project: tsusen   Author: stamparm   File: settings.py    MIT License 4 votes vote down vote up
def read_config(config_file):
    global config

    if not os.path.isfile(config_file):
        exit("[!] missing configuration file '%s'" % config_file)

    config.clear()

    try:
        array = None
        content = open(config_file, "rb").read()

        for line in content.split("\n"):
            line = re.sub(r"#.+", "", line)
            if not line.strip():
                continue

            if line.count(' ') == 0:
                array = line.upper()
                config[array] = []
                continue

            if array and line.startswith(' '):
                config[array].append(line.strip())
                continue
            else:
                array = None
                try:
                    name, value = line.strip().split(' ', 1)
                except ValueError:
                    name = line.strip()
                    value = ""
                finally:
                    name = name.upper()
                    value = value.strip("'\"")

            if name.startswith("USE_"):
                value = value.lower() in ("1", "true")
            elif value.isdigit():
                value = int(value)
            else:
                for match in re.finditer(r"\$([A-Z0-9_]+)", value):
                    if match.group(1) in globals():
                        value = value.replace(match.group(0), globals()[match.group(1)])
                    else:
                        value = value.replace(match.group(0), os.environ.get(match.group(1), match.group(0)))
                if subprocess.mswindows and "://" not in value:
                    value = value.replace("/", "\\")

            config[name] = value

    except (IOError, OSError):
        pass

    for option in ("MONITOR_INTERFACE",):
        if not option in config:
            exit("[!] missing mandatory option '%s' in configuration file '%s'" % (option, config_file)) 
Example 21
Project: ipnoise   Author: stamparm   File: settings.py    MIT License 4 votes vote down vote up
def read_config(config_file):
    global config

    if not os.path.isfile(config_file):
        exit("[!] missing configuration file '%s'" % config_file)

    config.clear()

    try:
        array = None
        content = open(config_file, "rb").read()

        for line in content.split("\n"):
            line = re.sub(r"#.+", "", line)
            if not line.strip():
                continue

            if line.count(' ') == 0:
                array = line.upper()
                config[array] = []
                continue

            if array and line.startswith(' '):
                config[array].append(line.strip())
                continue
            else:
                array = None
                try:
                    name, value = line.strip().split(' ', 1)
                except ValueError:
                    name = line.strip()
                    value = ""
                finally:
                    name = name.upper()
                    value = value.strip("'\"")

            if name.startswith("USE_"):
                value = value.lower() in ("1", "true")
            elif value.isdigit():
                value = int(value)
            else:
                for match in re.finditer(r"\$([A-Z0-9_]+)", value):
                    if match.group(1) in globals():
                        value = value.replace(match.group(0), globals()[match.group(1)])
                    else:
                        value = value.replace(match.group(0), os.environ.get(match.group(1), match.group(0)))
                if subprocess.mswindows and "://" not in value:
                    value = value.replace("/", "\\")

            config[name] = value

    except (IOError, OSError):
        pass

    for option in ("MONITOR_INTERFACE",):
        if not option in config:
            exit("[!] missing mandatory option '%s' in configuration file '%s'" % (option, config_file))