sys.stdin.readline

Here are the examples of the python api sys.stdin.readline taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

129 Examples 7

Example 51

Project: nightmare Source File: envitools.py
Function: lockstepemulator
def lockStepEmulator(emu, trace):
    while True:
        print "Lockstep: 0x%.8x" % emu.getProgramCounter()
        try:
            pc = emu.getProgramCounter()
            op = emu.makeOpcode(pc)
            trace.stepi()
            emu.stepi()
            cmpRegs(emu, trace)
        except RegisterException, msg:
            print "Lockstep Error: %s: %s" % (repr(op),msg)
            setRegs(emu, trace)
            sys.stdin.readline()
        except Exception, msg:
            traceback.print_exc()
            print "Lockstep Error: %s" % msg
            return

Example 52

Project: parlparse Source File: patchtool.py
def RunPatchTool(typ, sdatext, ce):
	if not ce.stamp:
		print "No stamp available, so won't move your cursor to right place"
	else:
		assert ce.stamp.sdate[:10] == sdatext[:10]  # omitting the letter extension

	print "\nHit RETURN to launch your editor to make patches "
	sys.stdin.readline()
	RunPatchToolW(typ, sdatext, ce.stamp, ce.fragment)
	memberList.reloadJSON()

Example 53

Project: honeything Source File: split-cmd.py
Function: read_ids
    def read_ids():
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            if line:
                line = line.strip()
            try:
                it = cp.get(line.strip())
                next(it)  # skip the file type
            except KeyError, e:
                add_error('error: %s' % e)
                continue
            yield IterToFile(it)

Example 54

Project: PyLatencyMap Source File: LatencyMap.py
Function: get_new_line
    def get_new_line(self):
        while True:
           line = sys.stdin.readline()
           if not line:
                print "\nReached EOF from data source, exiting."
                sys.exit(0)
           if line.strip() <> '':
               return(line.lower().strip())    # return the line read from stdin, lowercase, strip 

Example 55

Project: PytheM Source File: exploit.py
	def stdinpwn(self, payload):
		resource.setrlimit(resource.RLIMIT_STACK, (-1, -1))
                resource.setrlimit(resource.RLIMIT_CORE, (-1, -1))
                P = Popen(self.target, stdin=PIPE)
                print "[*] Sending buffer with lenght: "+str(len(payload))
		P.stdin.write(payload)
		while True:
			line = sys.stdin.readline()
			P.poll()
			ret = P.returncode
			if ret is None:
				P.stdin.write(line)
			else:
				if ret == -11:
					print "[*] Child program crashed with SIGSEGV"
				else:
					print "[-] Child program exited with code %d" % ret
				break
		print "\n If it does not work automatically, run on terminal: (cat buffer.txt ; cat) | {}".format(self.target)

Example 56

Project: mutt-ical Source File: mutt-ical.py
Function: execute
def execute(command, mailtext):
    process = Popen(command, stdin=PIPE)
    process.stdin.write(mailtext)
    process.stdin.close()

    result = None
    while result is None:
        result = process.poll()
        time.sleep(.1)
    if result != 0:
        print "unable to send reply, subprocess exited with\
                exit code %d\nPress return to continue" % result
        sys.stdin.readline()

Example 57

Project: lamvery Source File: utils.py
Function: confirm_overwrite
def confirm_overwrite(path):
    ret = True
    if os.path.exists(path):
        print('Overwrite {}? [y/n]: '.format(path))
        y_n = sys.stdin.readline()
        if not y_n.startswith('y'):
            ret = False
    return ret

Example 58

Project: medicare-demo Source File: colorlog.py
Function: main
def main():
    while True:
        line=sys.stdin.readline()
        if len(line)==0: break
        line=line.strip("\n")
        line=prefix+line
        line = colorize(line)
        print line

Example 59

Project: pttdm Source File: pttdm.py
def slide(*args, **kwargs):
    def wrap(f):
        @wraps(f)
        def wrapped_f():
            print_func(f)
            sys.stdin.readline()
            if kwargs.get('executable', False):
                print_func_result(f)
                sys.stdin.readline()
        return wrapped_f
    if len(args) == 1 and callable(args[0]):
        # No arguments, this is the decorator
        # Set default values for the arguments
        return wrap(args[0])
    else:
        # This is just returning the decorator
        return wrap

Example 60

Project: PyPunchP2P Source File: client.py
    def chat_symmetric(self):
        """
        Completely rely on relay server(TURN)
        """
        def send_msg_symm(sock):
            while True:
                data = 'msg ' + sys.stdin.readline()
                sock.sendto(data, self.master)

        def recv_msg_symm(sock):
            while True:
                data, addr = sock.recvfrom(1024)
                if addr == self.master:
                    sys.stdout.write(data)
        Thread(target=send_msg_symm, args=(self.sockfd,)).start()
        Thread(target=recv_msg_symm, args=(self.sockfd,)).start()

Example 61

Project: offlineimap Source File: Machine.py
Function: get_pass
    def getpass(s, accountname, config, errmsg=None):
        if errmsg:
            s._printData(s.logger.warning,
              'getpasserror', "%s\n%s"% (accountname, errmsg),
              False)

        s._log_con_handler.acquire() # lock the console output
        try:
            s._printData(s.logger.info, 'getpass', accountname)
            return (sys.stdin.readline()[:-1])
        finally:
            s._log_con_handler.release()

Example 62

Project: PyAutoC Source File: findertools.py
def _test():
    import EasyDialogs
    print 'Original findertools functionality test...'
    print 'Testing launch...'
    pathname = EasyDialogs.AskFileForOpen('File to launch:')
    if pathname:
        result = launch(pathname)
        if result:
            print 'Result: ', result
        print 'Press return-',
        sys.stdin.readline()
    print 'Testing print...'
    pathname = EasyDialogs.AskFileForOpen('File to print:')
    if pathname:
        result = Print(pathname)
        if result:
            print 'Result: ', result
        print 'Press return-',
        sys.stdin.readline()
    print 'Testing copy...'
    pathname = EasyDialogs.AskFileForOpen('File to copy:')
    if pathname:
        destdir = EasyDialogs.AskFolder('Destination:')
        if destdir:
            result = copy(pathname, destdir)
            if result:
                print 'Result:', result
            print 'Press return-',
            sys.stdin.readline()
    print 'Testing move...'
    pathname = EasyDialogs.AskFileForOpen('File to move:')
    if pathname:
        destdir = EasyDialogs.AskFolder('Destination:')
        if destdir:
            result = move(pathname, destdir)
            if result:
                print 'Result:', result
            print 'Press return-',
            sys.stdin.readline()
    print 'Testing sleep...'
    if EasyDialogs.AskYesNoCancel('Sleep?') > 0:
        result = sleep()
        if result:
            print 'Result:', result
        print 'Press return-',
        sys.stdin.readline()
    print 'Testing shutdown...'
    if EasyDialogs.AskYesNoCancel('Shut down?') > 0:
        result = shutdown()
        if result:
            print 'Result:', result
        print 'Press return-',
        sys.stdin.readline()
    print 'Testing restart...'
    if EasyDialogs.AskYesNoCancel('Restart?') > 0:
        result = restart()
        if result:
            print 'Result:', result
        print 'Press return-',
        sys.stdin.readline()

Example 63

Project: reddit-bots Source File: reddit-self-posts-copier.py
    def submit(self, submission, modhash):
        self.submitted.append(submission['id'])
        try:
            open(self.options.save_file, 'a').write('\n' + submission['id'])
        except IOError:
            if self.options.verbose:
                print('Problem saving submission %s.' % submission['id'])
        
        submission_title = unescape_entities(submission['title'])
        
        if self.options.manual:
            normal_title = title.get()
            title.set('[!] ' + normal_title);
            print('Submit %r from %s (Y/N)?' % (submission_title, submission['subreddit']))
            approved = stdin.readline()[0].upper()
            title.set(normal_title)
            if approved != 'Y':
                return
        elif self.options.verbose:
            print('Submitting %r from %s.' % (submission_title, submission['subreddit']))
        
        params = urlparse.urlencode({
            'title': submission_title,
            'text': unescape_entities(submission['selftext']),
            'kind': 'self',
            'sr': self.options.target,
            'uh': modhash
        })
        
        request = urlrequest.Request(self.options.submit_url, params, USER_AGENT)
        response = request_json(request)
        
        if self.options.verbose:
            if '.error.BAD_CAPTCHA.field-captcha' in str(response):
                print('Could not submit the post because a CAPTCHA was required.')
            elif '.error.RATELIMIT.field-ratelimit' in str(response):
                print('Could not submit the post because a submission rate limit was triggered.')
            elif response is None:
                print('Problem submitting the post.' + self._maybe_down_message)

