在交互式ssh模式下在进程内调用多个命令

时间:2019-04-02 07:37:16

标签: python shell ssh paramiko

我开始使用paramiko从计算机上的python脚本调用服务器上的命令。

我编写了以下代码:

from paramiko import client

class ssh:
    client = None

    def __init__(self, address, port, username="user", password="password"):
        # Let the user know we're connecting to the server
        print("Connecting to server.")
        # Create a new SSH client
        self.client = client.SSHClient()
        # The following line is required if you want the script to be able to access a server that's not yet in the known_hosts file
        self.client.set_missing_host_key_policy(client.AutoAddPolicy())
        # Make the connection
        self.client.connect(address, port, username=username, password=password, look_for_keys=False)

    def sendcommand(self, command):
        # Check if connection is made previously
        if self.client is not None:
            stdin, stdout, stderr = self.client.exec_command(command)
            while not stdout.channel.exit_status_ready():
                # Print stdout data when available
                if stdout.channel.recv_ready():
                    # Retrieve the first 1024 bytes
                    _data = stdout.channel.recv(1024)
                    while stdout.channel.recv_ready():
                        # Retrieve the next 1024 bytes
                        _data += stdout.channel.recv(1024)

                    # Print as string with utf8 encoding
                    print(str(_data, "utf8"))
        else:
            print("Connection not opened.")


    def closeconnection(self):
        if self.client is not None:
            self.client.close()

def main():
    connection = ssh('10.40.2.222', 2022 , "user" , "password")
    connection.sendcommand("cd /opt/process/bin/; ./process_cli; scm")    
    print("here")

    #connection.sendcommand("yes")
    #connection.sendcommand("nsgadmin")
    #connection.sendcommand("ls")

    connection.closeconnection()

if __name__ == '__main__':
    main()

现在,我要发送到服务器(scm)的命令中的最后一个命令是应该发送到我在服务器中运行的进程“ process_cli”的命令,并且应该向我输出该进程的输出(该过程从服务器外壳的标准输入获取输入,并将输出打印到服务器外壳的标准输出)。
当我以交互方式运行时,一切正常,但是当我运行脚本时,可以成功连接到服务器并在该服务器上运行所有基本的shell命令(例如:ls,pwd等),但是我无法运行任何命令在此服务器内部运行的进程上。

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

SSH“ exec”通道(由SSHClient.exec_command使用)在单独的shell中执行每个命令。结果:

  1. cd /opt/process/bin/./process_cli完全无效。
  2. scm将作为shell命令而不是process_cli的子命令被执行。

您需要:

  1. cdprocess_cli作为一个命令(在同一shell中)执行:

    stdin, stdout, stderr = client.exec_command('cd /opt/process/bin/ && ./process_cli') 
    

    stdin, stdout, stderr = client.exec_command('/opt/process/bin/process_cli') 
    
  2. process_cli的(子)命令馈送到其标准输入:

    stdin.write('scm\n')
    stdin.flush()
    

类似的问题: