ImportParamiko,osImportLoggingclassSsh_host (object):def __init__(self,host_ip,password,port=22,user='Root', log_file='Ssh_host.log'): Self.host_ip=host_ip Self.password=Password Self.port=Port Self.user=User Self.log_file=Log_filedef __connect(self): transport=Paramiko. Transport ((Self.host_ip,self.port)) Transport.connect (username=self.user, password=Self.password) sftp=Paramiko. Sftpclient.from_transport (transport)returntransport,sftpdef __logger(Self,method): Logger=Logging.getlogger (method) Formatter= Logging. Formatter ('% (asctime) s% (levelname) -8s:% (message) s') File_handler=logging. Filehandler (Self.log_file) file_handler.setformatter (formatter) Logger.addhandler (File_handler) Logge R.setlevel (Logging.info)returnLoggerdefRun_sys (Self,command): Logger= self.__logger('Run_sys') SSH=Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect (hostname=self.host_ip, Port=self.port, username='Root', password=Self.password) stdin, stdout, stderr=ssh.exec_command (command)ifLen (Stderr.read (). Decode ())! =0:logger.error ("%s:%s<==>%s"%(self.host_ip, Command, Stderr.read (). Decode ( )))Print(command)Print(Stdout.read (). Decode ())#Output Results Print(Stderr.read (). Decode ()) Ssh.close ( )returnstdin, stdout, stderrdefDownload_file (self,filename,local_path='f://baidunetdiskdownload//'): Logger= self.__logger('Download_file') Connect,sftp= self.__connect() sftp.get (Filename,local_path+os.path.basename (filename)) Logger.info ('%s:%s Download%s'%(Self.host_ip,filename,local_path)) Connect.close ()defUpload_file (self,filename,local_path='f://baidunetdiskdownload//'): Logger= self.__logger('Upload_file') Connect, sftp= self.__connect() sftp.put (Local_path+os.path.basename (filename), filename) logger.info ('%s:%s Upload%s'%(Self.host_ip,local_path,filename)) connect.close () host1= Ssh_host ('192.168.71.3','Zedata') Host1.run_sys ('pwd')#host1.upload_file ('/root/bad.txt ')Host1.download_file ('/root/bad.txt')
Remotely execute commands, download files, upload files (and log logs)