- 论坛徽章:
- 6
|
贴上实现代码,其中我把输出用str函数转了一下,否则要报错:
def ssh_runcommand(ip, user, password1, password2, cmd, port=22):
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(ip, port, user, password1)
if user != 'root':
ssh = s.invoke_shell()
time.sleep(0.1)
ssh.send('export LANG=en_US.UTF-8;su - root\n')
buff = ''
while not buff.endswith('assword: '):
resp = ssh.recv(9999)
buff += resp
ssh.send(password2)
ssh.send('\n')
buff = ''
while not buff.endswith('# '):
resp = ssh.recv(9999)
buff += resp
ssh.send(cmd)
ssh.send('\n')
time.sleep(0.1)
ssh.send('exit')
ssh.send('\n')
buff = ''
while re.search('logout.*', buff) is None:
resp = ssh.recv(9999)
buff += resp
s.close()
ssh.close()
else:
ssh = s.invoke_shell()
time.sleep(0.1)
ssh.send(cmd)
ssh.send('\n')
time.sleep(0.1)
ssh.send('exit')
ssh.send('\n')
buff = ''
while re.search('logout.*', buff) is None:
resp = ssh.recv(9999)
buff += str(resp)
s.close()
ssh.close()
f = open(os.path.join(current_path, log_file), 'a')
f.write(str(buff))
f.close()
except BaseException as x:
print('Connect %s error, can not run the command %s, error information is %s' % (ip, cmd, x))
|
|