示例#1
0
    def __init__(self):
        import commands
        commands.__init__()

        to_execute = []

        arg_num = 0
        for arg in sys.argv[1:]:
            arg_num += 1
            if not arg.startswith('-') and len(sys.argv) >= arg_num:
                if commands.commands.has_key(sys.argv[arg_num].replace('-','_')):
                    to_execute.append(sys.argv[arg_num].replace('-','_'))
                    
                if commands.commands.has_key("%s_%s" % (
                        '_'.join(to_execute),sys.argv[arg_num].replace('-','_')
                    )):

                    to_execute.append(sys.argv[arg_num].replace('-','_'))

        for cmd_component in to_execute:
            sys.argv.pop(sys.argv.index(cmd_component.replace('_','-')))

        # force default encoding to match the locale encoding (T249)
        reload(sys)
        sys.setdefaultencoding(locale.getpreferredencoding() or 'utf-8')

        # wrap sys.stdout in a locale-aware StreamWriter (#3983)
        sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)

        commands.execute('_'.join(to_execute))
示例#2
0
def main():

    parser = argparse.ArgumentParser(prog='client',
                                     usage='python3 client.py [options]')
    parser.add_argument('--user', help='The username to use for the client')
    parser.add_argument('--server',
                        choices=['prod', 'dev', 'local'],
                        default='local',
                        help="Which server should the client connect to")
    args = parser.parse_args()

    setSettings(args.server)
    sessionToken = str(authREST(args.user))
    client.connect((settings["url"], settings["socket"]))
    client.setblocking(True)

    commands.load(client)

    receiver = threading.Thread(target=socketReceive)
    receiver.start()

    # Authentification
    sendMessage(0, sessionToken.encode("utf-8"))

    while True:
        input()
        importlib.reload(commands)
        commands.load(sendMessage)
        commands.execute()
    receiver.join()
    client.close()
示例#3
0
文件: __init__.py 项目: kanarip/piko
    def __init__(self):
        import commands
        commands.__init__()

        to_execute = []

        arg_num = 0
        for arg in sys.argv[1:]:
            arg_num += 1
            if not arg.startswith('-') and len(sys.argv) >= arg_num:
                if commands.commands.has_key(sys.argv[arg_num].replace(
                        '-', '_')):
                    to_execute.append(sys.argv[arg_num].replace('-', '_'))

                if commands.commands.has_key(
                        "%s_%s" % ('_'.join(to_execute),
                                   sys.argv[arg_num].replace('-', '_'))):

                    to_execute.append(sys.argv[arg_num].replace('-', '_'))

        for cmd_component in to_execute:
            sys.argv.pop(sys.argv.index(cmd_component.replace('_', '-')))

        # wrap sys.stdout in a locale-aware StreamWriter (#3983)
        sys.stdout = codecs.getwriter(locale.getpreferredencoding())(
            sys.stdout)

        try:
            commands.execute('_'.join(to_execute))
        except KeyboardInterrupt, err:
            print >> sys.stderr, _("Interrupted")
            pass
示例#4
0
    def run(self):
        while True:
            readbuffer = self.s_channel.recv(1024).decode("UTF-8",
                                                          errors="ignore")
            temp = string.split(readbuffer, "\n")
            readbuffer = temp.pop()

            for line in temp:
                if "PING" in line:
                    print("Pong back")
                    self.s_channel.send(line.replace("PING", "PONG"))
                    break

                self.user, message = essentials.get_user_and_message(line)
                print(self.user + " typed :" + message)

                if CHECK_LINKS and self.user != IDENTITY:
                    urls = essentials.get_links(message)
                    if urls:
                        print urls
                        self.send_message(
                            essentials.get_site_ratings(urls) + " (myWOT.com)")

                if message.startswith("!"):
                    result = commands.execute(
                        message.split()[0],
                        message.split()[1:],
                        bot_class=self,
                        whitelisted=self.user in WHITELIST,
                    )
                    if result:
                        self.send_message(result)
