在本地计算机上运行shell命令的python代码无法获取用户输入密码以切换到超级用户

时间:2017-06-06 14:34:31

标签: python shell ssh

我正在编写一个python代码来通过SSH服务器运行shell命令。现在,我很难切换到超级用户。 以下是代码: 以下代码主要来自此链接: https://daanlenaerts.com/blog/2016/01/02/python-and-ssh-sending-commands-over-ssh-using-paramiko/http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

from paramiko import client
class ssh:
    client = None

    def __init__(self, address, username, password):
        print("Connecting to server.")
        self.client = client.SSHClient() # create a SSHclient object
        self.client.set_missing_host_key_policy(client.AutoAddPolicy()) #will auto accept unknown keys
        self.client.connect(address, username=username, password=password, look_for_keys=False) # connect us to the local SSH server

    def sendCommand(self, command):
        if(self.client):
            stdin, stdout, stderr = self.client.exec_command(command)

            if stdout is None or stdin is None or stderr is None:
                return
            while not stdout.channel.exit_status_ready():
                # Print data when available
                if stdout.channel.recv_ready():
                    alldata = stdout.channel.recv(1024)
                    prevdata = b"1"
                    while prevdata:
                        prevdata = stdout.channel.recv(1024)
                        alldata += prevdata

                    print(str(alldata, "utf8"))
        else:
            print("Connection not opened.")



connection = ssh("server_address","username","password")
connection.sendCommand("ls")

stdin, stdout, stderr = connection.sendCommand("su") # stdin: standard input; stdout: standard output; stderr: standard errors 

stdin.write('my_password')
stdin.flush()
connection.sendCommand("ls")

错误讯息:

stdin, stdout, stderr = connection.sendCommand("su") # stdin: standard input; stdout: standard output; stderr: standard errors
TypeError: 'NoneType' object is not iterable

搜索此错误消息后,表示数据为none。我糊涂了。任何人都可以帮我解决这个问题吗? PS:我知道还有其他一些方法可以做到这一点。我只是想知道,如果我想更新这段代码,那我该怎么办呢?

0 个答案:

没有答案