将telnet和ftp的下载上传封装成函数:
#encoding=utf-8
def do_telnet(Host, username, password, finish, commands):
import telnetlib
'''Telnet远程登录:Windows客户端连接Linux服务器'''
# 连接Telnet服务器
tn = telnetlib.Telnet(Host, port=23, timeout=10)
tn.set_debuglevel(1)
# 输入登录用户名
tn.read_until('login: ')
tn.write(username + '\n')
# 输入登录密码
tn.read_until('assword: ')
tn.write(password + '\n')
# 登录完毕后执行命令
tn.read_until(finish)
for command in commands:
tn.write('%s\n' % command)
#执行完毕后,终止Telnet连接(或输入exit退出)
tn.read_until(finish)
tn.close() # tn.write('exit\n')
def do_ftp_download(host,username,password,localfile,remotefile):
import ftplib
'''connect the remote linux server'''
ftp=ftplib.FTP()
ftp.connect(host,port=21)
#ftp.set_debuglevel(2)
''' longin '''
ftp.login(username,password)
ftp.set_pasv(0)
f = open(localfile, 'wb')
ftp.retrbinary('RETR ' + remotefile, f.write, 1024)
f.close()
ftp.close()
def do_ftp_upload(host,username,password,localfile,remotefile):
import ftplib
ftp=ftplib.FTP(host)
ftp.login(username,password)
#ftp.set_debuglevel(2)
f = open(localfile, 'rb')
ftp.storbinary('STOR ' + remotefile,f)
ftp.close()
f.close()
if __name__=='__main__':
# 配置选项
#import sys
#params=sys.argv[0]
import time
params=raw_input("plsease input your analyis file:\n")
Host = '135.252.181.62' #Telnet服务器IP
username = 'liutaili' #登录用户名
password = 'liutaili' #登录密码
finish = 'liutaili@bl8062' #命令提示符
commands = ['cd parser;dos2unix %s ;./smartParser.sh %s' % (params,params)]
begin_time=int(time.time())
timeArray=time.localtime(begin_time)
begin_otherStyleTime=time.strftime("%Y-%m-%d %H:%M:%S",timeArray)
do_ftp_upload(Host,username,password,params,'/home/liutaili/parser/%s' % params )
print ("upload file ok")
do_telnet(Host, username, password, finish, commands)
print ("analysis file done")
do_ftp_download(Host,username,password,"%s.status.txt" % params, "/home/liutaili/parser/%s.status.txt" % params)
print ("do analysi done")
end_time=int(time.time())
timeArray=time.localtime(end_time)
end_otherStyleTime=time.strftime("%Y-%m-%d %H:%M:%S",timeArray)
print "--------------------------------------------"
print "---Begin time: %s" % begin_otherStyleTime
print "---End time: %s" % end_otherStyleTime
print "--------------------------------------------"
print "--------------------------------------------"
print ("the result file is : %s.status.txt" % params)
print "--------------------------------------------"
raw_input('Press any key to exit!')