简体   繁体   中英

How to raise this exception or error message?

I have been implementing rsync in Python/Django to transfer data between the files. Here's my 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))

I take the remotehost, username and password input from the form. But those passwords, username or servername may not be correct. Even they are not correct this code transforms me to thanks.html but files on those server are not listed of course as username, password, hostname were not correct. How do I validate it? How do I raise exception or wrong username, password or hostname error?

In python if you want to work with ssh or sftp(copying files over an ssh connection) then the paramiko library is the way to go. If you just want to check whether the provided host, username, password combination is valid this function will do the job:

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)

an example call of the function would be:

test_ssh('10.0.0.10', 'myuser', 'mypassword')

if it was able to connect to the host correctly it will return successfully. Otherwise it will through an exception with the details of exactly what failed. For example when one puts an invalid host the following exception gets raised:

socket.error: [Errno 113] No route to host

invalid username, password will raise:

paramiko.AuthenticationException: Authentication failed.

You can catch these exceptions as you would normally do in Python and display whatever type of message you wish to your user. I would recommend that instead of using sshpass and subprocess to use paramiko.

Before you do anything else, stop . You are using globals to store usernames and passwords. This means that subsequent requests - from other users - will have access to the previous user's data. Do not do this . If you're using globals in Python anyway, you're probably doing it wrong: if you're using it to pass data between requests in Django, you're definitely doing it wrong.

Note that I've warned you about this before . Please stop implementing fundamentally unsafe architectures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM