通过python实现linux切换用户_Python操作远程服务器切换到root用户
在自動化運(yùn)維過程中,需要遠(yuǎn)程服務(wù)器切換到root用戶下執(zhí)行命令,嘗試了一些方法,得到如下好用的方法,供大家使用:
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')
總結(jié)
以上是生活随笔為你收集整理的通过python实现linux切换用户_Python操作远程服务器切换到root用户的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你也在《我的世界》里流浪过吗?MC有这么
- 下一篇: 快手取消大小周快手取消大小周薪资