paramiko普通用户切root执行命令

import paramiko,time

def verification_ssh(host, username, passwd, port, root_pwd, cmd):
    s=paramiko.SSHClient()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(hostname=host, port=port, username=username, password=passwd)
    if username != 'root':
        ssh = s.invoke_shell()
        time.sleep(0.1)
        ssh.send('su root\n')
        buff = ''
        while not buff.endswith('Password: '):
            resp = ssh.recv(9999)
            buff +=resp.decode('utf-8')
        ssh.send(root_pwd+'\n')

        buff = ''
        while "root@" not in buff:
            resp = ssh.recv(9999)
            buff +=resp.decode('utf-8')
        ssh.send(cmd+'\n')
        buff = ''
        res = ''
        while "root@" not in res:
            resp = ssh.recv(9999)
            buff +=resp.decode('utf-8')
            res = buff.split('\r\n')[-1]

        s.close()

        result = buff
    else:
        stdin, stdout, stderr = s.exec_command(cmd)
        result = stdout.read()
        s.close()
    print(result)



verification_ssh('20.58.32.14', 'sys', 'test', 22, '123456', 'ert')

 

posted @ 2022-03-02 23:28  Linuxbugs  阅读(661)  评论(0编辑  收藏  举报