我一直在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,但這些服務器上的文件當然沒有列出,因爲用戶名,密碼,主機名不正確。我如何驗證它?如何提出異常或錯誤的用戶名,密碼或主機名錯誤?
您可能需要閱讀[返回代碼](https://en.wikipedia.org/wiki/Exit_status)和[Popen](http://docs.python.org/2/library/subprocess# subprocess.Popen) – goncalopp
你可以請更具體一點嗎?我想顯示如下消息:主機名不正確或用戶名/密碼不正確! – sachitad
當然。如果你真的想用Popen(而不是像Marwan Alsabbagh所建議的那樣的庫)來做到這一點,你應該檢查每個Popen調用的返回代碼,並將其與每個程序返回的返回代碼列表進行比較(sshpass, rsync的)。你可以在程序的手冊上找到這些信息,或者如果失敗了,可以通過反覆試驗來找到。 – goncalopp