#coding=utf-8
import paramiko,time
def verification_ssh(host,username,password,port,root_pwd,cmd):
s = paramiko.SSHClient()
s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname = host,port=int(port),username=username, password=password)
if username != 'root':
ssh = s.invoke_shell()
time.sleep(0.1)
ssh.send('su - \n')
buff = ''
# 注意这里Password 有些伪终端这里是中文
while not buff.endswith('Password: '):
resp = ssh.recv(9999)
# 注意编码格式
buff +=resp.decode('gbk')
ssh.send(root_pwd)
ssh.send('\n')
buff = ''
while not buff.endswith('# '):
resp = ssh.recv(9999)
buff +=resp.decode('gbk')
ssh.send(cmd)
ssh.send('\n')
buff = ''
while not buff.endswith('# '):
resp = ssh.recv(9999)
buff +=resp.decode('gbk')
s.close()
result = buff
else:
stdin, stdout, stderr = s.exec_command(cmd)
result = stdout.read()
s.close()
return result
res = verification_ssh('172.25.16.38','study','123',54321,'x22xx','pwd')
print(res)