简体   繁体   中英

How do I go inside a docker container and restart a service in Python using Paramiko module?

This is my piece of code that I am trying to use to restart a service but I am not able to. I am using python's paramiko module to restart a service by going into the container of the service.

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

Can someone please guide how can I restart a service by going into a docker container?

So the solution to my above problem was:

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

For anyone who faces a similar issue in the future can use this solution to execute command in docker container. Two modules would be required for this Paramiko and Keyring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM