【发布时间】:2012-11-23 03:35:49
【问题描述】:
我一直在 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,但这些服务器上的文件当然没有列出,因为用户名、密码、主机名不正确。我如何验证它?如何引发异常或错误的用户名、密码或主机名错误?
【问题讨论】:
-
你可能想阅读return codes和Popen
-
你能说得更具体一点吗?我想显示如下消息:主机名不正确或用户名/密码不正确!!
-
当然。如果您真的想使用 Popen(而不是库,正如 Marwan Alsabbagh 建议的那样)来执行此操作,您应该检查您进行的每个 Popen 调用的返回代码,并将其与每个程序返回的返回代码列表进行比较(sshpass, rsync)。您可能可以在程序手册上找到该信息,或者,如果失败,可以通过反复试验找到。
标签: python django exception-handling