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

时间:2012-11-23 03:35:49

标签: python django exception-handling

我一直在Python / Django中实现rsync来在文件之间传输数据。这是我的views.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,用户名和密码。但是那些密码,用户名或服务器名称可能不正确。即使它们不正确,此代码也会将我转换为thanks.html,但这些服务器上的文件当然未列为用户名,密码,主机名不正确。我如何验证它?如何引发异常或错误的用户名,密码或主机名错误?

2 个答案:

答案 0 :(得分:1)

在python中,如果你想使用ssh或sftp(通过ssh连接复制文件),那么paramiko库就可以了。如果您只想检查提供的主机,用户名,密码组合是否有效,此功能将完成此任务:

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中通常那样捕获这些异常,并向用户显示您希望的任何类型的消息。我建议不要使用sshpass和subprocess来使用paramiko。

答案 1 :(得分:1)

在您执行任何其他操作之前,停止。您正在使用全局变量来存储用户名和密码。这意味着来自其他用户的后续请求将可以访问先前用户的数据。 不要这样做。如果你在Python中使用全局变量,那么你可能做错了:如果你使用它在Django中的请求之间传递数据,你肯定做错了。

请注意I've warned you about this before。请停止实施基本上不安全的架构。