Course4-Python ftp/ssh

1. ftp

Python 自带有模块支持ftp. 可以参看一下代码。

  1 #!/usr/bin/env python
  2 import sys
  3 import os
  4 import time
  5 import getopt
  6 import traceback
  7 from ftplib import FTP
  8 
  9 class ftp_up_down():
 10         def __init__(self):
 11                 pass
 12         def captureException(self,logname='ftp_log.log'):                
 13                 logs = open(logname, 'a')
 14                 print >> logs, time.strftime('%Y-%m-%d %X', time.localtime())
 15                 err = ''.join(traceback.format_exception(*sys.exc_info()))
 16                 print >> logs, err
 17                 logs.close()
 18 
 19         def logging(self,mystring, filename='ftp_log.log'):
 20               
 21                 try:
 22                     print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + " " + mystring
 23                     fso = open(filename, 'a')
 24                     fso.write(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + " " + mystring + '\n' + '\n')
 25                     fso.close()
 26                 except:
 27                     captureException()
 28            
 29         def ftp_up(self,ServerFolder, LocalLocation, FileName, ServerAddr, user, password):
 30             try:
 31                 time1= time.time()
 32                 bufsize = 2048#set buffer size 
 33                 ftp=FTP() 
 34                 #ftp.set_debuglevel(2)#open debug level, 2 display the detailed info, 0 close the debug info 
 35                 ftp.connect(ServerAddr)#connect
 36                 ftp.login(user,password)#login 
 37                 print ftp.getwelcome()#display ftp server welcome message
 38                 ftp.cwd(ServerFolder) #choose the work directory
 39                 filename = LocalLocation + '\\' + FileName
 40                 file_handler = open(filename,'rb')#open the file in local as readonly
 41                 ftp.storbinary('STOR %s' % os.path.basename(filename),file_handler,bufsize)#upload file 
 42                 ftp.set_debuglevel(0) 
 43                 file_handler.close() 
 44                 ftp.quit()
 45                 time2= time.time()
 46                 print "ftp up OK"
 47                 self.logging('Successfully upload file: "{0}" to FTP Server: {1}'.format(str(FileName), str(ServerAddr)))
 48                 print round((time2-time1),3)
 49             except:
 50                 self.logging('Fail to upload file: "{0}" to FTP Server: {1}'.format(str(FileName), str(ServerAddr)))
 51                 self.captureException()
 52             
 53         def ftp_down(self,ServerFolder, LocalLocation, FileName, ServerAddr, user, password):
 54             try:
 55                 time1= time.time()
 56                 bufsize = 2048#set buffer size
 57                 ftp=FTP() 
 58                 #ftp.set_debuglevel(2)
 59                 ftp.connect(ServerAddr)#connect 
 60                 ftp.login(user,password)#login 
 61                 print ftp.getwelcome()#display ftp server welcome message
 62                 ftp.cwd(ServerFolder)#choose the work directory  
 63                 filename = LocalLocation + '\\' + FileName
 64                 file_handler = open(filename,'wb').write #open the file in local as write
 65                 ftp.retrbinary('RETR %s' % os.path.basename(filename),file_handler,bufsize)#download file 
 66                 ftp.set_debuglevel(0)  
 67                 ftp.quit()
 68                 time2= time.time()
 69                 print "ftp down OK"
 70                 self.logging('Successfully download file: "{0}" from FTP Server: {1}'.format(str(FileName), str(ServerAddr)))
 71                 print round((time2-time1),3)
 72             except:
 73                 self.logging('Fail to download file: "{0}" from FTP Server: {1}'.format(str(FileName), str(ServerAddr)))
 74                 self.captureException()
 75         def usage(self):        print '''
 76 Usage:ftp_up_down [-u|-d]|[-S serverfolder| -L localfolder| -F filename| -I unix_ip| -U unix_user| -P unix_password]|[--help]\n
 77 \t-u|-d -u means upload, -p means download\n
 78 \t-S the unix folder to store the upload/download file\n
 79 \t-L the Windows folder to store the upload/download file\n
 80 \t-F the file name to be upload/download\n
 81 \t-I the unix server ip\n
 82 \t-U the unix user\n
 83 \t-P the unix user password\n
 84 Examples:
 85 \tftp_up_down -d -S "/release/scripts/" -L "E:\\Daly\\Investigation\\" -F "a.txt" -I 10.100.99.1xx -U root -P pass\n
 86 \tftp_up_down -u -S "/release/scripts/" -L "E:\\Daly\\Investigation\\" -F "a.txt" -I 10.100.99.1xx -U root -P pass
 87 '''
 88 ABSPATH=None  
 89 if __name__ == "__main__":
 90         ABSPATH=os.path.abspath(sys.argv[0])
 91         ABSPATH=os.path.dirname(ABSPATH)+"\\"
 92         #print ABSPATH
 93         work_folder=ABSPATH
 94         #print work_folder
 95         serverfolder=""
 96         localfolder=""
 97         filename=""
 98         unix_ip=""
 99         unix_user=""
