1

アイテムが存在しないリストをスライスしているときに問題が発生しました。予想どおり、IndexError例外が表示されますが、リスト内のすべてのスライスに対してtryandexceptステートメントを実行するのは好きではありません。 upcomongコードのself.uptime。

コードは次のとおりです。

import datetime
from urllib2 import urlopen, URLError

from core.libs.menu import Colors
from core.libs.request_handler import make_request


class TargetBox(object):
    def __init__(self, url=None):
        self.url = url
        self.cmd = 'whoami;'
        self.cmd += 'id;'
        self.cmd += 'uname -a;'
        self.cmd += 'pwd;'
        self.cmd += 'ls -ld `pwd` | awk \'{print $1}\';'
        self.cmd += 'bash -c "input=\$(uptime); if [[ \$input == *day* ]]; then out=\$(echo \$input | awk \'{print \$3\\" days\\"}\'); if [[ \$input == *min* ]]; then out=\$(echo \\"\$out and \\" && echo \$input | awk \'{print \$5\\" minutes\\"}\'); else out=\$(echo \\"\$out, \\" && echo \$input | awk \'{print \$5}\' | tr -d \\",\\" | awk -F \\":\\" \'{print \$1\\" hours and \\"\$2\\" minutes\\"}\'); fi elif [[ \$input == *min* ]]; then out=\$(echo \$input | awk \'{print \$3\\" minutes\\"}\'); else out=\$(echo \$input | awk \'{print \$3}\' | tr -d \\",\\" | awk -F \\":\\" \'{print \$1\\" hours and \\"\$2\\" minutes\\"}\'); fi; echo \$out;" ;'
        self.cmd += "/sbin/ifconfig | grep -e 'inet addr' | grep -v '127.0.0.1' | cut -f2 -d':' | cut -f1 -d' ';"

        self.available_commands = ['@backdoor', '@download', '@enum', '@history', '@info', '@update', '@upload', 'clear', 'exit']

    def get_information(self):
        now = datetime.datetime.now()

        # Call get_page_source() method then assign it to self.source
        source = make_request.get_page_source(self.cmd)

        self.current_user = source[0]
        self.current_id = source[1]
        self.kernel_info = source[2]
        self.cwd = source[3]
        self.perm_cwd = source[4]
        try:
            self.uptime = source[5]
        except IndexError:
            self.uptime = 'Unknown'
        self.host_ip = ', '.join(source[6:])
        self.session = now.strftime("%Y-%m-%d")
        try:
            # Get the attacker's ip address (Thanks @mandreko)
            self.local_ip = (urlopen('http://ifconfig.me/ip').read()).strip()
        except URLError:
            self.local_ip = 'Unknown'

        self.info = \
        '''
        {dashed}
        {red}User{end}        :  {green}{current_user}{end}
        {red}ID{end}          :  {green}{current_id}{end}
        {red}Kernel{end}      :  {green}{kernel_info}{end}
        {red}CWD{end}         :  {green}{cwd}{end}\t\t{hot}{perm_cwd}{end}
        {red}Uptime{end}      :  {green}{uptime}{end}
        {red}Target's IPs{end}:  {green}{host_ip}{end}
        {red}Our IP{end}      :  {green}{local_ip}{end}
        {dashed}

        {hot}[+] Available commands: {available_commands}{end}
        {hot}[+] Inserting{end} {red}!{end} {hot}at the begining of the command will execute the command locally ({red}on your box{end}){end}
        '''.format(dashed='-' * int(len(self.kernel_info) + 16),
                red=Colors.RED, green=Colors.GREEN, end=Colors.END, hot=Colors.HOT,
                current_user=self.current_user,
                current_id=self.current_id,
                kernel_info=self.kernel_info,
                cwd=self.cwd,
                perm_cwd=self.perm_cwd,
                host_ip=self.host_ip,
                local_ip=self.local_ip,
                uptime=self.uptime,
                available_commands=self.available_commands,)
        print self.info

info = TargetBox()

変数のブロック全体でステートメントを使用できますか?例えば

try:
    self.current_user = source[0]
    self.current_id = source[1]
    self.kernel_info = source[2]
    self.cwd = source[3]
    self.perm_cwd = source[4]
    self.uptime = source[5]
except IndexError:
    self.var_name = 'Unknown'
4

2 に答える 2

3

値をフォールバック/デフォルト値に事前初期化すると、例外がスローされたときに何もできなくなります。

self.current_user = None
self.current_id = None
self.kernel_info = None
self.cwd = None
self.perm_cwd = None
self.uptime = 'Unknown'

try:
    self.current_user = source[0]
    self.current_id = source[1]
    self.kernel_info = source[2]
    self.cwd = source[3]
    self.perm_cwd = source[4]
    self.uptime = source[5]
except IndexError:
    pass

もちろん、None特定のシナリオに応じて、別のものに変更してください。

指定されたインデックスにある要素が存在する場合はそれを返す関数を使用することもできます。それ以外の場合は、デフォルト値を返します。

def get_index_with_default(seq, index, default=None):
    try:
        return seq[index]
    except:
        return default

次に、次の方法で割り当てを実行できます。

self.uptime = get_index_with_default(source, 5, 'Unknown')
于 2012-07-20T00:52:19.260 に答える
2

try/except多くの場合、これは便利でPythonicなアプローチですが、この場合は別の方法で、元のリストにない各値にデフォルトを割り当てるだけです。イテレータとnext()ビルトインを使用すると、自然な方法でこれを実現できます。

source = iter(source)
self.current_user = next(source, "Unknown")
self.current_id = next(source, "Unknown")
self.kernel_info = next(source, "Unknown")
self.cwd = next(source, "Unknown")
self.perm_cwd = next(source, "Unknown")
self.uptime = next(source, "Unknown")

これを実現する別の方法は、目的の長さになるまで「不明」をリストに追加することです。

from itertools import repeat
source.extend(repeat("Unknown", 6 - len(source) if len(source) < 6 else 0))
self.current_user, self.current_id, self.kernel_info, self.cwd, self.perm_cwd, self.uptime = source
于 2012-07-20T00:58:11.643 に答える