手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python操作远程服务器切换到root用户

[日期:2016-08-25] 来源:Linux社区  作者:Linux [字体:大 中 小]

在自动化运维过程中,需要远程服务器切换到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')

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-08/134607.htm

linux
相关资讯       Python操作远程服务器 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款