示例#5
0
    def respond(self, message, participant=None, bot_admin=False):
        if isinstance(participant, Participant):
            bridge = participant.bridge
            if bot_admin != participant.bot_admin:
                bot_admin = participant.bot_admin
        else:
            bridge = None

        return commands.execute(self, message, bot_admin, bridge)
示例#6
0
def dbteardown():
    msg = "destroying database %s\n" % DATABASE_NAME
    sys.stdout.write(msg)
    code, result = execute("dropdb -U%s %s" % (DATABASE_USER, DATABASE_NAME))
    if code:
        m = "{0}\nDatabase already destroyed, or some other error occurred.\n"
        msg = m.format(m)
        sys.stdout.write(msg)
        sys.exit(3)
示例#7
0
def dbTable(module, filename, dropTables=None):
    if dropTables is None:
        dropTables = []
    path = module.__path__[0]
    sql_filepath = os.path.join(path, filename)
    for table in dropTables:
        msg = "dropping table %s\n" % table
        sys.stdout.write(msg)
        c = "echo 'drop table {0}' | psql -U{1} {2}"
        command = c.format(table, DATABASE_USER, DATABASE_NAME)
        execute(command)
    sys.stdout.write("setting up table\n")
    code, result = execute("cat %s | psql -U%s %s" %
                           (sql_filepath, DATABASE_USER, DATABASE_NAME))
    if code:
        m = "{0}\nDatabase either already existed, or some other error "\
            "occurred.\n"
        msg = m.format(m)
        sys.stdout.write(msg)
        sys.exit(2)
示例#8
0
def dbsetup():
    m = "setting up database {0} with user {1}\n"
    msg = m.format(DATABASE_NAME, DATABASE_USER)
    sys.stdout.write(msg)
    code, result = execute("createdb -U%s %s" % (DATABASE_USER, DATABASE_NAME))
    if code:
        m = "{0}\nDatabase either already existed, or some other error "\
            "occurred.\n"
        msg = m.format(m)
        sys.stdout.write(msg)
        sys.exit(1)
示例#9
0
def handler(fileName):
	global speech

	translator = gapi.Translator(speech.lang, 'en-uk')
	try:
		cfileName = psw.convert(fileName)
		phrase = speech.getText(cfileName)
		import os
		os.remove(fileName)
		os.remove(cfileName)
		if phrase!=None:
			phrase = phrase.lower()
			if len(phrase.strip())>0:
				print 'text:',phrase
				#psw.play(speech.getAudio(phrase))
				cmd = translator.translate(phrase).strip().lower()
				print 'cmd:',cmd
				commands.execute(cmd, speech)
	except Exception, e:
		print "Unexpected error:", sys.exc_info()[0], e
示例#10
0
    def bot(self, cmd: str, lower_limit: int, upper_limit: int):
        """
        lower_limit and upper_limit are in minutes
        """
        print('starting bot in 5 seconds')
        self.exit_event.wait(5)

        while not self.exit_event.is_set():
            subcmds = cmd.split(';')
            print(f'[{datetime.now()}] running command', subcmds)
            for sub in subcmds:
                script = self.get_script(sub)
                if script:
                    commands.execute(script)
                else:
                    keyboard.write(sub + '\n')
            duration = random.randrange(lower_limit, upper_limit)
            print(f'[{datetime.now()}] sleeping for {duration / 60} minutes')
            self.exit_event.wait(duration)

        print('stopping bot. goodbye.')
