ImportSYSImportParamikoImportConfig_reader fromCheck_utilsImportStandout_print, Parse_remainsize_response_lines, Error_out_print fromTimeImport TimeclassRemotemodel:"""Remote options Model execute remote command""" def __init__(Self, host, port=22): Self.hostname=host Self.port=Port Self.username, Self.password=self.load_conf () Self.s=None self.session=None self.init_conn ()defload_conf (self):"""Read Config get the login info of remote host Machine:return:login username and PASSW Ord of SSH Login of this host""" ifSelf.hostname.find ("10.179.1.110")! =-1: Error_out_print ("error:the remote machine of KOR can not provide. Please know") Sys.exit (-1) Username, password=config_reader.read_login_config (self.hostname)if notUsernameor notPassword:error_out_print ('error:can not find SSH login info in this host[%s]. Check Need'%self.hostname) Sys.exit (-1) returnusername, passworddefInit_conn (self):"""Make a connection with the remote Machine:return:""" Try: Paramiko.util.log_to_file ("Paramiko_log.log") Self.s=Paramiko. Sshclient () Self.s.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Self.s.connect (hostname=self.hostname, Port=self.port, Username=self.username, password=Self.password) Standout_print ('success connect the remote machine [host=%s]'%self.hostname)exceptException, E:standout_print (str (e)) Standout_print ('connect failed.in host[%s] user[%s] or pwd[%s] maybe wrong.'%(Self.hostname, Self.username, Self.password)) Sys.exit (-1) defClose (self):"""Close if close can not use this connection:return:""" ifself.s:self.s.close () Self=NonedefExecute_command (Self, command):""":p Aram Command:execute cmd:return:the Response Lines"""Standout_print ("info:execute command [%s]"%command) stdin, stdout, stderr=self.s.exec_command (command) stdin.write ("pwd"+"\ n") Stdin.flush () Response_lines=stdout.readlines () error_info=Stderr.read ()ifError_info andError_info.strip (): Error_out_print ('Remote Command Error info:%s'%Stderr.read ()) Error_out_print (Error_info)returnNone#Info_arr = response_info.split (' \ n ') returnResponse_linesdefremain_space_size (Self, directory_path):""":p Aram Directory_path:: Return:free size of the directory unit SIZE:MB """cmd='sudo df-m%s 1>&2'% Directory_path#/USR/LOCAL/PGSQL/DATA/SSD1Response_lines=Self.execute_command (cmd)#response_lines = Self.execute_command_channel (cmd) returnparse_remainsize_response_lines (response_lines)defExecute (Self, command, sudo=False): Feed_password=FalseifSudo andSelf.username! ="Root": Command="sudo%s"%Command Feed_password="pwd"stdin, stdout, stderr= Self.s.exec_command (Command, get_pty=True)ifFeed_password:stdin.write (Self.password+"\ n") Stdin.flush ()return{' out': Stdout.readlines (),'Err': Stderr.readlines (),'retval': Stdout.channel.recv_exit_status ()}if __name__=='__main__': Host=""hostname=""Command="sudo df-m/data/pgsql94/data"RM= Remotemodel (host=hostname)Printrm.execute_command (command)#print Rm.execute ("Df-m/data/pgsql94/data 1>&2", True)
Reference http://www.developerq.com/article/1493123866
Error 1:
Remote command error Info:sudo:sorry, you must has a TTY to run sudo
is due to
Self.s.exec_command (command, Get_pty=true)
Not set
Get_pty=true
Error 2:
will be stuck in
Stdout.readlines ()
is because SSH is waiting for the password to enter the user name
Stdin.write ("pwd" + "\ n") Stdin.flush ()
This way of interacting, note the need to wrap "\ n", and the front must not have other characters such as spaces, to ensure that the password is correct
Python uses Paramiko remote execution commands