paramiko和sudo su - oracle

时间:2017-10-19 09:31:47

标签: sudo paramiko

我正在尝试使用测试用户连接到Linux服务器并执行命令sudo su - oracle whoami。但不能正确地做到这一点。 有人可以帮忙吗?

我的代码如下

import paramiko as pk
import socket as sk
import os
from datetime import datetime as dt

class Master:
    client = None
    error = None
    host = None
    user = None
    passwd = No

def __init__(self, address, username, password=None):
    self.client = pk.SSHClient()
    self.client.set_missing_host_key_policy(pk.AutoAddPolicy())
    try:
        self.client.connect(address, username=username, password=password, look_for_keys=False, port=22, timeout=2)
        self.host = address
        self.user = username
        self.passwd = password

    except pk.SSHException as e:
        self.error = e
    except sk.timeout:
        self.error = "Socket timedout"
    except:
        self.error = "Unknown Error"

def sendCommand(self, command, pty=False):
    out = []
    print("\nCommand that is passed is {}".format(command))
    if(self.client):
        stdin, stdout, stderr = self.client.exec_command(command, get_pty=pty, timeout=5)
        print(stderr.readlines())
        for line in stdout.readlines():
            out.append(line.strip())
        return out
    else:
        print("Connection not opened.")


host = '10.1.1.50'
user = 'test'
password = 'abc123'

conn = Master(address=host, username=user, password=password)

command = "echo -e {} | sudo su - oracle whoami \n".format(password)
output = conn.sendCommand(command, pty=True)

print(output)

有人可以建议如何使用paramiko sudo su - oracle吗?

1 个答案:

答案 0 :(得分:0)

使用面料来实现这一目标 -

from fabric.api import env, sudo, run
env.password="LOCALUSERPASSWORD"
run("echo 'whoami' | sudo su - oracle")#Prints oracle