示例#11
0
    def check(self):
        """Process sms messages

        Download and process all sms messages from a Google Voice account.
        this is executed every 15 seconds
        """
        # load the playlist
        self.load_playlist()

        # Parse and act on any new sms messages
        messages = self.voice.sms().messages
        for msg in self.extract_sms(self.voice.sms.html):
            logging.debug(str(msg))
            response = commands.execute(msg['text'], msg['from'])
            if response:
                logging.info('Request: "' + msg['text'] + '" from ' +
                             msg['from'])

                try:
                    if isinstance(response, basestring):
                        self.voice.send_sms(msg['from'], response)
                    else:
                        # Multiple parts, send them with a delay in hopes to avoid
                        # them being received out of order by the recipient.
                        for part in response:
                            self.voice.send_sms(msg['from'], str(part))
                            time.sleep(2)
                except ValidationError as v_error:
                    logging.warn(
                        str(v_error) +
                        ': Error sending sms response (command still executed)',
                        exc_info=1)

                logging.info('Response: "' + str(response) + '"')
            else:
                logging.info('Unknown request: "' + msg['text'] + '" from ' +
                             msg['from'])
                self.voice.send_sms(msg['from'],
                                    cm.sms.unknown_command_response)

        # update the playlist
        self.update_playlist()

        # Delete all messages now that we've processed them
        for msg in messages:
            msg.delete(1)
示例#12
0
def main():
    """Process sms messages

    Download and process all sms messages from a Google Voice account.
    Runs in a loop that is executed every 15 seconds
    """
    # Load playlist from file, notifying users of any of their requests that have now played
    logging.info('loading playlist ' + args.playlist)
    start_commands = False
    while True:
        with open(args.playlist, 'rb') as playlist_fp:
            fcntl.lockf(playlist_fp, fcntl.LOCK_SH)
            playlist = csv.reader(playlist_fp, delimiter='\t')
            songs = []

            for song in playlist:
                logging.debug(song)

                if len(song) < 2 or len(song) > 4:
                    logging.error(
                        'Invalid playlist.  Each line should be in the form: '
                        '<song name><tab><path to song>')
                    logging.warning('Removing invalid entry')
                    print "Error found in playlist"
                    print "Deleting entry:", song
                    continue
                elif len(song) == 2:
                    song.append(set())
                elif len(song) >= 3:
                    # Votes for the song are stored in the 3rd column
                    song[2] = set(song[2].split(','))

                    if len(song) == 4:
                        # Notification of a song being played is stored in the 4th column
                        song_played(song)
                        del song[3]
                        song[2] = set()

                songs.append(song)

            fcntl.lockf(playlist_fp, fcntl.LOCK_UN)

        logging.info('loaded %d songs from playlist', len(songs))
        cm.set_playlist(songs)

        if not start_commands:
            commands.start(cm)
            start_commands = True

        # Parse and act on any new sms messages
        messages = VOICE.sms().messages
        for msg in extract_sms(VOICE.sms.html):
            logging.debug(str(msg))
            response = commands.execute(msg['text'], msg['from'])
            if response:
                logging.info('Request: "' + msg['text'] + '" from ' +
                             msg['from'])

                try:
                    if isinstance(response, basestring):
                        VOICE.send_sms(msg['from'], response)
                    else:
                        # Multiple parts, send them with a delay in hopes to avoid
                        # them being received out of order by the recipient.
                        for part in response:
                            VOICE.send_sms(msg['from'], str(part))
                            time.sleep(2)
                except ValidationError as v_error:
                    logging.warn(
                        str(v_error) +
                        ': Error sending sms response (command still executed)',
                        exc_info=1)

                logging.info('Response: "' + str(response) + '"')
            else:
                logging.info('Unknown request: "' + msg['text'] + '" from ' +
                             msg['from'])
                VOICE.send_sms(msg['from'], cm.sms.unknown_command_response)

        # Update playlist with latest votes
        with open(args.playlist, 'wb') as playlist_fp:
            fcntl.lockf(playlist_fp, fcntl.LOCK_EX)
            writer = csv.writer(playlist_fp, delimiter='\t')
            for song in songs:
                if len(song[2]) > 0:
                    song[2] = ",".join(song[2])
                else:
                    del song[2]
            writer.writerows(songs)
            fcntl.lockf(playlist_fp, fcntl.LOCK_UN)

        # Delete all messages now that we've processed them
        for msg in messages:
            msg.delete(1)

        if args.setup:
            break
        time.sleep(15)