Example 64

Project: buildtools-BaseTools Source File: InstallPkg.py
Function: main
def Main(Options = None):
    ContentZipFile, DistFile = None, None

    try:
        DataBase = GlobalData.gDB        
        CheckEnvVariable()
        WorkspaceDir = GlobalData.gWORKSPACE
        if not Options.PackageFile:
            Logger.Error("InstallPkg", OPTION_MISSING, ExtraData=ST.ERR_SPECIFY_PACKAGE)
        
        #
        # unzip dist.pkg file
        #
        DistPkg, Dep, ContentZipFile, DpPkgFileName = UnZipDp(WorkspaceDir, Options, DataBase)

        #
        # PackageList, ModuleList record the information for the meta-data
        # files that need to be generated later
        #
        PackageList = []
        ModuleList = []
        DistPkg.PackageSurfaceArea = GetPackageList(DistPkg, Dep, WorkspaceDir, Options, 
                                                    ContentZipFile, ModuleList, PackageList)

        DistPkg.ModuleSurfaceArea = GetModuleList(DistPkg, Dep, WorkspaceDir, ContentZipFile, ModuleList)       
        
        
        GenToolMisc(DistPkg, WorkspaceDir, ContentZipFile)
        
        #
        # copy "Distribution File" to directory $(WORKSPACE)/conf/upt
        #
        DistFileName = os.path.split(DpPkgFileName)[1]
        DestDir = os.path.normpath(os.path.join(WorkspaceDir, GlobalData.gUPT_DIR))
        CreateDirectory(DestDir)
        DestFile = os.path.normpath(os.path.join(DestDir, DistFileName))
        if os.path.exists(DestFile):
            FileName, Ext = os.path.splitext(DistFileName)
            NewFileName = FileName + '_' + DistPkg.Header.GetGuid() + '_' + DistPkg.Header.GetVersion() + Ext
            DestFile = os.path.normpath(os.path.join(DestDir, NewFileName))
            if os.path.exists(DestFile):
                #
                # ask for user input the new file name
                #
                Logger.Info( ST.MSG_NEW_FILE_NAME_FOR_DIST)
                Input = stdin.readline()
                Input = Input.replace('\r', '').replace('\n', '')
                DestFile = os.path.normpath(os.path.join(DestDir, Input))
        copyfile(DpPkgFileName, DestFile)
        NewDpPkgFileName = DestFile[DestFile.find(DestDir) + len(DestDir) + 1:]

        #
        # update database
        #
        Logger.Quiet(ST.MSG_UPDATE_PACKAGE_DATABASE)
        DataBase.AddDPObject(DistPkg, NewDpPkgFileName, DistFileName, 
                       DistPkg.Header.RePackage)
        
        ReturnCode = 0
        
    except FatalError, XExcept:
        ReturnCode = XExcept.args[0]
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(),
                platform) + format_exc())
    except KeyboardInterrupt:
        ReturnCode = ABORT_ERROR
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(),
                platform) + format_exc())
    except:
        ReturnCode = CODE_ERROR
        Logger.Error(
                    "\nInstallPkg",
                    CODE_ERROR,
                    ST.ERR_UNKNOWN_FATAL_INSTALL_ERR % Options.PackageFile,
                    ExtraData=ST.MSG_SEARCH_FOR_HELP,
                    RaiseError=False
                    )
        Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(),
            platform) + format_exc())

    finally:
        Logger.Quiet(ST.MSG_REMOVE_TEMP_FILE_STARTED)
        if DistFile:
            DistFile.Close()
        if ContentZipFile:
            ContentZipFile.Close()
        if GlobalData.gUNPACK_DIR:
            rmtree(GlobalData.gUNPACK_DIR)
            GlobalData.gUNPACK_DIR = None
        Logger.Quiet(ST.MSG_REMOVE_TEMP_FILE_DONE)

    if ReturnCode == 0:
        Logger.Quiet(ST.MSG_FINISH)
    
    return ReturnCode

Example 65

Project: python-apt Source File: progress.py
Function: media_change
    def mediaChange(self, medium, drive):
	print "Please insert medium %s in drive %s" % (medium, drive)
	sys.stdin.readline()

Example 66

