복붙노트

[PYTHON] Python Paramiko를 사용하여 SSH를 통해 명령 / 스크립트에 입력 / 변수 전달

PYTHON

Python Paramiko를 사용하여 SSH를 통해 명령 / 스크립트에 입력 / 변수 전달

SSH를 통해 원격 서버의 bash 스크립트에 응답을 전달하는 데 문제가 있습니다.

나는 파이썬 3.6.5에서 원격 리눅스 서버로 SSH 할 프로그램을 작성 중이다. 이 원격 Linux 서버에는 필자가 입력해야하는 bash 스크립트가 있습니다. 어떤 이유로 든 원래 파이썬 프로그램에서 SSH를 통해 사용자 입력을 전달할 수 없으며 bash 스크립트 사용자 입력 질문을 채 웁니다.

main.py

from tkinter import *
import SSH

hostname = 'xxx'
username = 'xxx'
password = 'xxx'

class Connect:
    def module(self):
        name = input()
        connection = SSH.SSH(hostname, username, password)
        connection.sendCommand(
            'cd xx/{}/xxxxx/ && source .cshrc && ./xxx/xxxx/xxxx/xxxxx'.format(path))

SSH.py

from paramiko import client

class SSH:

    client = None

    def __init__(self, address, username, password):
        print("Login info sent.")
        print("Connecting to server.")
        self.client = client.SSHClient()    # Create a new SSH client
        self.client.set_missing_host_key_policy(client.AutoAddPolicy())
        self.client.connect(
            address, username=username, password=password, look_for_keys=False) # connect

    def sendCommand(self, command):
        print("Sending your command")
        # Check if connection is made previously
        if (self.client):
            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
                    alldata = stdout.channel.recv(1024)
                    while stdout.channel.recv_ready():
                        # Retrieve the next 1024 bytes
                        alldata += stdout.channel.recv(1024)


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

Connect 클래스의 마지막 / xxxxxx는 시작되는 원격 스크립트입니다. 다음과 같은 형식을 기다리는 텍스트 응답을 엽니 다.

Connect 클래스 내 main.py 파일의 스크립트에 응답을 제대로 전달하는 방법을 찾지 못하는 것 같습니다.

내가 인수 또는 변수로 이름을 전달하려고 시도한 모든 방법은 대답이 사라지는 것처럼 보입니다 (Linux 프롬프트에서 인쇄하고 bash 스크립트에서 인쇄하지 않으려 고 할 가능성이 있음)

read_until 함수를 사용하여 :를 찾으면 문제의 끝에서 작동한다고 생각합니다.

제안?

해결법

  1. ==============================

    1.명령이 표준 입력에 필요로하는 입력을 작성하십시오.

    명령이 표준 입력에 필요로하는 입력을 작성하십시오.

    stdin, stdout, stderr = self.client.exec_command(command)
    stdin.write(name + '\n')
    stdin.flush()
    

    물론 모듈에서 name 변수를 sendCommand로 전파해야하지만,이 부분을 수행하는 방법을 알고 있다고 가정합니다.

  2. from https://stackoverflow.com/questions/50749745/pass-input-variables-to-command-script-over-ssh-using-python-paramiko by cc-by-sa and MIT license