示例#13
0
def exec(event, vk_api):
    text = execute(parse_vk_request(event))
    if text is not None and text != '':
        vk_api.messages.send(random_id=random.randint(0, 10000000),
                             peer_id=event.object.from_id,
                             message=text)
示例#14
0
文件: main.py 项目: wangyinfeng/Kit
def run_cli():
	args = sys.argv[1:]
	context = parser.parse_args(args)
	if context.command == 'run':
		context.args = [sys.argv[0]] + args[1:]
	commands.execute(context)
示例#15
0
import commands
import motorctrl

if __name__ == '__main__':
    motorctrl.startup()
    while True:
        message = raw_input('Enter a command to execute: ')
        if commands.execute(message) == False:
            break
示例#16
0
def main(argv):
    devices = adb.get_attached_devices()

    print """
    !!! Test AntiVirus !!!
    !!! Attenzione:    !!!
    !!! Prima dell'installazione dell'agente, al dispositivo va impedito il libero accesso ad internet. !!!
    """
    print """ prerequisiti:
    1) Telefono connesso in USB,
    2) USB Debugging enabled (settings/developer options/usb debugging)
    3) NESSUNA SIM INSTALLATA <======== NB!!!!!!!!!!!!!!!!!!!!!!!
    4) screen time 2m (settings/display/sleep)
    """

    print "devices connessi:"
    for device in devices:
        print device

    if not devices:
        print "non ci sono device connessi"
    else:

        if len(devices) > 1:
            dev = raw_input("su quale device si vuole eseguire il test? ")
            print "Eseguo il test su %s" % dev

        if len(sys.argv) >= 2:
            serialno = sys.argv[1]

        else:
            serialno = '.*'

        device = AdbClient(serialno=serialno)
        # print 'Args=', (str(sys.argv))
        # operation = sys.argv[1]

        init = raw_input('Init everything? (y/n)')
        if init == "y":
            print "Init!"
            commands.init_device(device.serialno)

        dev = device.serialno

        operation = -1

        while operation != "99":
            print ''
            print '#################       OPERATIONS      #################'
            print 'What operation do you want to perform?'
            print '1  - get new configuration from installed av'
            print '2  - use net RSSM'
            print '3  - use net TPLINK'
            print '4  - disable net'
            print '5  - get wifi network name'
            print '6  - ping google'
            print '7  - test all avs'
            print '8  - test a single av'
            print '9 - is infected?'
            print '10 - got r00t?'
            print '11 - pull file'
            print '12 - push file'
            print ''
            print '#################     INTERNAL TESTS    #################'
            print '20 - test get_server'
            print '21 - test set_server'
            print '22 - test get_client'
            print '23 - test set_client'
            print '24 - test install'
            print '25 - test install_agent'
            print '26 - test uninstall'
            print '27 - test uninstall_agent'
            print '28 - test execute'
            print '29 - test execute_agent'
            print ''
            print '#################          EXIT         #################'
            print '99 - Clean & exit!'

            operation = raw_input()

            if operation == '1':
                print 'Which av you want to retrieve?'
                print str(apk_dataLoader.get_av_list())
                av = raw_input()
                commands.update(av, dev)

            elif operation == '2':
                commands.wifi('open', dev)

            elif operation == '3':
                commands.wifi('av', dev)

            elif operation == '4':
                commands.wifi('disable', dev)

            elif operation == '5':
                print commands.info_wifi_network(dev)

            elif operation == '6':
                if commands.can_ping_google(dev):
                    print "I can ping google"
                else:
                    print "I canNOT ping google"

            elif operation == '7':
                # TODO: andrebbe spostato il do_test
                for av in apk_dataLoader.get_av_list():
                    do_test(device, av)

            elif operation == '8':
                # TODO: andrebbe spostato il do_test
                print 'Which av you want to test?'
                print str(apk_dataLoader.get_av_list())
                av = raw_input()
                do_test(device, av)

            elif operation == '9':
                if commands.check_infection(dev):
                    print "Infected"
                else:
                    print "Clean"

            elif operation == '10':
                if commands.check_su_permissions(dev):
                    print "Root!"
                else:
                    print "Not root :("
            elif operation == '11':
                print '12 - pull file'
                commands.pull(['file.png'], '/sdcard/', 'tmp', dev)
                if os.path.exists('tmp/file.png'):
                    print 'Pull OK!'
                    #debug: time.sleep(20)
                    os.remove('tmp/file.png')
                else:
                    print 'Pull failed!'

            elif operation == '12':
                print '13 - push file'
                commands.push(['file.png'], 'assets', '/sdcard/', dev)

            elif operation == '20':
                print "testvarsrv= " + commands.get_server('testvarsrv')
            elif operation == '21':
                commands.set_server({'testvarsrv': 'testvaluesrv'})
            elif operation == '22':
                print "testvarcli= " + commands.get_client('testvarcli')
            elif operation == '23':
                commands.set_client({'testvarcli': 'testvaluecli'})
            elif operation == '24':
                commands.install('wifi_enabler', dev)
            elif operation == '25':
                commands.install_agent(dev)
            elif operation == '26':
                commands.uninstall('wifi_enabler', dev)
            elif operation == '27':
                commands.uninstall_agent(dev)
            elif operation == '28':
                commands.execute('wifi_enabler', dev)
            elif operation == '29':
                commands.execute_agent(dev)

        print "Operazioni terminate, cleaning time"
        commands.reset_device(dev)
        print "The end"