Project: linear-book-scanner Source File: vsane.py
def main(argv):
  pygame.init()
  h = pygame.display.Info().current_h * 4 // 5
  pygame.display.set_mode((h * 16 // 9, h))
  pygame.display.set_caption("Waiting for data...")
  while True:
    a, b = sys.stdin.readline(), sys.stdin.readline()
    if not a or not b:
      break
    screen = pygame.display.get_surface()
    screen.fill((70, 120, 173))
    sys.stdout.write(a + b)
    sys.stdout.flush()
    img_a, img_b = process_image(h, a.strip()), process_image(h, b.strip())
    w2 = screen.get_width() // 2
    epsilon = screen.get_width() // 200
    screen.blit(img_a, (w2 - img_a.get_width() - epsilon, 0))
    screen.blit(img_b, (w2 + epsilon, 0))
    pygame.display.set_caption("%s | %s" % (a.strip(), b.strip()))
    pygame.display.update()

Example 67

Project: airxploit Source File: console.py
    def main_menu(self):
        """
        print the main menu
        """
        print ">>> ",
        
        cmd = sys.stdin.readline()
        cmd = cmd.strip()
        matched_show = re.match(r"^show\s?(.*)", cmd)
        
        if cmd == "help" or cmd == "":
            self.list_commands()
        elif cmd == "exit" or cmd == "quit":
            self.run_away()
        elif matched_show:
            self.list_plugins(matched_show.group(1))
        else:    
            try:
                cmd_successfull = [
                                   "g0t it!",
                                   "yeah",
                                   "ok",
                                   "ack",
                                   "yes, master.",
                                   ":)"
                                   ]
                self._controller.run_command(cmd)            
                print "<<< " + cmd_successfull[ random.randint(0, len(cmd_successfull)-1)]
            except airxploit.cuemup.not_a_command.NotACommand, e:
                print "<<< Unknown command"
            except airxploit.feckup.not_an_event.NotAnEvent, e:
                print "<<< " + str(e)
            except airxploit.feckup.big_shit.BigShit, e:
                print "<<< " + str(e)
                logging.error(str(e))
            except airxploit.feckup.plugin_init.PluginInit, e:
                print "<<< " + str(e)
                logging.error(str(e))
            except TypeError, e:
                bad_command = [
                               "Ouch!",
                               "Wrong, wrong, wrong...",
                               "Eh... what?",
                               "lol"
                               ]
                print "<<< " + bad_command[ random.randint(0, len(bad_command)-1)]
                print str(e)
                logging.error(str(e))
        print "\n"        
        self.main_menu()

Example 68

Project: imago Source File: capture.py
def main():
    """Parse the argument and setup the UI."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-c', '--cmd', dest='cmd', action='store_true',
                    help="take commands from stdin")
    parser.add_argument('-d', type=int, default=0,
                        help="video device id")
    parser.add_argument('-a', type=int, default=0,
                        help="take picture automaticaly every A seconds")
    parser.add_argument('-r', type=int, nargs=2, default=[640, 480],
                        help="set camera resolution")
    args = parser.parse_args()

    res=(args.r[0], args.r[1])
    capture = Capture(args.d, res)


    if args.cmd:
        def enqueue_input(queue):
            for line in iter(sys.stdin.readline, b''):
                queue.put(line)

        q = Queue()
        t = Thread(target=enqueue_input, args=(q,))
        t.daemon = True 
        t.start()
        
        capture.live(q)

        clock = pygame.time.Clock()

        while True:
            try:
                line = q.get_nowait() # or q.get(timeout=.1)
            except Empty:
                pass
            else: 
                if line == "take\n":
                    capture.take()
                elif line == "exit\n":
                    break
            clock.tick(10)

    else:
        capture.live(None)
        if args.a > 0:
            capture.auto(args.a)
        else:
            capture.manual()

    del capture

Example 69

Project: cyberflex-shell Source File: cyberflex-shell.py
    def cmd_runscript(self, filename, ask = True):
        "Run an APDU script from a file"
        fh = file(filename)
        
        doit = not ask
        #ignored_SWs = ["\x62\x82"]
        ignored_SWs = []
        
        for line in fh:
            if line[:2] == "//" or line[:1] == "#":
                continue
            
            if not doit:
                print "?? %s" % line.strip()
                print "Execute? (Yes/No/All/Exit) ",
                answer = sys.stdin.readline()
                if answer[0].lower() in ('y', "\n"):
                    pass
                elif answer[0].lower() == 'n':
                    continue
                elif answer[0].lower() == 'a':
                    doit = True
                elif answer[0].lower() == 'e':
                    return
                else:
                    continue
            
            self.parse_and_execute(line)
            
            if self.card.sw_changed and not self.card.check_sw(self.card.last_sw) \
                    and self.card.last_sw not in ignored_SWs:
                
                print "SW(%s) was not OK. Ignore (i) or Abort (a)? " % binascii.hexlify(self.card.last_sw),
                answer = sys.stdin.readline()
                if answer[0].lower() in ('i', "\n"):
                    pass
                elif answer[0].lower() == 'a':
                    return
                elif answer[0] == 'S':
                    ignored_SWs.append(self.card.last_sw)
                    pass
                else:
                    return

Example 70

Project: turbulenz_tools Source File: exportevents.py
Function: parse_args
def _parse_args():
    parser = argparse.ArgumentParser(description="Export event logs and anonymised user information of a game.")
    parser.add_argument("-v", "--verbose", action="store_true", help="verbose output")
    parser.add_argument("-s", "--silent", action="store_true", help="silent running")
    parser.add_argument("--version", action='version', version=__version__)

    parser.add_argument("-u", "--user", action="store",
                        help="Hub login username (will be requested if not provided)")
    parser.add_argument("-p", "--password", action="store",
                        help="Hub login password (will be requested if not provided)")

    parser.add_argument("-t", "--type", action="store", default=DATATYPE_DEFAULT,
                        help="type of data to download, either events or users (defaults to " + DATATYPE_DEFAULT + ")")
    parser.add_argument("-d", "--daterange", action="store", default=TODAY_START,
                        help="individual 'yyyy-mm-dd' or range 'yyyy-mm-dd : yyyy-mm-dd' of dates to get the data " \
                             "for (defaults to today)")
    parser.add_argument("-o", "--outputdir", action="store", default="",
                        help="folder to output the downloaded files to (defaults to current directory)")

    parser.add_argument("-w", "--overwrite", action="store_true",
                        help="if a file to be downloaded exists in the output directory, " \
                             "overwrite instead of skipping it")
    parser.add_argument("--indent", action="store_true", help="apply indentation to the JSON output")
    parser.add_argument("--hub", default=HUB_URL, help="Hub url (defaults to https://hub.turbulenz.com/)")

    parser.add_argument("project", metavar='project_slug', help="Slug of Hub project you wish to download from")

    args = parser.parse_args(argv[1:])

    if args.silent:
        basicConfig(level=CRITICAL)
    elif args.verbose:
        basicConfig(level=INFO)
    else:
        basicConfig(level=WARNING)

    if not PROJECT_SLUG_PATTERN.match(args.project):
        error('Incorrect "project" format')
        exit(-1)

    username = args.user
    if not username:
        print 'Username: ',
        username = stdin.readline()
        if not username:
            error('Login information required')
            exit(-1)
        username = username.strip()
        args.user = username

    if not USERNAME_PATTERN.match(username):
        error('Incorrect "username" format')
        exit(-1)

    if not args.password:
        try:
            args.password = getpass()
        except GetPassWarning:
            error('Echo free password entry unsupported. Please provide a --password argument')
            return -1

    if args.type not in ['events', 'users']:
        error('Type must be one of \'events\' or \'users\'')
        exit(1)

    if isinstance(args.daterange, int):
        args.daterange = DateRange(args.daterange)
    else:
        args.daterange = DateRange.parse(args.daterange)

    return args

Example 71

Project: conary Source File: server.py
def addUser(netRepos, userName, admin = False, mirror = False):
    if os.isatty(0):
        from getpass import getpass

        pw1 = getpass('Password:')
        pw2 = getpass('Reenter password:')

        if pw1 != pw2:
            print "Passwords do not match."
            return 1
    else:
        # chop off the trailing newline
        pw1 = sys.stdin.readline()[:-1]

    # never give anonymous write access by default
    write = userName != 'anonymous'
    # if it is mirror or admin, it needs to have its own role
    roles = [ x.lower() for x in netRepos.auth.getRoleList() ]
    if mirror or admin:
        assert (userName.lower() not in roles), \
               "Can not add a new user matching the name of an existing role"
        roleName = userName
    else: # otherwise it has to be ReadAll or WriteAll
        roleName = "ReadAll"
        if write:
            roleName = "WriteAll"
    if roleName.lower() not in roles:
        netRepos.auth.addRole(roleName)
        # group, trovePattern, label, write
        netRepos.auth.addAcl(roleName, None, None, write = write)
        netRepos.auth.setMirror(roleName, mirror)
        netRepos.auth.setAdmin(roleName, admin)
    netRepos.auth.addUser(userName, pw1)
    netRepos.auth.addRoleMember(roleName, userName)

Example 72

Project: pyff Source File: eyetracker.py
Function: calibrate
    def calibrate(self):
        """Call calibration for the eye tracker."""

        print("Perform calibration. Press Enter to start calibration")
        sys.stdin.readline()
        result = api.PerformCalibration(5, 0, False, False, True, 0, True, True, True, hex2dec('C0C0C0'), hex2dec('0000FF') , "")
        if(result == 0):
            self.logger.debug("PerformCalibration call succeed")
            status = c_int()
            improve = c_short()
            #Wait for CalibrationDone without Timeout
            result = api.WaitForCalibrationResult(byref(status), byref(improve), -1)
            if(result == 0):
                str_result = 'Calibration Result: ' + calibrationStatus[status.value]
                str_improve = 'Improve: ' + str(improve.value)
                print str_result
                print str_improve
                self.logger.debug(str_result)
                self.logger.debug(str_improve)
            else:
                self.logger.debug('WaitForCalibrationResult call failed')
            print("Calibration Complete")
            return True
        else:
            self.logger.debug("PerformCalibration call failed")
        return False

Example 73

Project: LTLMoP Source File: _SensorHandler.py
Function: check_for_input
    def checkForInput(self):
        return sys.stdin.readline()

Example 74

Project: pwn_plug_sources Source File: handler.py
def do():
 global remote
 global connectionid
 line = "just dot have an empty line"
 path = ""
 remote = "00:00:00:00:00:00"
 connectionid = "0"
 while len(line) > 2:
  line = sys.stdin.readline()
  if len(line) < 2:
   break
  log(2, "header_line: " + line)
  line = string.rstrip(line, "\n")
  tmp = line.split(None, 1)
  if tmp[0].find("command:") == 0:
   command = tmp[1]
  if tmp[0].find("friendly:") == 0:
   friendly = tmp[1]	
  if tmp[0].find("length:") == 0:
   length = tmp[1]
  if tmp[0].find("path:") == 0:
   path = tmp[1]
  if tmp[0].find("target:") == 0:
   target = tmp[1]
  if tmp[0].find("type:") == 0:
   type = tmp[1]
  if tmp[0].find("local:") == 0:
   local = tmp[1]
  if tmp[0].find("remote:") == 0:
   remote = tmp[1]
  if tmp[0].find("filename:") == 0:
   filename = tmp[1]
  if tmp[0].find("description:") == 0:
   description = tmp[1]
  if tmp[0].find("connection_id:") == 0:
   connectionid = tmp[1]
  if tmp[0].find("count:") == 0:
   count = tmp[1]
  if tmp[0].find("data_type:") == 0:
   datatype = tmp[1]
  if tmp[0].find("server_session:") == 0:
   serversession = tmp[1]

 # -- PROCESS commands --

 # -- PUT --
 if command == "put":
  fullpath = BASEPATH + path + "/" + filename
  log(1, "PUT " + fullpath + " " + length + " Bytes\n")
  if len(filename) == 1:
   clean_exit(2)
  # create
  if datatype == "1":
   if os.access(fullpath, os.F_OK) and OVERWRITE == 0:
    log(1, "PUT " + fullpath + " exits and overwrite is disabled\n")
    clean_exit(2)
   fp = open(fullpath, "w")
   if fp == -1:
    log(1, "PUT " + fullpath + " can't be created/overwritten\n")
    clean_exit(2)
   buf = sys.stdin.read(int(length))
   fp.write(buf)
   fp.close()
   log(1, "PUT " + fullpath + " saved\n")
   clean_exit(1)
  # delete file/directory
  else:
   if not os.access(fullpath, os.F_OK) or OVERWRITE == 0:
    log(1, "PUT (delete) " + fullpath + " no such file or no permissions\n")
    clean_exit(2)
   else:
    try:
     os.unlink(fullpath)
     log(1, "PUT (delete)" + fullpath + " deleted\n")
    except OSError:
     os.rmdir(fullpath)
     log(1, "PUT (delete)" + fullpath + " deleted\n")
    clean_exit(1)

 # -- GET --
 elif command == "get":
  # folder listing
  if type == "x-obex/folder-listing":
   log(1, "GET listing of folder: " + BASEPATH + path + "\n")
   if os.access(BASEPATH + path, os.F_OK) == -1:
    log(1, "GET " + BASEPATH + path + " can't be accessed\n")
   buf = "<?xml version=\"1.0\"?>\n" + "<!DOCTYPE folder-listing SYSTEM \"obex-folder-listing.dtd\">\n" + "<folder-listing version=\"1.0\">\n"
   lsout = os.popen("ls -la " + BASEPATH + path, "r")
   line = "no empty line"
   while len(line) > 0:
    line = lsout.readline()
    line = string.rstrip(line, "\n")
    parts = line.split(None, 8)
    if len(parts) > 3:
     if parts[0].find("d") == 0:
      if parts[8] == "..":
       buf = buf + "<partenfolder/>\n"
      elif parts[8] != ".":
       buf = buf + "<folder name=\"" + parts[8] + "\" size=\"" + parts[4] + "\"/>\n"
     elif parts[0].find("-") == 0:
      buf = buf + "<file name=\"" + parts[8] + "\" size=\"" + parts[4] + "\"/>\n"
   buf = buf + "</folder-listing>"
   print "length: " + str(len(buf)) + "\n"
   log(2, "GET listing length " + str(len(buf)) + "\n")
   print buf
   log(2, "GET listing: " + buf + "\n");
   clean_exit(1)

  # regular get
  fullpath = BASEPATH + path + "/" + filename
  log(1, "GET " + fullpath + "\n")
  fp = open(fullpath)
  if fp == -1:
   log(1, "GET can't open " + fullpath + "\n")
   clean_exit(2)
  fp.seek(0, 2)
  fpsize = fp.tell()
  fp.seek(0, 0)
  buf = fp.read(fpsize)
  print "length: " + str(fpsize) + "\n"
  log(1, "GET " + fullpath + " " + str(fpsize) + " Bytes\n")
  print buf
  fp.close()
  clean_exit(1)

 # -- CONNECTION STUFF --
 elif command == "connect":
  log(1, "CONNECT\n")
  clean_exit(1)
 elif command == "disconnect":
  log(1, "DISCONNECT\n")
  clean_exit(1)
 elif command == "accept":
  res = dialog("SOBEXSRV", "incoming connection from: " + remote, "")
  log(1, "ACCEPT at security level " + str(res) + "\n")
  clean_exit(res)
 #
 # need to implement mkdir
 #
 elif command == "setpath":
  clean_exit(1)

Example 75

Project: narcissus Source File: amqp_log_sender.py
Function: main
def main():
    options, args = parser.parse_args()

    options.targets = [t.strip() for t in options.targets.split(',')]

    # Create connection and session
    session_dicts = []
    for target in options.targets:
        print "Attempting to setup connection with", target
        try:
            socket = connect(target, 5672)
            connection = Connection(
                socket, username='guest', password='guest',
            )
            connection.start(timeout=10000)
            session = connection.session(str(uuid4()))

            # Setup routing properties
            print "Talking to %s on topic %s" % (target, options.topic)
            properties = session.delivery_properties(routing_key=options.topic)
            session_dicts.append({
                'target': target,
                'socket': socket,
                'connection': connection,
                'session': session,
                'properties': properties,
            })
            print "    Created target", target
        except Exception as e:
            print "    Failed to create target", target
            print str(e)
            import traceback
            traceback.print_exc()

    print "Entering mainloop"
    print "Sending to", ",".join([d['target'] for d in session_dicts])
    while True:
        msg = sys.stdin.readline()
        if not msg:
            break

        if options.debug:
            print "[sending]", msg

        for d in session_dicts:
            d['session'].message_transfer(
                destination='amq.topic',
                message=Message(d['properties'], msg))

    # Close session
    for d in session_dicts:
        d['session'].close(timeout=10)

Example 76

Project: pyadb Source File: whatsapp.py
def main():
    
    adb = ADB()
    
    # set ADB path
    adb.set_adb_path('~/android-sdk-linux/platform-tools/adb')
    
    print "[+] Using PyADB version %s" % adb.pyadb_version()
    
    # verity ADB path
    print "[+] Verifying ADB path...",
    if adb.check_path() is False:
        print "ERROR"
        exit(-2)
    print "OK"
    
    # print ADB Version
    print "[+] ADB Version: %s" % adb.get_version()
    
    print ""
    
    # restart server (may be other instances running)
    print "[+] Restarting ADB server..."
    adb.restart_server()
    if adb.lastFailed():
        print "\t- ERROR\n"
        exit(-3)
    
    # get detected devices
    dev = 0
    while dev is 0:
        print "[+] Detecting devices..." ,
        error,devices = adb.get_devices()
    
        if error is 1:
            # no devices connected
            print "No devices connected"
            print "[+] Waiting for devices..."
            adb.wait_for_device()
            continue
        elif error is 2:
            print "You haven't enought permissions!"
            exit(-3)
            
        print "OK"
        dev = 1

    # this should never be reached
    if len(devices) == 0:
        print "[+] No devices detected!"
        exit(-4)

    # show detected devices
    i = 0
    for dev in devices:
        print "\t%d: %s" % (i,dev)
        i += 1
    
    # if there are more than one devices, ask to the user to choose one of them
    if i > 1:
        dev = i + 1
        while dev < 0 or dev > int(i - 1):
            print "\n[+] Select target device [0-%d]: " % int(i - 1) ,
            dev = int(stdin.readline())
    else:
        dev = 0
    
    # set target device
    try:
        adb.set_target_device(devices[dev])
    except Exception,e:
        print "\n[!] Error:\t- ADB: %s\t - Python: %s" % (adb.get_error(),e.args)
        exit(-5)

    print "\n[+] Using \"%s\" as target device" % devices[dev]
    
    # check if 'su' binary is available
    print "[+] Looking for 'su' binary: ",
    supath = adb.find_binary("su")

    if supath is not None:
        print "%s" % supath
    else:
        print "Error: %s" % adb.get_error()

    # 'su' binary has been found
    if supath is not None:
        print "[+] Checking if 'su' binary can give root access:"
        rootid = adb.shell_command('%s -c id' % supath)
        if adb.lastFailed() is False and 'root' in rootid.replace('(',')').split(')'): # it can provide root privileges
            print "\t- Yes"
            get_whatsapp_root(adb,supath)
        else: # only have normal-user 
            print "\t- No: %s" % adb.get_error()
            get_whatsapp_nonroot(adb)
    else:
        get_whatsapp_nonroot(adb)

    exit(0)

Example 77

Project: vivisect Source File: rar.py
    def iterRar4Files(self):

        if self.salt != None and self.aes == None:
            raise PasswordRequired()

        while True:
            hdr = self.read(7)
            crc,ctype,cflags,csize = struct.unpack('<HBHH', hdr)
            body = self.read(csize - 7)

            rar4 = Rar4Block()
            rar4.vsParse( hdr )

            #if self.salt != None:
                #remain = csize % 16
                #if remain:
                    #pad = self.read( 16 - remain )
                    #print 'PAD',pad.encode('hex')

            cls = rar4blocks.get(rar4.HEAD_TYPE)
            if cls != None:
                rar4 = cls()
                rar4.vsParse(hdr+body)

            print rar4.tree()
            import sys; sys.stdin.readline()

            #if ctype == MAIN_HEAD and cflags & MHD_PASSWORD:
                #if passwd == None:
                    #raise PasswordRequired()

                #salt30 = fd.read(SIZE_SALT30)
                #iv,key = initIvKey(passwd,salt)
                #self.aes = aesInit(iv,key)
                #break

            if ctype == ENDARC_HEAD:
                break

Example 78

Project: diesel Source File: stdin.py
def create():
    while True:
        line = sys.stdin.readline()
        print 'iter!', line
        fork_from_thread(put, line)

Example 79

Project: buildtools-BaseTools Source File: InstallPkg.py
def GenToolMisc(DistPkg, WorkspaceDir, ContentZipFile):
    ToolObject = DistPkg.Tools
    MiscObject = DistPkg.MiscellaneousFiles
    DistPkg.FileList = []
    FileList = []
    ToolFileNum = 0
    FileNum = 0
    RootDir = WorkspaceDir
    
    #
    # FileList stores both tools files and misc files
    # Misc file list must be appended to FileList *AFTER* Tools file list
    #
    if ToolObject:
        FileList += ToolObject.GetFileList()
        ToolFileNum = len(ToolObject.GetFileList())
        if 'EDK_TOOLS_PATH' in os.environ:
            RootDir = os.environ['EDK_TOOLS_PATH']
    if MiscObject:
        FileList += MiscObject.GetFileList()
    for FileObject in FileList:
        FileNum += 1
        if FileNum > ToolFileNum:
            #
            # Misc files, root should be changed to WORKSPACE
            #
            RootDir = WorkspaceDir
        File = ConvertPath(FileObject.GetURI())
        ToFile = os.path.normpath(os.path.join(RootDir, File))
        if os.path.exists(ToFile):
            Logger.Info( ST.WRN_FILE_EXISTED % ToFile )
            #
            # ask for user input the new file name
            #
            Logger.Info( ST.MSG_NEW_FILE_NAME)
            Input = stdin.readline()
            Input = Input.replace('\r', '').replace('\n', '')
            OrigPath = os.path.split(ToFile)[0]
            ToFile = os.path.normpath(os.path.join(OrigPath, Input))
        FromFile = os.path.join(FileObject.GetURI())
        Md5Sum = InstallFile(ContentZipFile, FromFile, ToFile, DistPkg.Header.ReadOnly, FileObject.GetExecutable())
        DistPkg.FileList.append((ToFile, Md5Sum))

Example 80

Project: estnltk Source File: w2json.py
Function: convert
def convert():
    pars = {"paragraphs": []}
    sens = {"sentences": []}
    sentence = {"words": []}
    l = sys.stdin.readline()    
    rows = 1
    try:
        while l:
            line = l.strip()
            if len(line) > 0:
                word = {"text": line}
                sentence["words"].append(word)
                if line == "</s>":
                    sens["sentences"].append(sentence) 
                    sentence = {"words": []}
            l = sys.stdin.readline()
            rows = rows + 1
    except IndexError:
        sys.stderr.write("Could not read line: \n")
        sys.stderr.write(" %s" % line)
        sys.stderr.write(" %d \n" % rows)
        sys.exit(1)
    pars["paragraphs"].append(sens) 
    print (json.dumps(pars, ensure_ascii = False, indent=4))

Example 81

Project: Harness Source File: framework.py
    def _session_cmd(self, SID=None):

        if not SID:
            return

        try:
            SID = int(SID)
        except:
            self.print_debug("Invalid SID")
            return

        if not SID in self.sessions:
            return

        mod_id = self.sessions[SID].mod_id

        # Find the stdin_q assigned to Module
        job = None
        for name, _job in self.jobs.items():
            if _job[1].mod_id == mod_id:
                job = _job[1]
                stdin_q = job.stdin_q
                break
        else:
            self.print_debug("Cannot match session to module")
            return

        job.enable_print()

        stdin_q.put((SID, "\r\n"))  # Trigger the first callback prompt

        while True:

            _cmd = sys.stdin.readline()
            if _cmd.lower() == "background\n" or _cmd.lower() == "bg\n":
                self.print_debug("sending session to background")
                job.disable_print()
                break;

            if _cmd == "":
                _cmd = "\r\n"
          
            if SID not in self.sessions:
                break

            stdin_q.put((SID, _cmd))
            self.sessions[SID].history.append(_cmd)
        
        job.disable_print()

Example 82

Project: mizuho Source File: code-filter.py
def code_filter():
    '''This function does all the work.'''
    global language, backend
    inline_comment = inline_comments[language]
    blk_comment = block_comments[language]
    if blk_comment:
        blk_comment = (re.escape(block_comments[language][0]),
            re.escape(block_comments[language][1]))
    stag,etag = commenttags[backend]
    in_comment = 0  # True if we're inside a multi-line block comment.
    tag_comment = 0 # True if we should tag the current line as a comment.
    line = sys.stdin.readline()
    while line:
        line = string.rstrip(line)
        line = string.expandtabs(line,tabsize)
        # Escape special characters.
        line = string.replace(line,'&','&amp;')
        line = string.replace(line,'<','<')
        line = string.replace(line,'>','>')
        # Process block comment.
        if blk_comment:
            if in_comment:
                if re.match(r'.*'+blk_comment[1]+r'$',line):
                    in_comment = 0
            else:
                if re.match(r'^\s*'+blk_comment[0]+r'.*'+blk_comment[1],line):
                    # Single line block comment.
                    tag_comment = 1
                elif re.match(r'^\s*'+blk_comment[0],line):
                    # Start of multi-line block comment.
                    tag_comment = 1
                    in_comment = 1
                else:
                    tag_comment = 0
        if tag_comment:
            if line: line = stag+line+etag
        else:
            if inline_comment:
                pos = string.find(line,inline_comment)
            else:
                pos = -1
            if pos >= 0:
                # Process inline comment.
                line = re.sub(r'\b(?P<word>\w+)\b',sub_keyword,line[:pos]) \
                    + stag + line[pos:] + etag
            else:
                line = re.sub(r'\b(?P<word>\w+)\b',sub_keyword,line)
        sys.stdout.write(line + os.linesep)
        line = sys.stdin.readline()

Example 83

Project: buildtools-BaseTools Source File: RmPkg.py
def Main(Options = None):

    try:
        DataBase = GlobalData.gDB        
        if not Options.DistributionFile:
            Logger.Error("RmPkg", 
                         OPTION_MISSING, 
                         ExtraData=ST.ERR_SPECIFY_PACKAGE)
        CheckEnvVariable()
        WorkspaceDir = GlobalData.gWORKSPACE
        #
        # Prepare check dependency
        #
        Dep = DependencyRules(DataBase)
        
        if Options.DistributionFile:
            (Guid, Version, NewDpFileName) = \
            DataBase.GetDpByName(os.path.split(Options.DistributionFile)[1])
            if not Guid:
                Logger.Error("RmPkg", UNKNOWN_ERROR, ST.ERR_PACKAGE_NOT_INSTALLED % Options.DistributionFile)
        else:
            Guid = Options.PackageGuid
            Version = Options.PackageVersion
        #
        # Check Dp existing
        #
        if not Dep.CheckDpExists(Guid, Version):
            Logger.Error("RmPkg", UNKNOWN_ERROR, ST.ERR_DISTRIBUTION_NOT_INSTALLED)
        #
        # Check for Distribution files existence in /conf/upt, if not exist, 
        # Warn user and go on.
        #
        StoredDistFile = os.path.normpath(os.path.join(WorkspaceDir, GlobalData.gUPT_DIR, NewDpFileName))
        if not os.path.isfile(StoredDistFile):
            Logger.Warn("RmPkg", ST.WRN_DIST_NOT_FOUND%StoredDistFile)
            StoredDistFile = None
            
        # 
        # Check Dp depex
        #
        CheckDpDepex(Dep, Guid, Version, WorkspaceDir)

        #
        # Get Current File List
        #
        NewFileList = GetCurrentFileList(DataBase, Guid, Version, WorkspaceDir)

        #
        # Remove all files
        #
        MissingFileList = []
        for (Path, Md5Sum) in DataBase.GetDpFileList(Guid, Version):
            if os.path.isfile(Path):
                if Path in NewFileList:
                    NewFileList.remove(Path)
                if not Options.Yes:
                    #
                    # check whether modified by users
                    #
                    Md5Sigature = md5.new(open(str(Path), 'rb').read())
                    if Md5Sum != Md5Sigature.hexdigest():
                        Logger.Info(ST.MSG_CONFIRM_REMOVE2 % Path)
                        Input = stdin.readline()
                        Input = Input.replace('\r', '').replace('\n', '')
                        if Input.upper() != 'Y':
                            continue
                RemovePath(Path)
            else:
                MissingFileList.append(Path)
        
        for Path in NewFileList:
            if os.path.isfile(Path):
                if (not Options.Yes) and (not os.path.split(Path)[1].startswith('.')):
                    Logger.Info(ST.MSG_CONFIRM_REMOVE3 % Path)
                    Input = stdin.readline()
                    Input = Input.replace('\r', '').replace('\n', '')
                    if Input.upper() != 'Y':
                        continue
                RemovePath(Path)

        #
        # Remove distribution files in /Conf/.upt
        #
        if StoredDistFile is not None:
            os.remove(StoredDistFile)

        #
        # update database
        #
        Logger.Quiet(ST.MSG_UPDATE_PACKAGE_DATABASE)
        DataBase.RemoveDpObj(Guid, Version)
        Logger.Quiet(ST.MSG_FINISH)
        
        ReturnCode = 0
        
    except FatalError, XExcept:
        ReturnCode = XExcept.args[0]        
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + \
                         format_exc())
    except KeyboardInterrupt:
        ReturnCode = ABORT_ERROR
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + \
                         format_exc())
    except:
        Logger.Error(
                    "\nRmPkg",
                    CODE_ERROR,
                    ST.ERR_UNKNOWN_FATAL_REMOVING_ERR,
                    ExtraData=ST.MSG_SEARCH_FOR_HELP,
                    RaiseError=False
                    )
        Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + \
                     format_exc())
        ReturnCode = CODE_ERROR
    return ReturnCode

Example 84

Project: pwn_plug_sources Source File: weevely.py
Function: exec_module
  def execmodule(self, url, pwd, modulestring, os):
    
    modname = modulestring.split('::')[0]
    modargs = modulestring.split('::')[1:]
    
    if not self.modules.has_key(modname):
      print '! Module', modname, 'doesn\'t exist. Print list (-l).'
    else:
      m = self.modules[modname]
      if m.has_key('arguments'):
	argnum=len(self.modules[modname]['arguments'])
	if len(modargs)!=argnum:
	  print '! Module', modname, 'takes exactly', argnum, 'argument/s:', ','.join(self.modules[modname]['arguments'])
	  print '! Description:', self.modules[modname]['description']
	  return
       
      if m.has_key('os'):
	if self.host.os not in self.modules[modname]['os']:
	  print '- Warning: remote system \'' + self.host.os + '\' and module supported system/s \'' + ','.join(self.modules[modname]['os']).strip() + '\' seems not compatible.'
	  print '- Press enter to continue or control-c to exit'
	  sys.stdin.readline()
	
      f = file('modules/' + modname + '.php')
      modargsstring='"'+'","'.join(modargs) + '"'
      modutext = '$ar = Array(' + modargsstring + ');\n' + f.read()
      
      toinject=''
      for i in modutext.split('\n'):
	if len(i)>2 and ( i[:2] == '//' or i[0] == '#'):
	  continue
	toinject=toinject+i+'\n'
      
      try:
	ret = self.host.execute_php(toinject)
      except Exception, e:
	#print '! Module execution failed: ' + str(e) + '.'
	raise
      else:
	print ret

Example 85

Project: tsproxy Source File: tsproxy.py
Function: run
  def run(self):
    global must_exit
    while not must_exit:
      for line in iter(sys.stdin.readline, ''):
        self.ProcessCommand(line.strip())

Example 86

Project: Fastir_Collector Source File: main.py
def main(param_options):
    print r"""
  ______        _   _____ _____
 |  ____|      | | |_   _|  __ \
 | |__ __ _ ___| |_  | | | |__) |
 |  __/ _` / __| __| | | |  _  /
 | | | (_| \__ \ |_ _| |_| | \ \
 |_|  \__,_|___/\__|_____|_|  \_\

     A forensic analysis tool
    """
    import time
    time.sleep(2)

    # check administrative rights
    if ctypes.windll.shell32.IsUserAnAdmin() == 0:
        print "ERROR: FastIR Collector must run with administrative privileges\nPress ENTER to finish..."
        sys.stdin.readline()
        return 0

    set_logger(param_options)

    modules = factory.load_modules(param_options["packages"], param_options["output_dir"])

    for m in modules:
        classes = factory.load_classes(m, param_options["OS"], param_options["release"])
        for cl in classes:
            instance = cl(param_options)
            if "dump" in str(cl):
                for opt in param_options["dump"].split(","):
                    try:
                        if opt in EXTRACT_DUMP:
                            list_method = EXTRACT_DUMP[opt]

                            for method in list_method:
                                if method.startswith(param_options["output_type"]):
                                    getattr(instance, method)()
                    except Exception:
                        param_options["logger"].error(traceback.format_exc())
                continue
            for name, method in inspect.getmembers(cl, predicate=inspect.ismethod):
                if not name.startswith("_"):
                    try:
                        if param_options["output_type"] in name:
                            getattr(instance, name)()
                    except KeyboardInterrupt:
                        return 0
                    except Exception:
                        param_options["logger"].error(traceback.format_exc())

    # Delete all shadow copies created during the acquisition process
    _VSS._close_instances()

    if "mount_letter" in param_options:
        unmount_share(param_options["mount_letter"])

    param_options['logger'].info('Check here %s for yours results' % os.path.abspath(param_options['output_dir']))

Example 87

Project: yandex-tank Source File: agent.py
Function: main
def main():
    fname = os.path.dirname(__file__) + "/_agent.log"
    logging.basicConfig(
        level=logging.DEBUG, filename=fname,
        format='%(asctime)s [%(levelname)s] %(name)s:%(lineno)d %(message)s')

    parser = OptionParser()
    parser.add_option(
        "", "--telegraf", dest="telegraf_path",
        help="telegraf_path",
        default="/tmp/telegraf")
    parser.add_option(
        "", "--host", dest="hostname_path",
        help="telegraf_path",
        default="/usr/bin/telegraf")
    (options, args) = parser.parse_args()

    logger.info('Init')
    try:
        logger.info('Trying to make telegraf executable')
        os.chmod(options.telegraf_path, 484)  # 0o744 compatible with old python versions
    except OSError:
        logger.warning(
            'Unable to set %s access rights to execute.',
            options.telegraf_path, exc_info=True)

    worker = AgentWorker(options.telegraf_path)
    worker.read_startup_config()

    logger.info('Starting AgentWorker: %s', worker)
    worker.start()

    try:
        logger.debug("Check for any stdin command for shutdown")
        cmd = sys.stdin.readline()
        if cmd:
            logger.info("Stdin cmd received: %s", cmd)
            worker.stop()
    except KeyboardInterrupt:
        logger.debug("Interrupted")
        worker.stop()

Example 88

Project: cgat Source File: Rsdb2Html.py
Function: write_body
    def WriteBody( self ):
        """assumes, first line is header, parse until '//', ignore '#'."""

        self.ParseHeader( sys.stdin.readline() )

        self.CreateTable()

        num_lines = 0

        total_lines = 0
        sys.stderr.write("parsing..")
        
        while 1:
            line = sys.stdin.readline()
            
            if not line: break
            if line[0] == "#": continue
            if line[0:2] == "//": break
            
            if not (total_lines % 100) and total_lines > 0:
                sys.stderr.write( ".%i.." % total_lines)
                print self.table 
                self.table.body = []

            total_lines = total_lines + 1

            (columns) = string.split( line[:-1], "\t" )
            
            if not columns:
                break

            if self.mUseIndex:
                col_string = [str(total_lines),] + self.ParseColumns( columns )
            else:
                col_string = self.ParseColumns( columns )
                
            self.table.body.append( col_string ) 
        
        print self.table
        
        sys.stderr.write("done\n")

Example 89

Project: narcissus Source File: zeromq_log_sender.py
Function: main
def main():
    options, args = parser.parse_args()

    options.targets = [t.strip() for t in options.targets.split(',')]

    ctx = zmq.Context()
    s = ctx.socket(zmq.PUB)

    # Create connection and session
    session_dicts = []
    for target in options.targets:
        print "Binding to %r for publishing" % target
        try:
            s.bind(target)
            print "    Created target", target
        except Exception as e:
            print "    Failed to create target", target
            print str(e)
            import traceback
            traceback.print_exc()

    print "Entering mainloop"
    while True:
        msg = sys.stdin.readline()
        if not msg:
            break

        if options.debug:
            print "[sending]", msg

        print options.topic, msg,
        s.send_multipart((options.topic, msg))

    s.close()
    ctx.destroy()

Example 90

Project: smap Source File: gwiki2rst.py
def convert_table(line):
    rows = []
    # remove header formatting
    line = line.replace('*', '')
    while True:
        if line.startswith('||'):
            rows.append(re.split('\|\|', line.strip()))
        else:
            break
        line = sys.stdin.readline()
        if not line: break

    if len(rows):
        row_lengths = [0] * len(rows[0])
        for r in rows:
            row_lengths = map(max, zip(row_lengths, map(len, r)))
        if row_lengths[-1] != 0:
            row_lengths.append(0)

        def make_row(row):
            return '|'.join(map(lambda (x, y): x + (' ' * (y - len(x))), 
                                zip(row, row_lengths)))

        sep = '+'.join(map(lambda x: '-' * x, row_lengths))
        print
        print sep
        print make_row(rows[0])
        print '+'.join(map(lambda x: '=' * x, row_lengths))
        for r in rows[1:]:
            print make_row(r)
            print sep
        print


    

    return len(rows) > 0

Example 91

Project: cgstudiomap Source File: set_name_agi.py
def main(options, arguments):
    # print 'options = %s' % options
    # print 'arguments = %s' % arguments

    # AGI passes parameters to the script on standard input
    stdinput = {}
    while 1:
        input_line = sys.stdin.readline()
        if not input_line:
            break
        line = input_line.strip()
        try:
            variable, value = line.split(':')
        except:
            break
        if variable[:4] != 'agi_':  # All AGI parameters start with 'agi_'
            stderr_write("bad stdin variable : %s\n" % variable)
            continue
        variable = variable.strip()
        value = value.strip()
        if variable and value:
            stdinput[variable] = value
    stderr_write("full AGI environnement :\n")

    for variable in stdinput.keys():
        stderr_write("%s = %s\n" % (variable, stdinput.get(variable)))

    if options.outgoing:
        phone_number = stdinput.get('agi_%s' % options.outgoing_agi_var)
        stdout_write('VERBOSE "Dialed phone number is %s"\n' % phone_number)
    else:
        # If we already have a "True" caller ID name
        # i.e. not just digits, but a real name, then we don't try to
        # connect to OpenERP or geoloc, we just keep it
        if (
                stdinput.get('agi_calleridname')
                and not stdinput.get('agi_calleridname').isdigit()
                and stdinput.get('agi_calleridname').lower()
                not in ['asterisk', 'unknown', 'anonymous']
                and not options.notify):
            stdout_write(
                'VERBOSE "Incoming CallerID name is %s"\n'
                % stdinput.get('agi_calleridname'))
            stdout_write(
                'VERBOSE "As it is a real name, we do not change it"\n')
            return True

        phone_number = stdinput.get('agi_callerid')

    stderr_write('stdout encoding = %s\n' % sys.stdout.encoding or 'utf-8')

    if not isinstance(phone_number, str):
        stdout_write('VERBOSE "Phone number is empty"\n')
        exit(0)
    # Match for particular cases and anonymous phone calls
    # To test anonymous call in France, dial 3651 + number
    if not phone_number.isdigit():
        stdout_write(
            'VERBOSE "Phone number (%s) is not a digit"\n' % phone_number)
        exit(0)

    stdout_write('VERBOSE "Phone number = %s"\n' % phone_number)

    res = False
    # Yes, this script can be used without "-s openerp_server" !
    if options.server:
        if options.ssl:
            stdout_write(
                'VERBOSE "Starting XML-RPC secure request on OpenERP %s:%s"\n'
                % (options.server, str(options.port)))
            protocol = 'https'
        else:
            stdout_write(
                'VERBOSE "Starting clear XML-RPC request on OpenERP %s:%s"\n'
                % (options.server, str(options.port)))
            protocol = 'http'

        sock = xmlrpclib.ServerProxy(
            '%s://%s:%s/xmlrpc/object'
            % (protocol, options.server, str(options.port)))

        try:
            if options.notify and arguments:
                res = sock.execute(
                    options.database, options.user, options.password,
                    'phone.common', 'incall_notify_by_login',
                    phone_number, arguments)
                stdout_write('VERBOSE "Calling incall_notify_by_login"\n')
            else:
                res = sock.execute(
                    options.database, options.user, options.password,
                    'phone.common', 'get_name_from_phone_number',
                    phone_number)
                stdout_write('VERBOSE "Calling get_name_from_phone_number"\n')
            stdout_write('VERBOSE "End of XML-RPC request on OpenERP"\n')
            if not res:
                stdout_write('VERBOSE "Phone number not found in OpenERP"\n')
        except:
            stdout_write('VERBOSE "Could not connect to OpenERP"\n')
            res = False
        # To simulate a long execution of the XML-RPC request
        # import time
        # time.sleep(5)

    # Function to limit the size of the name
    if res:
        if len(res) > options.max_size:
            res = res[0:options.max_size]
    elif options.geoloc:
        # if the number is not found in OpenERP, we try to geolocate
        stdout_write(
            'VERBOSE "Trying to geolocate with country %s and lang %s"\n'
            % (options.country, options.lang))
        res = geolocate_phone_number(
            phone_number, options.country, options.lang)
    else:
        # if the number is not found in OpenERP and geoloc is off,
        # we put 'not_found_name' as Name
        res = not_found_name

    # All SIP phones should support UTF-8...
    # but in case you have analog phones over TDM
    # or buggy phones, you should use the command line option --ascii
    if options.ascii:
        res = convert_to_ascii(res)

    stdout_write('VERBOSE "Name = %s"\n' % res)
    if res:
        if options.outgoing:
            stdout_write('SET VARIABLE connectedlinename "%s"\n' % res)
        else:
            stdout_write('SET CALLERID "%s"<%s>\n' % (res, phone_number))
    return True

Example 92

Project: PyMISP Source File: copy_list.py
def loop_copy():
    while True:
        line = sys.stdin.readline()
        copy(line)

Example 93

Project: GromacsWrapper Source File: control.py
Function: get_input
    def getinput(self):
        print 'python->vmd> ',
        return sys.stdin.readline()

Example 94

Project: cylc Source File: batch_sys_manager.py
    def _jobs_submit_prep_by_stdin(self, job_log_root, job_log_dirs):
        """Prepare job files for submit by reading from STDIN.

        Job files are uploaded via STDIN in remote mode. Modify job
        files' CYLC_DIR for this host. Extract job submission methods
        and job submission command templates from each job file.

        Return a list, where each element contains something like:
        (job_log_dir, batch_sys_name, submit_opts)

        """
        items = [[job_log_dir, None, {}] for job_log_dir in job_log_dirs]
        items_map = {}
        for item in items:
            items_map[item[0]] = item
        handle = None
        batch_sys_name = None
        submit_opts = {}
        job_log_dir = None
        lines = []
        # Get job files from STDIN.
        # Modify CYLC_DIR in job file, if necessary.
        # Get batch system name and batch submit command template from each job
        # file.
        # Write job file in correct location.
        while True:  # Note: "for cur_line in sys.stdin:" may hang
            cur_line = sys.stdin.readline()
            if not cur_line:
                if handle is not None:
                    handle.close()
                break

            if cur_line.startswith(self.LINE_PREFIX_CYLC_DIR):
                old_line = cur_line
                cur_line = "%s'%s'\n" % (
                    self.LINE_PREFIX_CYLC_DIR, os.environ["CYLC_DIR"])
                if old_line != cur_line:
                    lines.append(self.LINE_UPDATE_CYLC_DIR)
            elif cur_line.startswith(self.LINE_PREFIX_BATCH_SYS_NAME):
                batch_sys_name = cur_line.replace(
                    self.LINE_PREFIX_BATCH_SYS_NAME, "").strip()
            elif cur_line.startswith(self.LINE_PREFIX_BATCH_SUBMIT_CMD_TMPL):
                submit_opts["batch_submit_cmd_tmpl"] = cur_line.replace(
                    self.LINE_PREFIX_BATCH_SUBMIT_CMD_TMPL, "").strip()
            elif cur_line.startswith(self.LINE_PREFIX_EXECUTION_TIME_LIMIT):
                submit_opts["execution_time_limit"] = float(cur_line.replace(
                    self.LINE_PREFIX_EXECUTION_TIME_LIMIT, "").strip())
            elif cur_line.startswith(self.LINE_PREFIX_JOB_LOG_DIR):
                job_log_dir = cur_line.replace(
                    self.LINE_PREFIX_JOB_LOG_DIR, "").strip()
                mkdir_p(os.path.join(job_log_root, job_log_dir))
                handle = open(
                    os.path.join(job_log_root, job_log_dir, "job.tmp"), "wb")

            if handle is None:
                lines.append(cur_line)
            else:
                for line in lines + [cur_line]:
                    handle.write(line)
                lines = []
                if cur_line.startswith(self.LINE_PREFIX_EOF + job_log_dir):
                    handle.close()
                    # Make it executable
                    os.chmod(handle.name, (
                        os.stat(handle.name).st_mode |
                        stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
                    # Rename from "*/job.tmp" to "*/job"
                    os.rename(handle.name, handle.name[:-4])
                    try:
                        items_map[job_log_dir][1] = batch_sys_name
                        items_map[job_log_dir][2] = submit_opts
                    except KeyError:
                        pass
                    handle = None
                    job_log_dir = None
                    batch_sys_name = None
                    submit_opts = {}
        return items

Example 95

Project: cylc Source File: batch_sys_manager.py
    def _job_submit_prepare_remote(self, job_file_path):
        """Prepare a remote job file.

        On remote mode, write job file, content from STDIN Modify job
        script's CYLC_DIR for this host. Extract job submission method
        and job submission command template.

        Return (batch_sys_name, batch_sys_submit)

        """
        batch_sys_name = None
        submit_opts = {}
        mkdir_p(os.path.dirname(job_file_path))
        job_file = open(job_file_path + ".tmp", "w")
        while True:  # Note: "for line in sys.stdin:" may hang
            line = sys.stdin.readline()
            if not line:
                sys.stdin.close()
                break
            if line.startswith(self.LINE_PREFIX_CYLC_DIR):
                old_line = line
                line = "%s'%s'\n" % (
                    self.LINE_PREFIX_CYLC_DIR, os.environ["CYLC_DIR"])
                if old_line != line:
                    job_file.write(self.LINE_UPDATE_CYLC_DIR)
            elif line.startswith(self.LINE_PREFIX_BATCH_SYS_NAME):
                batch_sys_name = line.replace(
                    self.LINE_PREFIX_BATCH_SYS_NAME, "").strip()
            elif line.startswith(self.LINE_PREFIX_BATCH_SUBMIT_CMD_TMPL):
                submit_opts["batch_submit_cmd_tmpl"] = line.replace(
                    self.LINE_PREFIX_BATCH_SUBMIT_CMD_TMPL, "").strip()
            elif line.startswith(self.LINE_PREFIX_EXECUTION_TIME_LIMIT):
                submit_opts["execution_time_limit"] = float(line.replace(
                    self.LINE_PREFIX_BATCH_SUBMIT_CMD_TMPL, "").strip())
            job_file.write(line)
        job_file.close()
        os.rename(job_file_path + ".tmp", job_file_path)
        os.chmod(job_file_path, (
            os.stat(job_file_path).st_mode |
            stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
        return batch_sys_name, submit_opts

Example 96

Project: pipetk Source File: pipetk.py
Function: loop
    def loop(self):
        line = sys.stdin.readline()
        while line:
            self.iter(line, 0)
            line = sys.stdin.readline()

Example 97

Project: pwn_plug_sources Source File: plecost-0.2.2-9-beta.py
    def pluginlist_generate(self):
        '''
         Create popular plugin list
        '''
        url_count = 1
        plugin_count = 0
	plugin_cve = CVE()
	if not os.path.isfile(CVE_file): 
		plugin_cve.CVE_list("wordpress")
	stats = os.stat(CVE_file)
	if int(time.time()) - int(stats[8]) > ttl_cvelist : 
		print ""
		print "- CVE file is too old. Reload now?[y/n]:",
		opt = sys.stdin.readline()
		if opt.strip() == "y":
			print ""
			print "- Really?[y/n]:",
			opt = sys.stdin.readline()
			if opt.strip() == "y":
				print ""
				print "- Reloading CVE list... by patient"
				plugin_cve.CVE_list("wordpress")
		else: 
			print "- Maybe later."
	plugin_cve.CVE_loadlist()
	try:
		wp_file = file(PluginList,"w")
	except IOError:
	        print ""
		print "[!] Error opening file: \"" + PluginList + "\""
		print ""
		sys.exit(-1)
	final_countdown = 1
	end = 0
	tmpCount = 0
        while True:
                try:
			wpage = urllib2.urlopen(WPlug_URL+"/"+str(url_count)+"/").read()
		except URLError:
                        print ""
                        print "[!] Web site of plugin is not accesible."
                        print ""
			sys.exit(-1)
		url_count += 1
                wpsoup = BeautifulSoup(wpage)
                if str(wpsoup).find('plugin-block') == -1:
			print "Wordpress plugin list end:"
			break
                for ana in wpsoup.findAll('a'):
                        plugin_url = ana["href"]
                        if plugin_url.find("wordpress.org/extend/plugins/") != -1 and plugin_url.find("popular") == -1 and plugin_url.find("tags") == -1 and plugin_url.find("google.com") == -1 and plugin_url.find(".php") == -1:
				plugin_count += 1
                                if (plugin_url.split('/')[5] != '' ):
					name = plugin_url.split('/')[5]
                                        if len(ana.findNext('li').contents) == 2: 
						version = ana.findNext('li').contents[1]
					if name != "tac":
						cves = plugin_cve.CVE_search(plugin_url.split('/')[5])
					cves_l = ""
					for l in cves:
						cve_a = l+";"
						cves_l = cves_l + cve_a
					if type(version) == unicode:
                        			version = unicode(version, errors='replace')
                    			else:
                        			pass
					u_version = version.encode('utf-8')
					try:
						wp_file.write(name+","+u_version+","+cves_l+"\n")
					except Exception:
						pass
			if int(NumChecks) != -1 and (plugin_count - 1) == int(NumChecks): 
				end = 1
				break
		if end == 1: 
			break
	
		if tmpCount == 1:
			print plugin_count,
			print " plugins stored. Last plugin processed: " + name
			sys.stdout.flush()
			tmpCount = 0
		else:
			tmpCount+=1
	wp_file.close()

Example 98

Project: HunTag Source File: bie12conll.py
Function: main
def main( dontDoBIE1ToBI=False, dontDoNbarToNP=False, dontDoNplusToNbar=False, fields="-2,-1" ) :
    fieldList = map( int, fields.split(",") )
    lengthSet = set()
    line = sys.stdin.readline()
    c=0
    while line :
	c+=1
	a = line.strip().split()
	if len(a)==0 :
	    print
	else :
	    assert len(a)>=2
	    lengthSet.add(len(a))
	    if len(lengthSet)>1 :
		log("Column number differs from those of previous lines:")
		log(line)
		sys.exit(-1)
	    for ind in fieldList :
		a[ind] = transform(a[ind], c, dontDoBIE1ToBI, dontDoNbarToNP, dontDoNplusToNbar)
	    print "\t".join(a)
	line = sys.stdin.readline()

Example 99

Project: orthrus Source File: commands.py
Function: run
    def run(self):

        util.color_print_singleline(util.bcolors.OKGREEN, "\t\t[+] Check Orthrus workspace... ")

        orthrus_root = self._config['orthrus']['directory']
        if not util.validate_job(orthrus_root, self._args.job_id):
            util.color_print(util.bcolors.FAIL, "failed. Are you sure you have done orthrus add --job or passed the "
                                                "right job ID. orthrus show -j might help")
            return False

        util.color_print(util.bcolors.OKGREEN, "done")
        self.job_config = ConfigParser.ConfigParser()
        self.job_config.read(self._config['orthrus']['directory'] + "/jobs/jobs.conf")
        jobId = self._args.job_id

        util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Triaging crashes for job [" \
                         + jobId + "]")

        if not os.path.exists(self._config['orthrus']['directory'] + "/jobs/" + jobId + "/unique/"):
            os.mkdir(self._config['orthrus']['directory'] + "/jobs/" + jobId + "/unique/")
        else:
            util.color_print(util.bcolors.OKGREEN, "[?] Rerun triaging? [y/n]...: ")

            if 'y' not in sys.stdin.readline()[0]:
                return True

            shutil.move(self._config['orthrus']['directory'] + "/jobs/" + jobId + "/unique/",
                        self._config['orthrus']['directory'] + "/jobs/" + jobId + "/unique." \
                        + time.strftime("%Y-%m-%d-%H:%M:%S"))
            os.mkdir(self._config['orthrus']['directory'] + "/jobs/" + jobId + "/unique/")

        if os.path.exists(self._config['orthrus']['directory'] + "/binaries/afl-harden"):
            if not self.triage(jobId, 'harden'):
                return False
        if os.path.exists(self._config['orthrus']['directory'] + "/binaries/afl-asan"):
            if not self.triage(jobId, 'asan'):
                return False

        #Second pass over all exploitable crashes
        exp_path = self._config['orthrus']['directory'] + "/jobs/" + jobId + "/exploitable/"
        uniq_path = self._config['orthrus']['directory'] + "/jobs/" + jobId + "/unique/"
        if os.path.exists(exp_path):
            if not self.triage(jobId, 'all', exp_path, uniq_path):
                return False

        triaged_crashes = os.listdir(uniq_path)
        util.color_print(util.bcolors.OKGREEN, "\t\t[+] Triaged " + str(len(triaged_crashes)) + \
                         " crashes. See {}".format(uniq_path))
        if not triaged_crashes:
            util.color_print(util.bcolors.OKBLUE, "\t\t[+] Nothing to do")
            return True

        return True

Example 100

Project: ddserver Source File: __main__.py
Function: receiver
@require(logger='ddserver.utils.logger:Logger')
def receiver(logger):
  """ Receive and process messages from PowerDNS
  """

  while True:
    # Read a line
    line = sys.stdin.readline()
    if not line:
      break

    # Lex the line
    message = lexer(line)

    # Check if we got a message
    if message is None:
      logger.error('recursor: Unknown tag: %s', line)
      continue

    logger.debug('recursor: Received message: %s', message)

    # Forward the message
    yield message
See More Examples - Go to Next Page
Page 1 Page 2 Selected Page 3