3

我一直在 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))

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

4

2 回答 2

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。

于 2012-11-23T07:46:21.320 回答
1

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

请注意,我之前已经警告过您。请停止实施根本不安全的架构。

于 2012-11-23T09:06:31.183 回答