利用Paramiko模块实现SFTP工具实现文件的上传下载
1 import paramiko 2 import sys 3 import optparse 4 5 6 class SFTPClient: 7 def __init__(self) -> None: 8 self.target = self.get_params()[0] 9 self.port = self.get_params()[1] 10 self.username = self.get_params()[2] 11 self.password = self.get_params()[3] 12 self.banner() 13 print('Start to connect the server...') 14 try: 15 self.sshclient = paramiko.SSHClient() 16 self.sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 17 self.sshclient.connect(hostname=self.target, port=self.port,username=self.username, password=self.password) 18 self.sftp = self.sshclient.open_sftp() 19 except paramiko.AuthenticationException: 20 print("[-] Your credentials is wrong") 21 sys.exit() 22 23 24 def banner(self): 25 banner= """ 26 ************************************************** 27 28 ********** SFTP Client Tool by Jason Wong********* 29 30 ************************************************** 31 32 Usage: 33 cd change directory 34 download download file from target 35 upload upload file to target 36 quit exit the probram 37 """ 38 print(banner) 39 40 41 def get_params(self): 42 parser = optparse.OptionParser("Usage: <Program> -t target -p port -u username -P password") 43 parser.add_option('-t','--target', dest='target', type='string', help='Specify target IP address') 44 parser.add_option('-p', '--port', dest='port', default=22, type='int', help="Specify target port") 45 parser.add_option('-u', '--username', dest='username', type='string', help='Specify username') 46 parser.add_option('-P', '--password', dest='password', type='string', help="Specify password") 47 options, args = parser.parse_args() 48 if options.target is None or options.username is None or options.password is None: 49 print(parser.usage) 50 sys.exit(0) 51 return options.target, options.port, options.username, options.password 52 53 def print_dirs(self,dirs): #更友好的打印目录,否则会直接以列表方式呈现 54 print("List the current directory as follows: \n") 55 for each in dirs: 56 57 print(each) 58 59 def run(self): 60 try: 61 self.sftp.chdir('/') 62 self.print_dirs(self.sftp.listdir()) 63 while True: 64 command = input("%s ~ " % self.target) 65 if command == 'quit': 66 break 67 elif command[0:2] == 'cd': 68 self.sftp.chdir(command[3:]) 69 self.print_dirs(self.sftp.listdir()) 70 elif command[0:8] == 'download': 71 self.sftp.get(command[9:],'/tmp/'+command[9:]) 72 elif command[0:3] == 'upload': 73 self.sftp.put('/tmp/'+command[4:], '/tmp/'+command[4:]) 74 else: 75 print("Unknown Command") 76 77 except KeyboardInterrupt: 78 print("Exit the program") 79 sys.exit(0) 80 81 82 if __name__ == "__main__": 83 ssh_client = SFTPClient() 84 ssh_client.run()
运行效果示意图如下:
STRIVE FOR PROGRESS,NOT FOR PERFECTION