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

            
                    
我开始使用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等),但是我无法运行任何命令在该服务器内部运行的进程上。

如何解决此问题?

参考方案

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

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

你需要:

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') 

process_cli的(子)命令输入其标准输入:

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

类似问题:

Execute multiple commands in Paramiko so that commands are affected by their predecessors
Execute (sub)commands in secondary shell/command on SSH server in Paramiko

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…