分离函数以分离Python文件后未定义全局变量

时间:2016-08-29 01:07:11

标签: python module global-variables

继续为项目编写我的字典攻击脚本。

我的脚本调用两个在SSH上执行实际字典攻击的函数。首先,我在main.py的get_args()函数中声明了我的全局变量,然后使用main()函数

def get_args():
    # stuff for parsing blah blah


    global service, username, wordlist, address, port, delay

    service = args.service
    username = args.username
    wordlist = args.password
    address = args.address
    port = args.port
    delay = args.delay

    return service, username, wordlist, address


def main():

    service, username, wordlist, address = get_args()

    # output and stuff

    # SSH bruteforce
    if service == 'ssh':
        if address is None:
            print R + "[!] You need to provide a SSH address for cracking! [!]" + W
    else:
        print C + "[*] Address: %s" % address + W
        sleep(0.5)
        global port
        if port is None:
            print O + "[?] Port not set. Automatically set to 22 for you [?]" + W
            port = 22

        print C + "[*] Port: %s "  % port + W
        sleep(1)
        print P + "[*] Starting dictionary attack! [*]" + W
        print "Using %s seconds of delay. Default is 1 second" % delay
        sshBruteforce(address, username, wordlist)

sshBruteforce(address, username, wordlist)引用我作为模块包含在单独文件中的函数,我用

导入该模块
from module1 import *

在module1.py中:

# ssh_connect()
def ssh_connect(password, code=0):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    paramiko.util.log_to_file("filename.log")

    try:
        ssh.connect(address, port=port, username=username, password=password)


def sshBruteforce(address, username, wordlist):
    wordlist = open(wordlist, 'r')

    for i in wordlist.readlines():
        password = i.strip("\n")
        try:
            response = ssh_connect(password)
            # actual bruteforcing here. The above line references the ssh_connect()
            # function, which is where the problem actual occurs

ssh.connect(address, port=port, username=username, password=password)是问题发生的地方。让我们说我像这样执行脚本:

python main.py -u root -w wordlist.txt -s ssh -p 22 -a 192.168.1.3 

这将字符串"root"存储在变量username中等等。但是,一旦main.py程序执行sshBruteforce()函数,就会发生这种情况:

global name 'address' is not defined

我知道这发生在ssh_connect()函数中,行ssh.connect(address, port=port, username=username, password=password),这意味着变量address中没有存储任何内容。我不知道为什么会这样。

from __main__ import *中加入module1.py不会改变任何内容。我已经看到很多这些问题,但没有一个与我的情况类似。

1 个答案:

答案 0 :(得分:-1)

全局定义的概念意味着您应该在函数之外定义它,尝试使用None或其他东西初始化函数以外的所有全局变量并查看问题是否已解决