100         unix_password=""
101         try:
102                 opts,args = getopt.getopt(sys.argv[1:], "hudS:L:F:I:U:P:", ["help", "up", "down", "serverfolder=", "localfolder=", "filename=", "ip=", "user=", "password="])
103                 #print opts
104                 #print args
105                 if not opts:
106                     try:
107                         ftp_up_down().usage()
108                     except:
109                         sys.exit(0)
110                 for opt, arg in opts:
111                         if opt in ("-h", "--help"):
112                                 ftp_up_down().usage()
113                                 sys.exit(0)
114                         elif opt in ("-S"):
115                                 serverfolder = arg
116                         elif opt in ("-L"):
117                                 localfolder = arg
118                         elif opt in ("-F"):
119                                 filename = arg
120                         elif opt in ("-I"):
121                                 unix_ip = arg
122                         elif opt in ("-U"):
123                                 unix_user = arg
124                         elif opt in ("-P"):
125                                 unix_password = arg
126                 #print opts[0]
127                 print serverfolder, localfolder, filename, unix_ip, unix_user, unix_password
128                 try:
129                         if("-u" in opts[0]):
130                                 try:
131                                         print serverfolder, localfolder, filename, unix_ip, unix_user, unix_password
132                                         ftp_up_down().ftp_up(ServerFolder=serverfolder, LocalLocation=localfolder, FileName=filename, ServerAddr=unix_ip, user=unix_user,password=unix_password)
133                                 except:
134                                         print ''.join(traceback.format_exception(*sys.exc_info()))
135                         elif("-d" in opts[0]):
136                                 try:
137                                         #print serverfolder, localfolder, filename, unix_ip, unix_user, unix_password
138                                         ftp_up_down().ftp_down(ServerFolder=serverfolder, LocalLocation=localfolder, FileName=filename, ServerAddr=unix_ip, user=unix_user,password=unix_password)
139                                 except:
140                                         print ''.join(traceback.format_exception(*sys.exc_info()))
141                 except:
142                         print ''.join(traceback.format_exception(*sys.exc_info()))
143         except getopt.GetoptError:
144                 print "getopt error"
145                 ftp_up_down().usage()
146                 sys.exit(1)
View Code

 

2. ssh

Python ssh需要安装其他模块支持,支持ssh的模块有pexpect(*Nix),paramiko等, 在此主要讲在Windows上支持的paramiko模块。可参看一下代码。

 1 import paramiko
 2 class CommonUtils(object):
 3     '''
 4     classdocs
 5     '''
 6     def __init__(self):
 7         '''
 8         Constructor
 9         '''
10         log().paramiko_log_to_file(level="DEBUG")
11     def ssh_conn(self,host,port,user,password):
12         '''
13         @param host: the host name or ip address 
14         @param port: the ssh port number  
15         @param user: the user to login the host
16         @param password: the user's password
17         example: ssh_conn("10.xx.xx.xx",22,'xxu1','password')
18         '''
19         try:
20             client = paramiko.SSHClient()
21             client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
22             client.connect(host,22,user,password)
23             return client
24         except Exception, e:
25             log().log("{0} Please check the user name and password are correct.".format(str(e)))
26             return None    
27     def ssh_close(self,conn):
28         conn.close()
29     def ssh_exec_querycommand(self,conn,command):
30         '''
31         @param conn: the ssh connection which setup with using function ssh_conn
32         @param command: the command to be executed 
33         '''
34         stdin, stdout, stderr = conn.exec_command(command)
35         stdin.flush()
36         output = []
37         for line in stdout:
38             print '###' + line.strip('\n')
39             output.append(line.strip('\n'))
40         if stderr != None and len(str(stderr)) == 0:
41             print 'Error info: ' + stderr.read()
42         return output
43     def ssh_exec_intercommand(self,conn,begincommand,promptanswer):
44         '''
45         @param conn: the ssh connection which setup with using function ssh_conn
46         @param begincommand: the command to be executed firstly
47         @param promptanswer: the command to be executed to answer the question after executed begincommand
48         '''
49         channel = conn.invoke_shell()
50         channel.recv(1024)
51         time.sleep(1)
52         channel.send(begincommand + '\n')
53         time.sleep(1)
54         question = channel.recv(1024)
55         #realquestion = (question.split(begincommand))[0:]
56         realquestion = (question.split('\n'))[1]
57         log().log("Question pops: {0}".format(realquestion))
58         time.sleep(1)
59         channel.send(promptanswer + '\n')
60         time.sleep(30)
61         result = channel.recv(1024)
62         log().log("After input answer: {0}".format(result))
63         channel.close()
64         return result
65     def ssh_exec_command_after_interaction(self,conn,begincommand,promptanswer,command):
66         '''
67         @param conn: the ssh connection which setup with using function ssh_conn
68         @param begincommand: the command to be executed firstly
69         @param promptanswer: the command to be executed to answer the question after executed begincommand
70         @param command: the command to be executed after the interaction 
71         '''
72         channel = conn.invoke_shell()
73         channel.recv(1024)
74         time.sleep(1)
75         channel.send(begincommand + '\n')
76         time.sleep(1)
77         question = channel.recv(1024)
78         realquestion = (question.split(begincommand))[1]
79         #realquestion = (question.split('\n'))[1]
80         log().log("Question pops: {0}".format(realquestion))
81         time.sleep(1)
82         channel.send(promptanswer + '\n')
83         time.sleep(1)
84         result = channel.recv(1024)
85         log().log("After input answer: {0}".format(result))
86         channel.send(command + '\n')
87         time.sleep(3)
88         cmdresult = channel.recv(1024)
89         fullcmdresult = (cmdresult.split(command))[0]
90         realcmdresult = (fullcmdresult.split('\n'))[1:-1]
91         finalrestult = ''
92         for i in range(len(realcmdresult)):
93             finalrestult += ''.join(realcmdresult[i])
94         log().log("Command result: {0}".format(finalrestult))
95         channel.close()
96         return str(finalrestult)
View Code

posted on 2016-03-15 13:48  Daly_You  阅读(257)  评论(0编辑  收藏  举报

导航