歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python ftp 文件上傳和文件下載

Python ftp 文件上傳和文件下載

日期:2017/3/1 10:50:49   编辑:Linux編程

Python ftp 文件上傳和文件下載

  1. import ftplib
  2. import os
  3. import socket
  4. HOST='192.168.30.109'
  5. FILE='test'
  6. def main():
  7. try:
  8. f=ftplib.FTP(HOST)
  9. except (socket.error,socket.gaierror),e:
  10. print 'ERROR:cannot reach "%s"'% HOST
  11. return
  12. print '***connected to host "%s"' % HOST
  13. try:
  14. f.login(user='test',passwd='123')
  15. except ftplib.error_perm:
  16. print 'ERROR:cannot login anonymously'
  17. f.quit()
  18. return
  19. print '***Logged in as "test""'
  20. try:
  21. f.retrbinary('RETR %s' % FILE,open(FILE,'wb').write)
  22. except ftplib.error_perm:
  23. print 'ERROR:cannot read file "%s"' % FILE
  24. os.unlink(FILE)
  25. else:
  26. print '***Downloaded "%s" to CWD' % FILE
  27. return
  28. try:
  29. f.storbinary('STOR %s' % FILE,open(FILE,'rb'))
  30. except ftplib.error_perm:
  31. print 'ERROR:cannot up file "%s"' % FILE
  32. os.unlink(FILE)
  33. else:
  34. print '***upload "%s" to ftp' % FILE
  35. f.quit()
  36. return
  37. if __name__=='__main__':
  38. main()
Copyright © Linux教程網 All Rights Reserved