2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 通过python实现linux切换用户_Python操作远程服务器切换到root用户

通过python实现linux切换用户_Python操作远程服务器切换到root用户

时间:2021-02-13 06:37:47

相关推荐

通过python实现linux切换用户_Python操作远程服务器切换到root用户

在自动化运维过程中,需要远程服务器切换到root用户下执行命令,尝试了一些方法,得到如下好用的方法,供大家使用:

import time

import paramiko

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 = ''

while not buff.endswith('Password: '):

resp = ssh.recv(9999)

buff +=resp

ssh.send(root_pwd)

ssh.send('\n')

buff = ''

while not buff.endswith('# '):

resp = ssh.recv(9999)

buff +=resp

ssh.send(cmd)

ssh.send('\n')

buff = ''

while not buff.endswith('# '):

resp = ssh.recv(9999)

buff +=resp

s.close()

result = buff else:

stdin, stdout, stderr = s.exec_command(cmd)

result = stdout.read()

s.close()

return result

if __name__ == "main":

verification_ssh('192.168.1.11','cimer','1q2w3e4r',22,'1q2w3e4r','ifdown eth0')

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。