Python 如何引发此异常或错误消息?

Python 如何引发此异常或错误消息?,python,django,exception-handling,Python,Django,Exception Handling,我一直在用Python/Django实现rsync,以便在文件之间传输数据。以下是我的观点.py: def upload_file(request): '''This function produces the form which allows user to input session_name, their remote host name, username and password of the server. User can either save, load o

我一直在用Python/Django实现rsync,以便在文件之间传输数据。以下是我的观点.py:

def upload_file(request):
    '''This function produces the form which allows user to input session_name, their remote host name, username 
    and password of the server. User can either save, load or cancel the form. Load will execute couple Linux commands
    that will list the files in their remote host and server.'''

    if request.method == 'POST':    
        # session_name = request.POST['session']
        url = request.POST['hostname']
        username = request.POST['username']
        global password
        password = request.POST['password']
        global source
        source = str(username) + "@" + str(url)

        command = subprocess.Popen(['sshpass', '-p', password, 'rsync', '--list-only', source],
                           stdout=subprocess.PIPE,
                           env={'RSYNC_PASSWORD': password}).communicate()[0]
    command = command.split(' ')[-1]

        result = subprocess.Popen(['ls', '/home/nfs/django/genelaytics/user'], stdout=subprocess.PIPE).communicate()[0].splitlines()

        return render_to_response('thanks.html', {'res':result, 'res1':command}, context_instance=RequestContext(request))

    else:
        pass
    return render_to_response('form.html', {'form': 'form'},  context_instance=RequestContext(request))

我从表单中获取remotehost、用户名和密码输入。但这些密码、用户名或服务器名可能不正确。即使它们不正确,这段代码也会将我转换为Thanke.html,但这些服务器上的文件并没有列出,当然用户名、密码、主机名都不正确。如何验证它?如何引发异常或错误的用户名、密码或主机名错误?

在python中,如果您想使用ssh或sftp(通过ssh连接复制文件),则可以使用库。如果您只想检查提供的主机、用户名、密码组合是否有效,此功能将执行以下操作:

import paramiko

def test_ssh(host, username, password):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username=username, password=password)
函数的一个示例调用是:

test_ssh('10.0.0.10', 'myuser', 'mypassword')
如果它能够正确连接到主机,它将成功返回。否则,它将通过一个异常,详细说明失败的内容。例如,当放置无效主机时,会引发以下异常:

socket.error: [Errno 113] No route to host
用户名无效,密码将引发:

paramiko.AuthenticationException: Authentication failed.

您可以像通常在Python中一样捕获这些异常,并向用户显示任何类型的消息。我建议使用paramiko,而不是使用sshpass和subprocess

在做任何其他事情之前,停止。您正在使用globals存储用户名和密码。这意味着来自其他用户的后续请求将可以访问前一个用户的数据不要这样做。如果在Python中使用globals,那么很可能是做错了:如果在Django中使用globals在请求之间传递数据,那么肯定是做错了


请注意。请停止实施根本不安全的体系结构。

您可能需要详细阅读,能否请您更具体一点?我想显示这样的消息:主机名不正确或用户名/密码不正确!!当然如果您真的想使用Popen(而不是像Marwan Alsabbagh建议的那样使用库)执行此操作,您应该检查每个Popen调用的返回代码,并将其与每个程序返回的返回代码列表(sshpass、rsync)进行比较。你可能会在程序手册上找到这些信息,或者,如果失败的话,通过反复试验。虽然我完全同意并赞同你回答的精神,我很好奇HTTP请求怎么可能会在他的代码中显示来自前一个进程的密码值-除非Django本身存在某种安全缺陷?它不会显示值,不会。但它很可能允许后续请求使用该值:可能将密码存储在全局中的原因是为了在不同的视图中访问它,攻击者可能直接进入该视图并使用先前存储的用户名/密码访问外部资源。