Docker服务容器应用程序日志收集自动化(按需)python

时间:2019-03-05 12:47:13

标签: python docker ssh paramiko docker-api

我想使用Docker service container Application log collection从远程服务器自动化python(按需)。我探索了Docker API是否可用于相同的地方,发现service container上没有它。然后我开始自动化Docker CLI

>>root@Workernode-01:~# docker exec -it 723acdcfe1ecf9875da166b2d8415837f3edc14227d4dfc610746af2500f683a bash 
>>root@723acdcfe1ec:/myapp #Inside Container
>>root@723acdcfe1ec:/myapp ls -l
-rw-r--r-- 1 root root  1893 Feb  8 12:35 config.py
-rw-r--r-- 1 root root  1851 Mar  4 06:54 config.pyc
-rw-r--r-- 1 root root 19681 Dec 27 21:33 execution_script.py
-rw-r--r-- 1 root root  4433 Dec 25 13:16 initial_script.py
-rw-r--r-- 1 root root 18484 Mar  5 12:22 app.log

我想从n获得最后app.log行。我尝试了相同的python模块paramiko,但是在执行Docker CLI时遇到了问题。

import paramiko
import socket

class AddNode():
    def __init__(self,host):
        self.ssh_output = None
        self.ssh_error = None
        self.client = None
        self.host = host
        self.username = 'root'
        self.password = 'hello@123'
        self.timeout = float(10)
        self.commands = ""
        self.port = 22
        self.label = None

    def connect(self):
        """Login to the remote server"""
        try:
            print "Establishing ssh connection"
            self.client = paramiko.SSHClient()
            # Parsing an instance of the AutoAddPolicy to set_missing_host_key_policy() changes it to allow any host.
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            # Connect to the server                
            self.client.connect(hostname=self.host, port=self.port, username=self.username, password=self.password,
                                timeout=self.timeout, allow_agent=False, look_for_keys=False)
            print "Connected to the server", self.host
        except paramiko.AuthenticationException:
            print "Authentication failed, please verify your credentials"
            result_flag = False
        except paramiko.SSHException as sshException:
            print "Could not establish SSH connection: %s" % sshException
            result_flag = False
        except socket.timeout as e:
            print "Connection timed out"
            result_flag = False
        except Exception, e:
            print("Exception in connecting to the server")
            print("Error:", e )
            result_flag = False
            self.client.close()
        else:
            result_flag = True

        return result_flag

    def execute_command(self, commands):  
        self.ssh_output = None
        result_flag = True
        try:
            if self.connect():
                for command in commands:
                    print "Executing command --> {}".format(command)
                    stdin, stdout, stderr = self.client.exec_command(command, timeout=10)
                    self.ssh_output = stdout.read()
                    self.ssh_error = stderr.read()
                    if self.ssh_error:
                        print "Problem occurred while running command:" + command + " The error is " + self.ssh_error
                        result_flag = False
                    else:
                        print "Command execution completed successfully", command

                #self.client.close()
            else:
                print "Could not establish SSH connection"
                result_flag = False
        except socket.timeout as e:
            print "Command timed out.", command
            self.client.close()
            result_flag = False
        except paramiko.SSHException:
            print "Failed to execute the command!", command
            self.client.close()
            result_flag = False

        return self.ssh_output,self.label 

try:
    obj = AddNode("100.102.130.140")
    commands = ["docker exec 723acdcfe1ecf9875da166b2d8415837f3edc14227d4dfc610746af2500f683a bash; ls -l" ]
    resultArr = obj.execute_command(commands)
    result = resultArr[0]
    print("Result:" ,result)


except Exception as e:
    print str(e)

0 个答案:

没有答案