第一次用Python语言写的程序,功能可以基本实现,还有很多不足的地方,需要改进。
#!/usr/local/env python
#-*- coding:UTF-8 -*-
import ftplib
import os
import socket
#HOST='192.168.203.100'
DIRN='/home/ftpadmin'
FILE='test.txt'
def download(f):
try:
f.cwd(DIRN)
except ftplib.error_perm:
print 'ERROR:Cannot CD to %s ' % DIRN
f.quit()
return
file=raw_input("请选择要下载的文件:")
try:
f.retrlines('RETR %s' % file,open(file,'wb').write)
except ftplib.error_perm:
print 'ERROR:cannot read file %s' % file
os.unlink(file)
else:
print "***Download %s tp CWD " % file
return
def put(f):
filepath=raw_input("请输入要上传的文件名:")
f1=open(filepath,'rb')
file_name=os.path.split(filepath)[-1]
try:
f.storlines('STOR %s' % file_name,f1)
except ftplib.error_perm:
f.quit()
return
def show(f):
f.dir()
def quit1(f):
print "退出程序"
f.quit()
order={'d':download,'p':put,'s':show}
def main():
HOST=raw_input( "请输入要登录的服务器地址:")
try:
f=ftplib.FTP(HOST)
except (socket.error,socket.gaierror),e:
print "ERROR:cannot reache %s" % HOST
return
print "...connected to host %s " % HOST
try:
f.login('ftpadmin','12345')
except ftplib.error_perm:
print 'ERROR:cannot login FTP'
f.quit()
return
print "成功登陆FTP服务器"
print "请选择操作的服务"
showmenu(f)
def showmenu(f):
s="""
(D)ownload
(P)put
(s)how
(Q)uit
Enter choice:
"""
done=False
while not done:
chosen=False
while not chosen:
try:
choice=raw_input(s).strip()[0].lower()
except (EOFError,KeyboardInterrupt):
print "异常,退出服务器"
choice='q'
print "你的选择是:%s" % choice
if choice not in 'dpqs':
print "invaid option,try again"
else:
chosen=True
if choice=='q':
quit1(f)
break
order[choice](f)
if __name__=='__main__':
main()