python-3.x - 如何进入 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 容器来重新启动服务吗?
解决方案
所以我上述问题的解决方案是:
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 需要两个模块。
推荐阅读
- google-bigquery - BigQuery 似乎每两个月就会删除一次从 Segment 传输的数据
- javascript - 是否可以返回字符串和数字实例的原始值?
- c - C 程序:[Done] 在 2.322 秒内以 code=3221225477 退出(Calloc / Free / Segmenation Error?)
- python - blit_buffer 函数在没有任何警告的情况下关闭 Kivy 应用程序
- c - 单独编译代码中结构的二进制兼容性
- git - 如何接管别人的开放拉取请求?
- vue.js - 如何仅在 vuejs 中上传图像文件?
- powerbi - 忽略选择“DAX 函数全部”不起作用
- flutter - 在 null 上调用了方法“addProduct”
- javascript - HTML 脚本标签未在 IE 中运行