python 采用paramiko 远程执行命令及报错解决
这篇文章主要介绍了python采用paramiko远程执行命令及报错解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
importsys
importparamiko
importconfig_reader
fromcheck_utilsimportstandout_print,parse_remainsize_response_lines,error_out_print
fromtimeimporttime
classRemoteModel:
"""remoteoptionsmodel
executeremotecommand
"""
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):
"""
readconfiggetthelogininfoofremotehostmachine
:return:
loginusernameandpasswordofSSHloginofthishost
"""
ifself.hostname.find("10.179.1.110")!=-1:
error_out_print("Error:theremotemachineofKORcannotprovide.pleaseknow")
sys.exit(-1)
username,password=config_reader.read_login_config(self.hostname)
ifnotusernameornotpassword:
error_out_print(
'Error:cannotfindsshlogininfointhishost[%s].checkneed'%self.hostname)
sys.exit(-1)
returnusername,password
definit_conn(self):
"""
makeaconnectionwiththeremotemachine
: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('successconnecttheremotemachine[host=%s]'%self.hostname)
exceptException,e:
standout_print(str(e))
standout_print(
'connectfailed.inhost[%s]user[%s]orpwd[%s]maybewrong.'%(
self.hostname,self.username,self.password))
sys.exit(-1)
defclose(self):
"""
close
ifclosecannotusethisconnection
:return:
"""
ifself.s:
self.s.close()
self=None
defexecute_command(self,command):
"""
:paramcommand:
executecmd
:return:
theresponselines
"""
standout_print("Info:executecommand[%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_infoanderror_info.strip():
error_out_print('remotecommanderrorinfo:%s'%stderr.read())
error_out_print(error_info)
returnNone
#info_arr=response_info.split('\n')
returnresponse_lines
defremain_space_size(self,directory_path):
"""
:paramdirectory_path:
:return:
freesizeofthedirectory
unitsize:MB
"""
cmd='sudodf-m%s1>&2'%directory_path#/usr/local/pgsql/data/ssd1
response_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=False
ifsudoandself.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="sudodf-m/data/pgsql94/data"
rm=RemoteModel(host=hostname)
printrm.execute_command(command)
#printrm.execute("df-m/data/pgsql94/data1>&2",True)
报错1:
remotecommanderrorinfo: sudo:sorry,youmusthaveattytorunsudo
是由于
self.s.exec_command(command,get_pty=True)
没有设置
get_pty=True
报错2:
会卡死在
stdout.readlines()
是由于SSH在等待输入用户名的密码
stdin.write("pwd"+"\n")
stdin.flush()
该种方式进行交互,注意必须要换行"\n",和前面必须不能有空格等其他字符,确保密码正确
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。