首页 > 解决方案 > 如何进入 docker 容器并使用 Paramiko 模块在 Python 中重新启动服务?

问题描述

这是我试图用来重新启动服务的一段代码,但我无法做到。我正在使用 python 的 paramiko 模块通过进入服务的容器来重新启动服务。

def sshOpensips(ip):
        warnings.filterwarnings(action='ignore',module='.*paramiko.*')
        client = pm.SSHClient()
        commands = ["docker exec -it opensips bash", "service opensips restart"]
        client.set_missing_host_key_policy(pm.AutoAddPolicy())
        pk = pm.RSAKey.from_private_key(open('/home/asad.javed/.ssh/y'))
        try:
                client.connect(ip, username='asad.javed', pkey=pk)
                print("Connection Established")
        except pm.SSHException:
                print("Connection Failed")
        for command in commands:
                stdin, stdout, stderr = client.exec_command(command);
        client.close()
        return True

有人可以指导我如何通过进入 docker 容器来重新启动服务吗?

标签: python-3.xparamiko

解决方案


所以我上述问题的解决方案是:

def sshOpensips(ip):
        warnings.filterwarnings(action='ignore',module='.*paramiko.*')
        command = ('docker exec opensips /bin/bash -c \"systemctl restart opensips\" && echo Opensips has restarted')
        client = pm.SSHClient()
        client.set_missing_host_key_policy(pm.AutoAddPolicy())
        pk = pm.RSAKey.from_private_key(open('/root/.ssh/id_rsa'))
        try:
                client.connect(ip, username='asad.javed', pkey=pk)
        except pm.SSHException:
                print("Connection Failed")
        session = client.get_transport().open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        session.exec_command(command)
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        kr.get_password("Opensips", "asad.javed")
        time.sleep(2)
        print(stdout.read().decode("utf-8"))
        for line in stdout.readlines():
                print(line.strip());

        exit_status = stdout.channel.recv_exit_status()

        if exit_status == 0:
                print("Command Executed")
        else:
                print("Error", exit_status)

        session.close()
        client.close()

对于将来遇到类似问题的任何人,都可以使用此解决方案在 docker 容器中执行命令。这个 Paramiko 和 Keyring 需要两个模块。


推荐阅读