gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:05:03 24 4
gpt4 key购买 nike

我开始使用 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 的 stdin 获取输入,并将输出打印到服务器 shell 的 stdout)。
当我以交互模式运行时,一切正常,但是当我运行脚本时,我成功连接到我的服务器并在此服务器上运行所有基本 shell 命令(例如: ls 、 pwd 等),但我无法运行任何命令在此服务器内运行的进程上。

如何解决这个问题?

最佳答案

SSH“exec” channel (由 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()

类似问题:

关于python - 以交互式 ssh 模式在进程内调用多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55469294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com