示例#17
0
    def messages_get(out=0):
        if not out:
            rs = vk.method('messages.get', messages_get_values)
        else:
            rs = vk.method('messages.get', messages_get_values__out)
        # log.debug(rs)

        # Если ничего не пришло
        if not rs['items']:
            return

        item = rs['items'][0]
        message_id = item['id']
        from_user_id = item['user_id']
        message = item['body']

        # Если сообщение пришло из групповой беседы, в chat_id будет число, иначе None
        chat_id = item.get('chat_id')

        # Бот реагирует только на сообщения, начинающиеся с префикса
        if not message.lower().startswith(command_prefix.lower()):
            return

        if chat_id:
            log.debug('From chat #%s from user #%s, message (#%s): "%s"',
                      chat_id, from_user_id, message_id, message)
        else:
            log.debug('From user #%s, message (#%s): "%s"', from_user_id,
                      message_id, message)

        command = message[len(command_prefix):].strip()

        # TODO: для каждой команды отдельный поток создавать
        # Пример: https://www.ibm.com/developerworks/ru/library/l-python_part_9/index.html#N10078
        # только поток нужно без демона использовать, демон указывает что при закрытии главного потока
        # должны и потоки-демоны завершиться, что для текущей задачи не будет правильным

        # Выполнение команды
        try:
            import commands
            message = commands.execute(command)

        except Exception as e:
            log.exception("Error:")

            import traceback
            message = 'При выполнении команды "{}" произошла ошибка: ' \
                      '"{}":\n\n{}'.format(command, e, traceback.format_exc())

        # Если ответа от бота нет
        if not message:
            message = 'Не получилось выполнить команду "{}" :( Попробуй позже повторить :)'.format(
                command)

        log.debug('Message: "%s"', message)

        messages_send_values = {'message': message, 'version': '5.67'}

        # Если сообщение пришло из групповой беседы
        if chat_id:
            messages_send_values['chat_id'] = chat_id
        else:
            messages_send_values['user_id'] = from_user_id

        time.sleep(0.3)
        last_message_bot_id = vk.method('messages.send', messages_send_values)

        if not out:
            messages_get_values['last_message_id'] = last_message_bot_id
        else:
            messages_get_values__out['last_message_id'] = last_message_bot_id
示例#18
0
def text_message(bot, update):
    cmd = update.message.text
    for out in commands.execute(cmd):
        bot.send_message(chat_id=update.message.chat_id, text=out)
示例#19
0
def main():
    """Process sms messages

    Download and process all sms messages from a Google Voice account.
    Runs in a loop that is executed every 15 seconds
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--playlist',
        default=cm.lightshow()['playlist_path'].replace(
            "$SYNCHRONIZED_LIGHTS_HOME", cm.HOME_DIR),
        help='filename with the song playlist, one song per line in the format: '
        '<song name><tab><path to song>')
    parser.add_argument(
        '--setup',
        default=False,
        help=
        'use this option to setup the default configuration file for Google Voice'
    )

    parser.add_argument(
        '--log',
        default='INFO',
        help=
        'Set the logging level. levels:INFO, DEBUG, WARNING, ERROR, CRITICAL')
    args = parser.parse_args()

    logging.basicConfig(
        filename=cm.LOG_DIR + '/music_and_lights.check.dbg',
        format='[%(asctime)s] %(levelname)s {%(pathname)s:%(lineno)d}'
        ' - %(message)s',
        level=logging.INFO)
    # logging levels
    levels = {
        'DEBUG': logging.DEBUG,
        'INFO': logging.INFO,
        'WARNING': logging.WARNING,
        'ERROR': logging.ERROR,
        'CRITICAL': logging.CRITICAL
    }

    level = levels.get(parser.parse_args().log.upper())
    logging.getLogger().setLevel(level)

    # Load playlist from file, notifying users of any of their requests that have now played
    logging.info('loading playlist ' + args.playlist)
    while True:
        with open(args.playlist, 'rb') as playlist_fp:
            fcntl.lockf(playlist_fp, fcntl.LOCK_SH)
            playlist = csv.reader(playlist_fp, delimiter='\t')
            songs = []

            for song in playlist:
                logging.debug(song)

                if len(song) < 2 or len(song) > 4:
                    logging.error(
                        'Invalid playlist.  Each line should be in the form: '
                        '<song name><tab><path to song>')
                    sys.exit()
                elif len(song) == 2:
                    song.append(set())
                elif len(song) >= 3:
                    # Votes for the song are stored in the 3rd column
                    song[2] = set(song[2].split(','))

                    if len(song) == 4:
                        # Notification of a song being played is stored in the 4th column
                        song_played(song)
                        del song[3]
                        song[2] = set()

                songs.append(song)

            fcntl.lockf(playlist_fp, fcntl.LOCK_UN)

        logging.info('loaded %d songs from playlist', len(songs))
        cm.set_songs(songs)

        # Parse and act on any new sms messages
        messages = VOICE.sms().messages
        for msg in extract_sms(VOICE.sms.html):
            logging.debug(str(msg))
            response = commands.execute(msg['text'], msg['from'])
            if response:
                logging.info('Request: "' + msg['text'] + '" from ' +
                             msg['from'])

                try:
                    if isinstance(response, basestring):
                        VOICE.send_sms(msg['from'], response)
                    else:
                        # Multiple parts, send them with a delay in hopes to avoid
                        # them being received out of order by the recipient.
                        for part in response:
                            VOICE.send_sms(msg['from'], str(part))
                            time.sleep(2)
                except:
                    logging.warn(
                        'Error sending sms response (command still executed)',
                        exc_info=1)

                logging.info('Response: "' + str(response) + '"')
            else:
                logging.info('Unknown request: "' + msg['text'] + '" from ' +
                             msg['from'])
                VOICE.send_sms(msg['from'],
                               _CONFIG['unknown_command_response'])

        # Update playlist with latest votes
        with open(args.playlist, 'wb') as playlist_fp:
            fcntl.lockf(playlist_fp, fcntl.LOCK_EX)
            writer = csv.writer(playlist_fp, delimiter='\t')
            for song in songs:
                if len(song[2]) > 0:
                    song[2] = ",".join(song[2])
                else:
                    del song[2]
            writer.writerows(songs)
            fcntl.lockf(playlist_fp, fcntl.LOCK_UN)

        # Delete all messages now that we've processed them
        for msg in messages:
            msg.delete(1)

        if args.setup:
            break
        time.sleep(15)